1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-10 16:11:13 -05:00

Update eslint and @typescript-eslint (denoland/deno_std#621)

Original: c3fe858f98
This commit is contained in:
Yoshiya Hinosawa 2019-10-06 01:02:34 +09:00 committed by Ryan Dahl
parent 2f90225c89
commit 96fe2d10a4
54 changed files with 204 additions and 188 deletions

View file

@ -1,5 +1,5 @@
steps:
- bash: npm install eslint@5.16.0 typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@1.13.0 @typescript-eslint/parser@1.13.0 eslint-config-prettier
- bash: npm install eslint@$(ESLINT_VERSION) typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@$(TS_ESLINT_VERSION) @typescript-eslint/parser@$(TS_ESLINT_VERSION) eslint-config-prettier
- template: ./template.unix.yml
- bash: npx eslint **/*.ts --max-warnings=0
- bash: npx eslint "**/*.ts" --max-warnings=0
- template: ./template.common.yml

View file

@ -1,6 +1,8 @@
steps:
- bash: npm install -g functional-red-black-tree
- bash: npm -g install eslint@5.16.0 typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@1.13.0 @typescript-eslint/parser@1.13.0 eslint-config-prettier
- task: NodeTool@0
inputs:
versionSpec: '10.x'
- bash: npm install eslint@$(ESLINT_VERSION) typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@$(TS_ESLINT_VERSION) @typescript-eslint/parser@$(TS_ESLINT_VERSION) eslint-config-prettier
- template: ./template.unix.yml
- bash: eslint **/*.ts --max-warnings=0
- bash: npx eslint "**/*.ts" --max-warnings=0
- template: ./template.common.yml

View file

@ -1,8 +1,8 @@
steps:
- bash: npm install eslint@5.16.0 typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@1.13.0 @typescript-eslint/parser@1.13.0 eslint-config-prettier
- bash: npm install eslint@$(ESLINT_VERSION) typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@$(TS_ESLINT_VERSION) @typescript-eslint/parser@$(TS_ESLINT_VERSION) eslint-config-prettier
- powershell: iwr https://deno.land/x/install/install.ps1 -out install.ps1; .\install.ps1 $(DENO_VERSION)
- bash: echo "##vso[task.prependpath]C:\Users\VssAdministrator\.deno\\bin"
- bash: npx eslint **/*.ts --max-warnings=0
- bash: npx eslint "**/*.ts" --max-warnings=0
- template: ./template.common.yml
parameters:
exe_suffix: ".exe"
exe_suffix: ".exe"

4
.eslintignore Normal file
View file

@ -0,0 +1,4 @@
/deno.d.ts
/prettier/vendor
**/testdata/

View file

@ -2,7 +2,8 @@
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
"project": "./tsconfig.json",
"createDefaultProgram": true
},
"plugins": ["@typescript-eslint"],
"extends": [
@ -11,7 +12,7 @@
"prettier/@typescript-eslint"
],
"rules": {
"@typescript-eslint/array-type": ["error", "array-simple"],
"@typescript-eslint/array-type": ["error", { "default": "array-simple" }],
"@typescript-eslint/explicit-member-accessibility": ["off"],
"@typescript-eslint/no-non-null-assertion": ["off"],
"@typescript-eslint/no-parameter-properties": ["off"],
@ -19,6 +20,8 @@
"error",
{ "argsIgnorePattern": "^_", "varsIgnorePattern": "_" }
],
"@typescript-eslint/ban-ts-ignore": ["off"],
"@typescript-eslint/no-empty-function": ["off"],
"max-len": [
"error",
{

View file

@ -96,7 +96,7 @@ function clean(length: number): Uint8Array {
}
function pad(num: number, bytes: number, base?: number): string {
var numString = num.toString(base || 8);
const numString = num.toString(base || 8);
return "000000000000".substr(numString.length + 12 - bytes) + numString;
}
@ -328,7 +328,7 @@ export class Tar {
// set meta data
const info = opts.filePath && (await Deno.stat(opts.filePath));
let mode =
const mode =
opts.fileMode || (info && info.mode) || parseInt("777", 8) & 0xfff,
mtime =
opts.mtime ||
@ -385,8 +385,9 @@ export class Tar {
getReader(): Deno.Reader {
const readers: Deno.Reader[] = [];
this.data.forEach((tarData): void => {
let { filePath, reader } = tarData,
headerArr = formatHeader(tarData);
let { reader } = tarData;
const { filePath } = tarData;
const headerArr = formatHeader(tarData);
readers.push(new Deno.Buffer(headerArr));
if (!reader) {
reader = new FileReader(filePath!);

View file

@ -1,6 +1,8 @@
variables:
DENO_VERSION: "v0.19.0"
TS_VERSION: "3.4.5"
ESLINT_VERSION: "6.5.1"
TS_ESLINT_VERSION: "2.3.2"
# TODO Try to get eslint to run under Deno, like prettier
jobs:

View file

@ -12,6 +12,7 @@ import { instantiate, load, ModuleMetaData } from "./utils.ts";
/* eslint-disable @typescript-eslint/no-namespace */
declare global {
namespace globalThis {
// eslint-disable-next-line no-var
var __results: [string, string] | undefined;
}
}

View file

@ -23,6 +23,7 @@ type Define = (
/* eslint-disable @typescript-eslint/no-namespace */
declare global {
namespace globalThis {
// eslint-disable-next-line no-var
var define: Define | undefined;
}
}

View file

@ -118,7 +118,7 @@ export function currentDayOfYear(): number {
* @return IMF date formated string
*/
export function toIMF(date: Date): string {
function dtPad(v: string, lPad: number = 2): string {
function dtPad(v: string, lPad = 2): string {
return pad(v, lPad, { char: "0" });
}
const d = dtPad(date.getUTCDate().toString());

View file

@ -56,7 +56,7 @@ async function read(
const tp = new TextProtoReader(reader);
let line: string;
let result: string[] = [];
let lineIndex = Startline;
const lineIndex = Startline;
const r = await tp.readLine();
if (r === Deno.EOF) return Deno.EOF;
@ -229,7 +229,7 @@ export async function parse(
throw `Error number of fields line:${i}`;
}
i++;
let out: Record<string, unknown> = {};
const out: Record<string, unknown> = {};
for (let j = 0; j < e.length; j++) {
const h = headers[j];
if (h.parse) {

View file

@ -85,7 +85,7 @@ export function decode(
dst: Uint8Array,
src: Uint8Array
): [number, Error | void] {
var i = 0;
let i = 0;
for (; i < Math.floor(src.length / 2); i++) {
const [a, aOK] = fromHexChar(src[i * 2]);
if (!aOK) {

View file

@ -64,8 +64,8 @@ class Parser {
return line.match(/'''/) ? true : false;
}
let merged = [],
acc = [],
const merged = [];
let acc = [],
isLiteral = false,
capture = false,
captureType = "",
@ -123,14 +123,14 @@ class Parser {
this.tomlLines = merged;
}
_unflat(keys: string[], values: object = {}, cObj: object = {}): object {
let out: Record<string, unknown> = {};
const out: Record<string, unknown> = {};
if (keys.length === 0) {
return cObj;
} else {
if (Object.keys(cObj).length === 0) {
cObj = values;
}
let key: string | undefined = keys.pop();
const key: string | undefined = keys.pop();
if (key) {
out[key] = cObj;
}
@ -152,7 +152,7 @@ class Parser {
delete this.context.currentGroup;
}
_split(str: string): string[] {
let out = [];
const out = [];
out.push(...str.split("\n"));
return out;
}
@ -233,8 +233,8 @@ class Parser {
const reg = /([a-zA-Z0-9-_\.]*) (=)/gi;
let result;
while ((result = reg.exec(dataString))) {
let ogVal = result[0];
let newVal = ogVal
const ogVal = result[0];
const newVal = ogVal
.replace(result[1], `"${result[1]}"`)
.replace(result[2], ":");
dataString = dataString.replace(ogVal, newVal);
@ -332,9 +332,9 @@ class Parser {
}
}
if (this._isDeclaration(line)) {
let kv = this._processDeclaration(line);
let key = kv.key;
let value = kv.value;
const kv = this._processDeclaration(line);
const key = kv.key;
const value = kv.value;
if (!this.context.currentGroup) {
this.context.output[key] = value;
} else {
@ -360,7 +360,7 @@ class Parser {
let k = keys[i];
if (k) {
let v = obj[k];
let pathDeclaration = this._parseDeclarationName(k);
const pathDeclaration = this._parseDeclarationName(k);
delete obj[k];
if (pathDeclaration.length > 1) {
const shift = pathDeclaration.shift();
@ -400,7 +400,7 @@ function joinKeys(keys: string[]): string {
}
class Dumper {
maxPad: number = 0;
maxPad = 0;
srcObject: object;
output: string[] = [];
constructor(srcObjc: object) {
@ -507,11 +507,11 @@ class Dumper {
}
}
_dateDeclaration(keys: string[], value: Date): string {
function dtPad(v: string, lPad: number = 2): string {
function dtPad(v: string, lPad = 2): string {
return pad(v, lPad, { char: "0" });
}
let m = dtPad((value.getUTCMonth() + 1).toString());
let d = dtPad(value.getUTCDate().toString());
const m = dtPad((value.getUTCMonth() + 1).toString());
const d = dtPad(value.getUTCDate().toString());
const h = dtPad(value.getUTCHours().toString());
const min = dtPad(value.getUTCMinutes().toString());
const s = dtPad(value.getUTCSeconds().toString());

View file

@ -1,7 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
async function cat(filenames: string[]): Promise<void> {
for (let filename of filenames) {
let file = await Deno.open(filename);
for (const filename of filenames) {
const file = await Deno.open(filename);
await Deno.copy(Deno.stdout, file);
file.close();
}

View file

@ -53,11 +53,11 @@ async function main(): Promise<void> {
});
if (res.ok) {
let resObj = await res.json();
const resObj = await res.json();
console.log("Success");
console.log(resObj["html_url"]);
} else {
let err = await res.text();
const err = await res.text();
console.error("Failure to POST", err);
}
}

View file

@ -286,7 +286,7 @@ export function parse(
argv._.push(flags.strings["_"] || !isNumber(arg) ? arg : Number(arg));
}
if (options.stopEarly) {
argv._.push.apply(argv._, args.slice(i + 1));
argv._.push(...args.slice(i + 1));
break;
}
}

View file

@ -17,8 +17,8 @@ class Flags {
space?: boolean;
zero?: boolean;
lessthan?: boolean;
width: number = -1;
precision: number = -1;
width = -1;
precision = -1;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -44,9 +44,9 @@ class Printf {
i: number;
state: State = State.PASSTHROUGH;
verb: string = "";
buf: string = "";
argNum: number = 0;
verb = "";
buf = "";
argNum = 0;
flags: Flags = new Flags();
haveSeen: boolean[];
@ -64,7 +64,7 @@ class Printf {
doPrintf(): string {
for (; this.i < this.format.length; ++this.i) {
let c = this.format[this.i];
const c = this.format[this.i];
switch (this.state) {
case State.PASSTHROUGH:
if (c === "%") {
@ -104,9 +104,9 @@ class Printf {
// %[<positional>]<flag>...<verb>
handleFormat(): void {
this.flags = new Flags();
let flags = this.flags;
const flags = this.flags;
for (; this.i < this.format.length; ++this.i) {
let c = this.format[this.i];
const c = this.format[this.i];
switch (this.state) {
case State.PERCENT:
switch (c) {
@ -152,7 +152,7 @@ class Printf {
break;
case State.POSITIONAL: // either a verb or * only verb for now, TODO
if (c === "*") {
let worp =
const worp =
this.flags.precision === -1 ? WorP.WIDTH : WorP.PRECISION;
this.handleWidthOrPrecisionRef(worp);
this.state = State.PERCENT;
@ -171,7 +171,7 @@ class Printf {
// handle Positional should have already taken care of it...
return;
}
let arg = this.args[this.argNum];
const arg = this.args[this.argNum];
this.haveSeen[this.argNum] = true;
if (typeof arg === "number") {
switch (wOrP) {
@ -182,7 +182,7 @@ class Printf {
this.flags.precision = arg;
}
} else {
let tmp = wOrP === WorP.WIDTH ? "WIDTH" : "PREC";
const tmp = wOrP === WorP.WIDTH ? "WIDTH" : "PREC";
this.tmpError = `%!(BAD ${tmp} '${this.args[this.argNum]}')`;
}
this.argNum++;
@ -271,7 +271,7 @@ class Printf {
return;
}
handleLessThan(): string {
let arg = this.args[this.argNum];
const arg = this.args[this.argNum];
if ((arg || {}).constructor.name !== "Array") {
throw new Error(`arg ${arg} is not an array. Todo better error handling`);
}
@ -294,7 +294,7 @@ class Printf {
} else if (this.args.length <= this.argNum) {
this.buf += `%!(MISSING '${verb}')`;
} else {
let arg = this.args[this.argNum]; // check out of range
const arg = this.args[this.argNum]; // check out of range
this.haveSeen[this.argNum] = true; // keep track of used args
if (this.flags.lessthan) {
this.buf += this.handleLessThan();
@ -404,7 +404,7 @@ class Printf {
return nStr;
}
fmtNumber(n: number, radix: number, upcase: boolean = false): string {
fmtNumber(n: number, radix: number, upcase = false): string {
let num = Math.abs(n).toString(radix);
const prec = this.flags.precision;
if (prec !== -1) {
@ -484,7 +484,7 @@ class Printf {
return fractional;
}
fmtFloatE(n: number, upcase: boolean = false): string {
fmtFloatE(n: number, upcase = false): string {
const special = this.fmtFloatSpecial(n);
if (special !== "") {
return special;
@ -553,7 +553,7 @@ class Printf {
return this.padNum(`${dig}.${fractional}`, n < 0);
}
fmtFloatG(n: number, upcase: boolean = false): string {
fmtFloatG(n: number, upcase = false): string {
const special = this.fmtFloatSpecial(n);
if (special !== "") {
return special;
@ -591,7 +591,7 @@ class Printf {
throw Error("can't happen");
}
let X = parseInt(m[F.exponent]) * (m[F.esign] === "-" ? -1 : 1);
const X = parseInt(m[F.exponent]) * (m[F.esign] === "-" ? -1 : 1);
let nStr = "";
if (P > X && X >= -4) {
this.flags.precision = P - (X + 1);
@ -616,14 +616,14 @@ class Printf {
return this.pad(s);
}
fmtHex(val: string | number, upper: boolean = false): string {
fmtHex(val: string | number, upper = false): string {
// allow others types ?
switch (typeof val) {
case "number":
return this.fmtNumber(val as number, 16, upper);
break;
case "string":
let sharp = this.flags.sharp && val.length !== 0;
const sharp = this.flags.sharp && val.length !== 0;
let hex = sharp ? "0x" : "";
const prec = this.flags.precision;
const end = prec !== -1 ? min(prec, val.length) : val.length;
@ -634,7 +634,7 @@ class Printf {
// TODO: for now only taking into account the
// lower half of the codePoint, ie. as if a string
// is a list of 8bit values instead of UCS2 runes
let c = (val.charCodeAt(i) & 0xff).toString(16);
const c = (val.charCodeAt(i) & 0xff).toString(16);
hex += c.length === 1 ? `0${c}` : c;
}
if (upper) {
@ -652,7 +652,7 @@ class Printf {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fmtV(val: any): string {
if (this.flags.sharp) {
let options =
const options =
this.flags.precision !== -1 ? { depth: this.flags.precision } : {};
return this.pad(Deno.inspect(val, options));
} else {
@ -669,6 +669,6 @@ class Printf {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function sprintf(format: string, ...args: any[]): string {
let printf = new Printf(format, ...args);
const printf = new Printf(format, ...args);
return printf.doPrintf();
}

View file

@ -3,7 +3,7 @@ import { sprintf } from "./sprintf.ts";
import { assertEquals } from "../testing/asserts.ts";
import { test, runIfMain } from "../testing/mod.ts";
let S = sprintf;
const S = sprintf;
test(function noVerb(): void {
assertEquals(sprintf("bla"), "bla");
@ -589,8 +589,8 @@ const tests: Array<[string, any, string]> = [
test(function testThorough(): void {
tests.forEach((t, i): void => {
// p(t)
let is = S(t[0], t[1]);
let should = t[2];
const is = S(t[0], t[1]);
const should = t[2];
assertEquals(
is,
should,
@ -608,7 +608,7 @@ test(function testWeirdos(): void {
});
test(function formatV(): void {
let a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } };
const a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } };
assertEquals(S("%v", a), "[object Object]");
assertEquals(S("%#v", a), "{ a: { a: { a: { a: [Object] } } } }");
assertEquals(
@ -619,18 +619,18 @@ test(function formatV(): void {
});
test(function formatJ(): void {
let a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } };
const a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } };
assertEquals(S("%j", a), `{"a":{"a":{"a":{"a":{"a":{"a":{"a":{}}}}}}}}`);
});
test(function flagLessThan(): void {
let a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } };
let aArray = [a, a, a];
const a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } };
const aArray = [a, a, a];
assertEquals(
S("%<#.1v", aArray),
"[ { a: [Object] }, { a: [Object] }, { a: [Object] } ]"
);
let fArray = [1.2345, 0.98765, 123456789.5678];
const fArray = [1.2345, 0.98765, 123456789.5678];
assertEquals(S("%<.2f", fArray), "[ 1.23, 0.99, 123456789.57 ]");
});

View file

@ -21,11 +21,9 @@ async function ensureValidCopy(
src: string,
dest: string,
options: CopyOptions,
isCopyFolder: boolean = false
isCopyFolder = false
): Promise<Deno.FileInfo> {
let destStat: Deno.FileInfo | null;
destStat = await Deno.lstat(dest).catch(
const destStat: Deno.FileInfo | null = await Deno.lstat(dest).catch(
(): Promise<null> => Promise.resolve(null)
);
@ -47,7 +45,7 @@ function ensureValidCopySync(
src: string,
dest: string,
options: CopyOptions,
isCopyFolder: boolean = false
isCopyFolder = false
): Deno.FileInfo {
let destStat: Deno.FileInfo | null;

View file

@ -112,7 +112,7 @@ export function joinGlobs(
if (globs.length === 0) return ".";
let joined: string | undefined;
for (const glob of globs) {
let path = glob;
const path = glob;
if (path.length > 0) {
if (!joined) joined = path;
else joined += `${SEP}${path}`;

View file

@ -127,7 +127,7 @@ export function globrex(
if (c === ")") {
if (ext.length) {
add(c);
let type: string | undefined = ext.pop();
const type: string | undefined = ext.pop();
if (type === "@") {
add("{1}");
} else if (type === "!") {
@ -264,19 +264,19 @@ export function globrex(
}
// Move over all consecutive "*"'s.
// Also store the previous and next characters
let prevChar = glob[i - 1];
const prevChar = glob[i - 1];
let starCount = 1;
while (glob[i + 1] === "*") {
starCount++;
i++;
}
let nextChar = glob[i + 1];
const nextChar = glob[i + 1];
if (!globstar) {
// globstar is disabled, so treat any number of "*" as one
add(".*");
} else {
// globstar is enabled, so determine if this is a globstar segment
let isGlobstar =
const isGlobstar =
starCount > 1 && // multiple "*"'s
// from the start of the segment
[SEP_RAW, "/", undefined].includes(prevChar) &&

View file

@ -19,14 +19,14 @@ function match(
opts = strWin;
strWin = "";
}
let res = globrex(glob, opts);
const res = globrex(glob, opts);
return res.regex.test(isWin && strWin ? strWin : strUnix);
}
test({
name: "globrex: standard",
fn(): void {
let res = globrex("*.js");
const res = globrex("*.js");
t.equal(typeof globrex, "function", "constructor is a typeof function");
t.equal(res instanceof Object, true, "returns object");
t.equal(res.regex.toString(), "/^.*\\.js$/", "returns regex object");

View file

@ -1,5 +1,7 @@
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
/* eslint-disable @typescript-eslint/no-explicit-any */
// TODO(kt3k): fix any types in this file
import { test } from "../../testing/mod.ts";
import { assertEquals } from "../../testing/asserts.ts";
@ -80,7 +82,7 @@ const unixSpecialCaseFormatTests = [
];
function checkParseFormat(path: any, paths: any): void {
paths.forEach(function(p: Record<string, unknown>[]) {
paths.forEach(function(p: Array<Record<string, unknown>>) {
const element = p[0];
const output = path.parse(element);
assertEquals(typeof output.root, "string");
@ -96,7 +98,7 @@ function checkParseFormat(path: any, paths: any): void {
}
function checkSpecialCaseParseFormat(path: any, testCases: any): void {
testCases.forEach(function(testCase: Record<string, unknown>[]) {
testCases.forEach(function(testCase: Array<Record<string, unknown>>) {
const element = testCase[0];
const expect = testCase[1];
const output = path.parse(element);

View file

@ -83,7 +83,7 @@ export function join(...paths: string[]): string {
if (paths.length === 0) return ".";
let joined: string | undefined;
for (let i = 0, len = paths.length; i < len; ++i) {
let path = paths[i];
const path = paths[i];
assertPath(path);
if (path.length > 0) {
if (!joined) joined = path;
@ -107,11 +107,11 @@ export function relative(from: string, to: string): string {
// Trim any leading backslashes
let fromStart = 1;
let fromEnd = from.length;
const fromEnd = from.length;
for (; fromStart < fromEnd; ++fromStart) {
if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break;
}
let fromLen = fromEnd - fromStart;
const fromLen = fromEnd - fromStart;
// Trim any leading backslashes
let toStart = 1;
@ -119,10 +119,10 @@ export function relative(from: string, to: string): string {
for (; toStart < toEnd; ++toStart) {
if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break;
}
let toLen = toEnd - toStart;
const toLen = toEnd - toStart;
// Compare paths to find the longest common path from root
let length = fromLen < toLen ? fromLen : toLen;
const length = fromLen < toLen ? fromLen : toLen;
let lastCommonSep = -1;
let i = 0;
for (; i <= length; ++i) {
@ -150,8 +150,8 @@ export function relative(from: string, to: string): string {
}
break;
}
let fromCode = from.charCodeAt(fromStart + i);
let toCode = to.charCodeAt(toStart + i);
const fromCode = from.charCodeAt(fromStart + i);
const toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode) break;
else if (fromCode === CHAR_FORWARD_SLASH) lastCommonSep = i;
}
@ -328,6 +328,7 @@ export function extname(path: string): string {
}
export function format(pathObject: FormatInputPathObject): string {
/* eslint-disable max-len */
if (pathObject === null || typeof pathObject !== "object") {
throw new TypeError(
`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`
@ -339,9 +340,9 @@ export function format(pathObject: FormatInputPathObject): string {
export function parse(path: string): ParsedPath {
assertPath(path);
let ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" };
const ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" };
if (path.length === 0) return ret;
let isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
let start: number;
if (isAbsolute) {
ret.root = "/";

View file

@ -304,7 +304,7 @@ export function join(...paths: string[]): string {
let joined: string | undefined;
let firstPart: string;
for (let i = 0; i < pathsCount; ++i) {
let path = paths[i];
const path = paths[i];
assertPath(path);
if (path.length > 0) {
if (joined === undefined) joined = firstPart = path;
@ -369,8 +369,8 @@ export function relative(from: string, to: string): string {
if (from === to) return "";
let fromOrig = resolve(from);
let toOrig = resolve(to);
const fromOrig = resolve(from);
const toOrig = resolve(to);
if (fromOrig === toOrig) return "";
@ -389,7 +389,7 @@ export function relative(from: string, to: string): string {
for (; fromEnd - 1 > fromStart; --fromEnd) {
if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break;
}
let fromLen = fromEnd - fromStart;
const fromLen = fromEnd - fromStart;
// Trim any leading backslashes
let toStart = 0;
@ -401,10 +401,10 @@ export function relative(from: string, to: string): string {
for (; toEnd - 1 > toStart; --toEnd) {
if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break;
}
let toLen = toEnd - toStart;
const toLen = toEnd - toStart;
// Compare paths to find the longest common path from root
let length = fromLen < toLen ? fromLen : toLen;
const length = fromLen < toLen ? fromLen : toLen;
let lastCommonSep = -1;
let i = 0;
for (; i <= length; ++i) {
@ -433,8 +433,8 @@ export function relative(from: string, to: string): string {
}
break;
}
let fromCode = from.charCodeAt(fromStart + i);
let toCode = to.charCodeAt(toStart + i);
const fromCode = from.charCodeAt(fromStart + i);
const toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode) break;
else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i;
}
@ -737,6 +737,7 @@ export function extname(path: string): string {
}
export function format(pathObject: FormatInputPathObject): string {
/* eslint-disable max-len */
if (pathObject === null || typeof pathObject !== "object") {
throw new TypeError(
`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`
@ -748,7 +749,7 @@ export function format(pathObject: FormatInputPathObject): string {
export function parse(path: string): ParsedPath {
assertPath(path);
let ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" };
const ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" };
const len = path.length;
if (len === 0) return ret;

View file

@ -27,7 +27,8 @@ test(function normalizeZeroLength() {
});
test(function isAbsoluteZeroLength() {
// Since '' is not a valid path in any of the common environments, return false
// Since '' is not a valid path in any of the common environments,
// return false
assertEquals(path.posix.isAbsolute(""), false);
if (path.win32) assertEquals(path.win32.isAbsolute(""), false);
});
@ -40,7 +41,8 @@ test(function resolveZeroLength() {
});
test(function relativeZeroLength() {
// relative, internally calls resolve. So, '' is actually the current directory
// relative, internally calls resolve. So, '' is actually the current
// directory
assertEquals(path.relative("", pwd), "");
assertEquals(path.relative(pwd, ""), "");
assertEquals(path.relative(pwd, pwd), "");

View file

@ -22,7 +22,7 @@ function patternTest(patterns: RegExp[], path: string): boolean {
// consistent results.
// See: https://stackoverflow.com/a/1520853
return patterns.some((pattern): boolean => {
let r = pattern.test(path);
const r = pattern.test(path);
pattern.lastIndex = 0;
return r;
});
@ -100,7 +100,7 @@ export async function* walk(
options.onError(err);
}
}
for (let info of ls) {
for (const info of ls) {
if (info.isSymlink()) {
if (options.followSymlinks) {
// TODO(ry) Re-enable followSymlinks.
@ -154,7 +154,7 @@ export function* walkSync(
options.onError(err);
}
}
for (let info of ls) {
for (const info of ls) {
if (info.isSymlink()) {
if (options.followSymlinks) {
unimplemented();

View file

@ -59,7 +59,7 @@ function toString(cookie: Cookie): string {
out.push(`Path=${cookie.path}`);
}
if (cookie.expires) {
let dateString = toIMF(cookie.expires);
const dateString = toIMF(cookie.expires);
out.push(`Expires=${dateString}`);
}
if (cookie.unparsed) {

View file

@ -7,7 +7,7 @@ import { test } from "../testing/mod.ts";
test({
name: "[HTTP] Cookie parser",
fn(): void {
let req = new ServerRequest();
const req = new ServerRequest();
req.headers = new Headers();
assertEquals(getCookies(req), {});
req.headers = new Headers();
@ -35,7 +35,7 @@ test({
test({
name: "[HTTP] Cookie Delete",
fn(): void {
let res: Response = {};
const res: Response = {};
delCookie(res, "deno");
assertEquals(
res.headers!.get("Set-Cookie"),
@ -47,7 +47,7 @@ test({
test({
name: "[HTTP] Cookie Set",
fn(): void {
let res: Response = {};
const res: Response = {};
res.headers = new Headers();
setCookie(res, { name: "Space", value: "Cat" });

View file

@ -150,7 +150,7 @@ async function serveDir(
const fileInfos = await readDir(dirPath);
for (const fileInfo of fileInfos) {
const filePath = posix.join(dirPath, fileInfo.name);
let fileUrl = posix.join(dirUrl, fileInfo.name);
const fileUrl = posix.join(dirUrl, fileInfo.name);
if (fileInfo.name === "index.html" && fileInfo.isFile()) {
// in case index.html as dir...
return await serveFile(req, filePath);

View file

@ -21,7 +21,7 @@ function killServer(): void {
server.stdout!.close();
}
let input = `GET / HTTP/1.1
const input = `GET / HTTP/1.1
GET / HTTP/1.1
@ -31,7 +31,7 @@ GET / HTTP/1.1
`;
const HUGE_BODY_SIZE = 1024 * 1024;
let output = `HTTP/1.1 200 OK
const output = `HTTP/1.1 200 OK
content-length: 8
Hello 1

View file

@ -139,7 +139,7 @@ export class ServerRequest {
let line = await tp.readLine();
if (line === Deno.EOF) throw new UnexpectedEOFError();
// TODO: handle chunk extension
let [chunkSizeString] = line.split(";");
const [chunkSizeString] = line.split(";");
let chunkSize = parseInt(chunkSizeString, 16);
if (Number.isNaN(chunkSize) || chunkSize < 0) {
throw new Error("Invalid chunk size");
@ -157,7 +157,7 @@ export class ServerRequest {
}
const entityHeaders = await tp.readMIMEHeader();
if (entityHeaders !== Deno.EOF) {
for (let [k, v] of entityHeaders) {
for (const [k, v] of entityHeaders) {
this.headers.set(k, v);
}
}
@ -242,8 +242,6 @@ export function parseHTTPVersion(vers: string): [number, number] {
default: {
const Big = 1000000; // arbitrary upper bound
const digitReg = /^\d+$/; // test if string is only digit
let major: number;
let minor: number;
if (!vers.startsWith("HTTP/")) {
break;
@ -254,8 +252,8 @@ export function parseHTTPVersion(vers: string): [number, number] {
break;
}
let majorStr = vers.substring(vers.indexOf("/") + 1, dot);
major = parseInt(majorStr);
const majorStr = vers.substring(vers.indexOf("/") + 1, dot);
const major = parseInt(majorStr);
if (
!digitReg.test(majorStr) ||
isNaN(major) ||
@ -265,8 +263,8 @@ export function parseHTTPVersion(vers: string): [number, number] {
break;
}
let minorStr = vers.substring(dot + 1);
minor = parseInt(minorStr);
const minorStr = vers.substring(dot + 1);
const minor = parseInt(minorStr);
if (
!digitReg.test(minorStr) ||
isNaN(minor) ||

View file

@ -349,7 +349,7 @@ const mockConn = {
};
test(async function readRequestError(): Promise<void> {
let input = `GET / HTTP/1.1
const input = `GET / HTTP/1.1
malformedHeader
`;
const reader = new BufReader(new StringReader(input));

View file

@ -5,7 +5,7 @@ import { serve } from "../server.ts";
window.onload = async function main() {
const addr = "0.0.0.0:4502";
console.log(`Simple server listening on ${addr}`);
for await (let req of serve(addr)) {
for await (const req of serve(addr)) {
req.respond({});
}
}

View file

@ -79,7 +79,7 @@ function getFlagFromPermission(perm: Permission): string {
function getInstallerDir(): string {
// In Windows's Powershell $HOME environmental variable maybe null
// if so use $HOMEPATH instead.
let { HOME, HOMEPATH } = env();
const { HOME, HOMEPATH } = env();
const HOME_PATH = HOME || HOMEPATH;
@ -109,7 +109,7 @@ function checkIfExistsInPath(filePath: string): boolean {
// $HOMEDRIVE is only used on Windows.
const { PATH, Path, HOMEDRIVE } = env();
let envPath = (PATH as string) || (Path as string) || "";
const envPath = (PATH as string) || (Path as string) || "";
const paths = envPath.split(isWindows ? ";" : ":");

View file

@ -407,7 +407,7 @@ export class BufReader implements Reader {
*/
export class BufWriter implements Writer {
buf: Uint8Array;
n: number = 0;
n = 0;
err: Error | null = null;
/** return new BufWriter unless w is BufWriter */

View file

@ -32,7 +32,7 @@ async function readBytes(buf: BufReader): Promise<string> {
const b = new Uint8Array(1000);
let nb = 0;
while (true) {
let c = await buf.readByte();
const c = await buf.readByte();
if (c === Deno.EOF) {
break; // EOF
}
@ -122,10 +122,10 @@ test(async function bufioBufReader(): Promise<void> {
}
texts[texts.length - 1] = all;
for (let text of texts) {
for (let readmaker of readMakers) {
for (let bufreader of bufreaders) {
for (let bufsize of bufsizes) {
for (const text of texts) {
for (const readmaker of readMakers) {
for (const bufreader of bufreaders) {
for (const bufsize of bufsizes) {
const read = readmaker.fn(stringsReader(text));
const buf = new BufReader(read, bufsize);
const s = await bufreader.fn(buf);
@ -210,8 +210,8 @@ class TestReader implements Reader {
async function testReadLine(input: Uint8Array): Promise<void> {
for (let stride = 1; stride < 2; stride++) {
let done = 0;
let reader = new TestReader(input, stride);
let l = new BufReader(reader, input.byteLength + 1);
const reader = new TestReader(input, stride);
const l = new BufReader(reader, input.byteLength + 1);
while (true) {
const r = await l.readLine();
if (r === Deno.EOF) {
@ -220,7 +220,7 @@ async function testReadLine(input: Uint8Array): Promise<void> {
const { line, more } = r;
assertEquals(more, false);
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
let want = testOutput.subarray(done, done + line.byteLength);
const want = testOutput.subarray(done, done + line.byteLength);
assertEquals(
line,
want,
@ -244,9 +244,9 @@ test(async function bufioReadLine(): Promise<void> {
test(async function bufioPeek(): Promise<void> {
const decoder = new TextDecoder();
let p = new Uint8Array(10);
const p = new Uint8Array(10);
// string is 16 (minReadBufferSize) long.
let buf = new BufReader(
const buf = new BufReader(
stringsReader("abcdefghijklmnop"),
MIN_READ_BUFFER_SIZE
);
@ -281,7 +281,7 @@ test(async function bufioPeek(): Promise<void> {
actual = assertNotEOF(await buf.peek(2));
assertEquals(decoder.decode(actual), "de");
let res = await buf.read(p.subarray(0, 3));
const res = await buf.read(p.subarray(0, 3));
assertEquals(decoder.decode(p.subarray(0, 3)), "def");
assert(res !== Deno.EOF);
@ -327,8 +327,8 @@ test(async function bufioWriter(): Promise<void> {
}
const w = new Buffer();
for (let nwrite of bufsizes) {
for (let bs of bufsizes) {
for (const nwrite of bufsizes) {
for (const bs of bufsizes) {
// Write nwrite bytes using buffer size bs.
// Check that the right amount makes it out
// and that the data is correct.

View file

@ -17,13 +17,13 @@ test(async function ioStringReader(): Promise<void> {
test(async function ioStringReader(): Promise<void> {
const r = new StringReader("abcdef");
const buf = new Uint8Array(3);
let res1 = await r.read(buf);
const res1 = await r.read(buf);
assertEquals(res1, 3);
assertEquals(decode(buf), "abc");
let res2 = await r.read(buf);
const res2 = await r.read(buf);
assertEquals(res2, 3);
assertEquals(decode(buf), "def");
let res3 = await r.read(buf);
const res3 = await r.read(buf);
assertEquals(res3, Deno.EOF);
assertEquals(decode(buf), "def");
});

View file

@ -6,7 +6,7 @@ import { copyBytes, tempFile } from "./util.ts";
import * as path from "../fs/path.ts";
test(function testCopyBytes(): void {
let dst = new Uint8Array(4);
const dst = new Uint8Array(4);
dst.fill(0);
let src = Uint8Array.of(1, 2);

View file

@ -5,7 +5,7 @@ import { decode, encode } from "../strings/mod.ts";
/** Writer utility for buffering string chunks */
export class StringWriter implements Writer {
private chunks: Uint8Array[] = [];
private byteLength: number = 0;
private byteLength = 0;
private cache: string | undefined;
constructor(private base: string = "") {

View file

@ -50,7 +50,7 @@ test(function customHandler(): void {
test(function logFunctions(): void {
const doLog = (level: string): TestHandler => {
const handler = new TestHandler(level);
let logger = new Logger(level, [handler]);
const logger = new Logger(level, [handler]);
logger.debug("foo");
logger.info("bar");
logger.warning("baz");

View file

@ -130,7 +130,7 @@ export function scanUntilBoundary(
class PartReader implements Reader, Closer {
n: number | Deno.EOF = 0;
total: number = 0;
total = 0;
constructor(private mr: MultipartReader, public readonly headers: Headers) {}
@ -312,7 +312,7 @@ export class MultipartReader {
}
private currentPart: PartReader | undefined;
private partsRead: number = 0;
private partsRead = 0;
private async nextPart(): Promise<PartReader | Deno.EOF> {
if (this.currentPart) {
@ -359,7 +359,7 @@ export class MultipartReader {
if (!hasPrefix(line, this.dashBoundaryDash)) {
return false;
}
let rest = line.slice(this.dashBoundaryDash.length, line.length);
const rest = line.slice(this.dashBoundaryDash.length, line.length);
return rest.length === 0 || equal(skipLWSPChar(rest), this.newLine);
}
@ -375,7 +375,7 @@ export class MultipartReader {
class PartWriter implements Writer {
closed = false;
private readonly partHeader: string;
private headersWritten: boolean = false;
private headersWritten = false;
constructor(
private writer: Writer,
@ -436,7 +436,7 @@ export class MultipartWriter {
private lastPart: PartWriter | undefined;
private bufWriter: BufWriter;
private isClosed: boolean = false;
private isClosed = false;
constructor(private readonly writer: Writer, boundary?: string) {
if (boundary !== void 0) {

View file

@ -54,21 +54,21 @@ test(async function testPrettierCheckAndFormatFiles(): Promise<void> {
join(tempDir, "2.ts")
];
var { code, stdout } = await run([...cmd, "--check", ...files]);
assertEquals(code, 1);
assertEquals(normalizeOutput(stdout), "Some files are not formatted");
let p = await run([...cmd, "--check", ...files]);
assertEquals(p.code, 1);
assertEquals(normalizeOutput(p.stdout), "Some files are not formatted");
var { code, stdout } = await run([...cmd, "--write", ...files]);
assertEquals(code, 0);
p = await run([...cmd, "--write", ...files]);
assertEquals(p.code, 0);
assertEquals(
normalizeOutput(stdout),
normalizeOutput(p.stdout),
normalizeOutput(`Formatting ${tempDir}/0.ts
Formatting ${tempDir}/1.js`)
);
var { code, stdout } = await run([...cmd, "--check", ...files]);
assertEquals(code, 0);
assertEquals(normalizeOutput(stdout), "Every file is formatted");
p = await run([...cmd, "--check", ...files]);
assertEquals(p.code, 0);
assertEquals(normalizeOutput(p.stdout), "Every file is formatted");
emptyDir(tempDir);
});
@ -79,23 +79,23 @@ test(async function testPrettierCheckAndFormatDirs(): Promise<void> {
const dirs = [join(tempDir, "foo"), join(tempDir, "bar")];
var { code, stdout } = await run([...cmd, "--check", ...dirs]);
assertEquals(code, 1);
assertEquals(normalizeOutput(stdout), "Some files are not formatted");
let p = await run([...cmd, "--check", ...dirs]);
assertEquals(p.code, 1);
assertEquals(normalizeOutput(p.stdout), "Some files are not formatted");
var { code, stdout } = await run([...cmd, "--write", ...dirs]);
assertEquals(code, 0);
p = await run([...cmd, "--write", ...dirs]);
assertEquals(p.code, 0);
assertEquals(
normalizeOutput(stdout),
normalizeOutput(p.stdout),
normalizeOutput(`Formatting ${tempDir}/bar/0.ts
Formatting ${tempDir}/bar/1.js
Formatting ${tempDir}/foo/0.ts
Formatting ${tempDir}/foo/1.js`)
);
var { code, stdout } = await run([...cmd, "--check", ...dirs]);
assertEquals(code, 0);
assertEquals(normalizeOutput(stdout), "Every file is formatted");
p = await run([...cmd, "--check", ...dirs]);
assertEquals(p.code, 0);
assertEquals(normalizeOutput(p.stdout), "Every file is formatted");
emptyDir(tempDir);
});

View file

@ -60,7 +60,7 @@ export function pad(
out = out.padEnd(strLen, opts.char);
}
} else if (opts.strict && outL > strLen) {
let addChar = opts.strictChar ? opts.strictChar : "";
const addChar = opts.strictChar ? opts.strictChar : "";
if (opts.strictSide === "left") {
let toDrop = outL - strLen;
if (opts.strictChar) {

View file

@ -235,7 +235,7 @@ export function assertArrayContains(
expected: unknown[],
msg?: string
): void {
let missing: unknown[] = [];
const missing: unknown[] = [];
for (let i = 0; i < expected.length; i++) {
let found = false;
for (let j = 0; j < actual.length; j++) {

View file

@ -19,7 +19,7 @@ test(async function benching(): Promise<void> {
bench(async function forAwaitFetchDenolandX10(b): Promise<void> {
b.start();
for (let i = 0; i < 10; i++) {
let r = await fetch("https://deno.land/");
const r = await fetch("https://deno.land/");
await r.text();
}
b.stop();
@ -31,7 +31,7 @@ test(async function benching(): Promise<void> {
await Promise.all(
urls.map(
async (denoland: string): Promise<void> => {
let r = await fetch(denoland);
const r = await fetch(denoland);
await r.text();
}
)

View file

@ -271,7 +271,7 @@ function printIteratorEntries(
// Too bad, so sad that separator for ECMAScript Map has been ' => '
// What a distracting diff if you change a data structure to/from
// ECMAScript Object or Immutable.Map/OrderedMap which use the default.
separator: string = ": "
separator = ": "
): string {
let result = "";
let current = iterator.next();

View file

@ -13,6 +13,7 @@ import { format } from "./format.ts";
// eslint-disable-next-line max-len
// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-explicit-any
function returnArguments(...args: any[]): IArguments {
// eslint-disable-next-line prefer-rest-params
return arguments;
}

View file

@ -62,7 +62,7 @@ function disableConsole(): void {
}
const encoder = new TextEncoder();
function print(txt: string, newline: boolean = true): void {
function print(txt: string, newline = true): void {
if (newline) {
txt += "\n";
}
@ -172,11 +172,11 @@ function createTestResults(tests: TestDefinition[]): TestResults {
);
}
function formatTestTime(time: number = 0): string {
function formatTestTime(time = 0): string {
return `${time.toFixed(2)}ms`;
}
function promptTestTime(time: number = 0, displayWarning = false): string {
function promptTestTime(time = 0, displayWarning = false): string {
// if time > 5s we display a warning
// only for test time, not the full runtime
if (displayWarning && time >= 5000) {
@ -308,10 +308,9 @@ async function runTestsSerial(
print(`${yellow("RUNNING")} ${name}`, false);
}
try {
let start, end;
start = performance.now();
const start = performance.now();
await fn();
end = performance.now();
const end = performance.now();
if (disableLog) {
// Rewriting the current prompt line to erase `running ....`
print(CLEAR_LINE, false);

View file

@ -66,7 +66,7 @@ export class TextProtoReader {
* }
*/
async readMIMEHeader(): Promise<Headers | Deno.EOF> {
let m = new Headers();
const m = new Headers();
let line: Uint8Array;
// The first line cannot start with a leading space.
@ -87,7 +87,7 @@ export class TextProtoReader {
}
while (true) {
let kv = await this.readLineSlice(); // readContinuedLineSlice
const kv = await this.readLineSlice(); // readContinuedLineSlice
if (kv === Deno.EOF) throw new UnexpectedEOFError();
if (kv.byteLength === 0) return m;
@ -104,7 +104,7 @@ export class TextProtoReader {
}
//let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey));
let key = str(kv.subarray(0, endKey));
const key = str(kv.subarray(0, endKey));
// As per RFC 7230 field-name is a token,
// tokens consist of one or more chars.
@ -123,7 +123,7 @@ export class TextProtoReader {
) {
i++;
}
let value = str(kv.subarray(i));
const value = str(kv.subarray(i));
// In case of invalid header we swallow the error
// example: "Audio Mode" => invalid due to space in the key

View file

@ -1,5 +1,5 @@
{
"extends": "tsconfig.test.json",
"extends": "./tsconfig.test.json",
"compilerOptions": {
"allowJs": true,
"baseUrl": ".",

View file

@ -100,7 +100,7 @@ export async function collectUint8Arrays(
}
const collected = new Uint8Array(length);
let offset = 0;
for (let chunk of chunks) {
for (const chunk of chunks) {
collected.set(chunk, offset);
offset += chunk.length;
}

View file

@ -368,7 +368,7 @@ export function createSecAccept(nonce: string): string {
const sha1 = new Sha1();
sha1.update(nonce + kGUID);
const bytes = sha1.digest();
return btoa(String.fromCharCode.apply(String, bytes));
return btoa(String.fromCharCode(...bytes));
}
/** Upgrade given TCP connection into websocket connection */
@ -480,7 +480,7 @@ export async function connectWebSocket(
headers: Headers = new Headers()
): Promise<WebSocket> {
const url = new URL(endpoint);
let { hostname } = url;
const { hostname } = url;
let conn: Conn;
if (url.protocol === "http:" || url.protocol === "ws:") {
const port = parseInt(url.port || "80");

View file

@ -70,7 +70,7 @@ async function* chunks(
let inspectIndex = 0;
let matchIndex = 0;
while (true) {
let result = await reader.read(inspectArr);
const result = await reader.read(inspectArr);
if (result === EOF) {
// Yield last chunk.
const lastChunk = inputBuffer.toString();
@ -81,7 +81,7 @@ async function* chunks(
// Discard all remaining and silently fail.
return;
}
let sliceRead = inspectArr.subarray(0, result as number);
const sliceRead = inspectArr.subarray(0, result as number);
await writeAll(inputBuffer, sliceRead);
let sliceToProcess = inputBuffer.bytes();