From 55b8a38d5090c53ce1327b44a7b6d65bf18273ee Mon Sep 17 00:00:00 2001 From: Alexander T Date: Thu, 13 Jun 2019 13:37:14 +0300 Subject: [PATCH 001/108] add eslint --- .eslintignore | 3 + .eslintrc | 121 +++++++++++++++ Gulpfile.js | 41 ++--- README.md | 2 +- package.json | 6 +- .../autolinkableStylishFormatter.ts | 97 ------------ scripts/tslint/rules/booleanTriviaRule.ts | 93 ------------ scripts/tslint/rules/debugAssertRule.ts | 45 ------ scripts/tslint/rules/nextLineRule.ts | 67 --------- scripts/tslint/rules/noBomRule.ts | 16 -- scripts/tslint/rules/noDoubleSpaceRule.ts | 54 ------- scripts/tslint/rules/noInOperatorRule.ts | 19 --- .../tslint/rules/noIncrementDecrementRule.ts | 55 ------- .../rules/noTypeAssertionWhitespaceRule.ts | 25 ---- .../objectLiteralSurroundingSpaceRule.ts | 44 ------ .../tslint/rules/typeOperatorSpacingRule.ts | 30 ---- scripts/tslint/tsconfig.json | 20 --- tslint.json | 141 ------------------ 18 files changed, 145 insertions(+), 734 deletions(-) create mode 100644 .eslintignore create mode 100644 .eslintrc delete mode 100644 scripts/tslint/formatters/autolinkableStylishFormatter.ts delete mode 100644 scripts/tslint/rules/booleanTriviaRule.ts delete mode 100644 scripts/tslint/rules/debugAssertRule.ts delete mode 100644 scripts/tslint/rules/nextLineRule.ts delete mode 100644 scripts/tslint/rules/noBomRule.ts delete mode 100644 scripts/tslint/rules/noDoubleSpaceRule.ts delete mode 100644 scripts/tslint/rules/noInOperatorRule.ts delete mode 100644 scripts/tslint/rules/noIncrementDecrementRule.ts delete mode 100644 scripts/tslint/rules/noTypeAssertionWhitespaceRule.ts delete mode 100644 scripts/tslint/rules/objectLiteralSurroundingSpaceRule.ts delete mode 100644 scripts/tslint/rules/typeOperatorSpacingRule.ts delete mode 100644 scripts/tslint/tsconfig.json delete mode 100644 tslint.json diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000000000..ffe06abf2d682 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,3 @@ +/built/local/** +/tests/** +/lib/** \ No newline at end of file diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000000000..9d473154a846f --- /dev/null +++ b/.eslintrc @@ -0,0 +1,121 @@ +{ + "parser": "@typescript-eslint/parser", + "parserOptions": { + "warnOnUnsupportedTypeScriptVersion": false, + "ecmaVersion": 6, + "sourceType": "module", + "project": "./src/tsconfig-base.json" + }, + "env": { + "browser": false, + "node": true, + "es6": true + }, + "plugins": [ + "@typescript-eslint", "microsoft-typescript" + ], + "rules": { + "@typescript-eslint/adjacent-overload-signatures": "off", + "@typescript-eslint/array-type": "off", + "@typescript-eslint/ban-types": "off", + "camelcase": "off", + "@typescript-eslint/camelcase": "off", + "@typescript-eslint/class-name-casing": "off", + "@typescript-eslint/explicit-member-accessibility": "off", + "@typescript-eslint/import/order": "off", + "indent": "off", + "@typescript-eslint/indent": "off", + "@typescript-eslint/interface-name-prefix": "off", + "@typescript-eslint/member-ordering": "off", + "@typescript-eslint/no-angle-bracket-type-assertion": "off", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-inferrable-types": "off", + "@typescript-eslint/no-misused-new": "error", + "@typescript-eslint/no-namespace": "off", + "@typescript-eslint/no-object-literal-type-assertion": "off", + "@typescript-eslint/no-parameter-properties": "off", + "@typescript-eslint/no-this-alias": "off", + "@typescript-eslint/no-triple-slash-reference": "off", + "@typescript-eslint/no-unnecessary-qualifier": "off", + "@typescript-eslint/no-unnecessary-type-assertion": "off", + "@typescript-eslint/no-use-before-define": "off", + "@typescript-eslint/no-var-requires": "off", + "@typescript-eslint/prefer-for-of": "error", + "@typescript-eslint/prefer-function-type": "off", + "@typescript-eslint/prefer-interface": "off", + "@typescript-eslint/prefer-namespace-keyword": "off", + "semi": "off", + "@typescript-eslint/semi": "off", + "@typescript-eslint/type-annotation-spacing": "off", + "@typescript-eslint/unified-signatures": "off", + + "microsoft-typescript/object-literal-surrounding-space": "off", + "microsoft-typescript/no-type-assertion-whitespace": "error", + "microsoft-typescript/type-operator-spacing": "off", + "microsoft-typescript/only-arrow-functions": "off", + "microsoft-typescript/no-double-space": "off", + "microsoft-typescript/boolean-trivia": "off", + "microsoft-typescript/no-in-operator": "off", + "microsoft-typescript/debug-assert": "off", + "microsoft-typescript/no-keywords": "off", + + "arrow-body-style": "off", + "arrow-parens": "off", + "brace-style": "off", + "comma-dangle": "off", + "complexity": "off", + "constructor-super": "error", + "curly": ["error", "multi-line"], + "dot-notation": "off", + "eol-last": "off", + "eqeqeq": "error", + "guard-for-in": "off", + "linebreak-style": "off", + "max-classes-per-file": "off", + "max-len": "off", + "new-parens": "error", + "no-bitwise": "off", + "no-caller": "error", + "no-cond-assign": "off", + "no-console": "off", + "no-debugger": "off", + "no-duplicate-case": "error", + "no-duplicate-imports": "error", + "no-empty": "off", + "no-eval": "off", + "no-extra-bind": "error", + "no-fallthrough": "off", + "no-invalid-this": "off", + "no-multiple-empty-lines": "off", + "no-new-func": "off", + "no-new-wrappers": "error", + "no-redeclare": "off", + "no-return-await": "error", + "no-restricted-globals": "off", + "no-sequences": "off", + "no-shadow": "off", + "no-sparse-arrays": "error", + "no-template-curly-in-string": "off", + "no-throw-literal": "off", + "no-trailing-spaces": "off", + "no-undef-init": "error", + "no-unsafe-finally": "error", + "no-unused-expressions": "off", + "no-unused-labels": "error", + "no-var": "off", + "object-shorthand": "off", + "one-var": "off", + "prefer-const": "off", + "prefer-object-spread": "error", + "quote-props": ["error", "consistent-as-needed"], + "quotes": "off", + "radix": "off", + "sort-keys": "off", + "space-before-function-paren": "off", + "space-in-parens": "off", + "unicode-bom": ["error", "never"], + "use-isnan": "error", + "valid-typeof": "off" + } +} diff --git a/Gulpfile.js b/Gulpfile.js index bfc4bf43db724..16d15164a9042 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -318,34 +318,23 @@ task("clean-tests").description = "Cleans the outputs for the test infrastructur const watchTests = () => watchProject("src/testRunner", cmdLineOptions); -const buildRules = () => buildProject("scripts/tslint"); -task("build-rules", buildRules); -task("build-rules").description = "Compiles tslint rules to js"; - -const cleanRules = () => cleanProject("scripts/tslint"); -cleanTasks.push(cleanRules); -task("clean-rules", cleanRules); -task("clean-rules").description = "Cleans the outputs for the lint rules"; - const lintFoldStart = async () => { if (fold.isTravis()) console.log(fold.start("lint")); }; const lintFoldEnd = async () => { if (fold.isTravis()) console.log(fold.end("lint")); }; -const lint = series([ - lintFoldStart, - ...["scripts/tslint/tsconfig.json", "src/tsconfig-base.json"].map(project => { - const lintOne = () => { - const args = ["node_modules/tslint/bin/tslint", "--project", project, "--formatters-dir", "./built/local/tslint/formatters", "--format", "autolinkableStylish"]; - if (cmdLineOptions.fix) args.push("--fix"); - log(`Linting: node ${args.join(" ")}`); - return exec(process.execPath, args); - }; - lintOne.dispayName = `lint(${project})`; - return lintOne; - }), - lintFoldEnd -]); +const eslint = async () => { + const args = [ + "node_modules/eslint/bin/eslint", "-f", "autolinkable-stylish", "-c", ".eslintrc", "--ext", ".ts", "." + ]; + + if (cmdLineOptions.fix) { + args.push("--fix"); + } + log(`Linting: ${args.join(" ")}`); + return exec(process.execPath, args); +} +const lint = series([lintFoldStart, eslint, lintFoldEnd]); lint.displayName = "lint"; -task("lint", series(buildRules, lint)); -task("lint").description = "Runs tslint on the compiler sources."; +task("lint", lint); +task("lint").description = "Runs eslint on the compiler sources."; task("lint").flags = { " --f[iles]=": "pattern to match files to lint", }; @@ -393,7 +382,7 @@ const generateCodeCoverage = () => exec("istanbul", ["cover", "node_modules/moch task("generate-code-coverage", series(preBuild, buildTests, generateCodeCoverage)); task("generate-code-coverage").description = "Generates code coverage data via istanbul"; -const preTest = parallel(buildRules, buildTests, buildServices, buildLssl); +const preTest = parallel(buildTests, buildServices, buildLssl); preTest.displayName = "preTest"; const postTest = (done) => cmdLineOptions.lint ? lint(done) : done(); diff --git a/README.md b/README.md index 04c8c7dbbcc36..7cd7a235bc9b1 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ gulp runtests # Run tests using the built compiler and test infrastructu # You can override the host or specify a test for this command. # Use --host= or --tests=. gulp baseline-accept # This replaces the baseline test results with the results obtained from gulp runtests. -gulp lint # Runs tslint on the TypeScript source. +gulp lint # Runs eslint on the TypeScript source. gulp help # List the above commands. ``` diff --git a/package.json b/package.json index 965c0c3bb32b1..9fab8be64e6bf 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,8 @@ "@types/through2": "latest", "@types/travis-fold": "latest", "@types/xml2js": "^0.4.0", + "@typescript-eslint/eslint-plugin": "latest", + "@typescript-eslint/parser": "latest", "azure-devops-node-api": "^8.0.0", "browser-resolve": "^1.11.2", "browserify": "latest", @@ -61,6 +63,9 @@ "chalk": "latest", "convert-source-map": "latest", "del": "latest", + "eslint": "latest", + "eslint-formatter-autolinkable-stylish": "latest", + "eslint-plugin-microsoft-typescript": "0.1.11", "fancy-log": "latest", "fs-extra": "^6.0.1", "gulp": "^4.0.0", @@ -85,7 +90,6 @@ "source-map-support": "latest", "through2": "latest", "travis-fold": "latest", - "tslint": "latest", "typescript": "next", "vinyl": "latest", "vinyl-sourcemaps-apply": "latest", diff --git a/scripts/tslint/formatters/autolinkableStylishFormatter.ts b/scripts/tslint/formatters/autolinkableStylishFormatter.ts deleted file mode 100644 index 23e01bc8587e1..0000000000000 --- a/scripts/tslint/formatters/autolinkableStylishFormatter.ts +++ /dev/null @@ -1,97 +0,0 @@ -import * as Lint from "tslint"; -import chalk from "chalk"; -import { sep } from "path"; -function groupBy(array: ReadonlyArray | undefined, getGroupId: (elem: T, index: number) => number | string): T[][] { - if (!array) { - return []; - } - - const groupIdToGroup: { [index: string]: T[] } = {}; - let result: T[][] | undefined; // Compacted array for return value - for (let index = 0; index < array.length; index++) { - const value = array[index]; - const key = getGroupId(value, index); - if (groupIdToGroup[key]) { - groupIdToGroup[key].push(value); - } - else { - const newGroup = [value]; - groupIdToGroup[key] = newGroup; - if (!result) { - result = [newGroup]; - } - else { - result.push(newGroup); - } - } - } - - return result || []; -} - -function max(array: ReadonlyArray | undefined, selector: (elem: T) => number): number { - if (!array) { - return 0; - } - - let max = 0; - for (const item of array) { - const scalar = selector(item); - if (scalar > max) { - max = scalar; - } - } - return max; -} - -function getLink(failure: Lint.RuleFailure, color: boolean): string { - const lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); - const sev = failure.getRuleSeverity().toUpperCase(); - let path = failure.getFileName(); - // Most autolinks only become clickable if they contain a slash in some way; so we make a top level file into a relative path here - if (path.indexOf("/") === -1 && path.indexOf("\\") === -1) { - path = `.${sep}${path}`; - } - return `${color ? (sev === "WARNING" ? chalk.blue(sev) : chalk.red(sev)) : sev}: ${path}:${lineAndCharacter.line + 1}:${lineAndCharacter.character + 1}`; -} - -function getLinkMaxSize(failures: Lint.RuleFailure[]): number { - return max(failures, f => getLink(f, /*color*/ false).length); -} - -function getNameMaxSize(failures: Lint.RuleFailure[]): number { - return max(failures, f => f.getRuleName().length); -} - -function pad(str: string, visiblelen: number, len: number) { - if (visiblelen >= len) return str; - const count = len - visiblelen; - for (let i = 0; i < count; i++) { - str += " "; - } - return str; -} - -export class Formatter extends Lint.Formatters.AbstractFormatter { - public static metadata: Lint.IFormatterMetadata = { - formatterName: "autolinkableStylish", - description: "Human-readable formatter which creates stylish messages with autolinkable filepaths.", - descriptionDetails: Lint.Utils.dedent` - Colorized output grouped by file, with autolinkable filepaths containing line and column information - `, - sample: Lint.Utils.dedent` - src/myFile.ts - ERROR: src/myFile.ts:1:14 semicolon Missing semicolon`, - consumer: "human" - }; - public format(failures: Lint.RuleFailure[]): string { - return groupBy(failures, f => f.getFileName()).map(group => { - const currentFile = group[0].getFileName(); - const linkMaxSize = getLinkMaxSize(group); - const nameMaxSize = getNameMaxSize(group); - return ` -${currentFile} -${group.map(f => `${pad(getLink(f, /*color*/ true), getLink(f, /*color*/ false).length, linkMaxSize)} ${chalk.grey(pad(f.getRuleName(), f.getRuleName().length, nameMaxSize))} ${chalk.yellow(f.getFailure())}`).join("\n")}`; - }).join("\n"); - } -} \ No newline at end of file diff --git a/scripts/tslint/rules/booleanTriviaRule.ts b/scripts/tslint/rules/booleanTriviaRule.ts deleted file mode 100644 index 0224a0f08d86b..0000000000000 --- a/scripts/tslint/rules/booleanTriviaRule.ts +++ /dev/null @@ -1,93 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -export class Rule extends Lint.Rules.AbstractRule { - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, ctx => walk(ctx)); - } -} - -function walk(ctx: Lint.WalkContext): void { - const { sourceFile } = ctx; - ts.forEachChild(sourceFile, function recur(node: ts.Node): void { - if (node.kind === ts.SyntaxKind.CallExpression) { - checkCall(node as ts.CallExpression); - } - ts.forEachChild(node, recur); - }); - - function checkCall(node: ts.CallExpression): void { - if (!shouldIgnoreCalledExpression(node.expression)) { - for (const arg of node.arguments) { - checkArg(arg); - } - } - } - - /** Skip certain function/method names whose parameter names are not informative. */ - function shouldIgnoreCalledExpression(expression: ts.Expression): boolean { - if (expression.kind === ts.SyntaxKind.PropertyAccessExpression) { - const methodName = (expression as ts.PropertyAccessExpression).name.text; - if (methodName.startsWith("set") || methodName.startsWith("assert")) { - return true; - } - switch (methodName) { - case "apply": - case "call": - case "equal": - case "fail": - case "isTrue": - case "output": - case "stringify": - return true; - } - } - else if (expression.kind === ts.SyntaxKind.Identifier) { - const functionName = (expression as ts.Identifier).text; - if (functionName.startsWith("set") || functionName.startsWith("assert")) { - return true; - } - switch (functionName) { - case "contains": - case "createAnonymousType": - case "createImportSpecifier": - case "createProperty": - case "createSignature": - case "resolveName": - return true; - } - } - return false; - } - - function checkArg(arg: ts.Expression): void { - if (!isTrivia(arg)) { - return; - } - - const ranges = ts.getTrailingCommentRanges(sourceFile.text, arg.pos) || ts.getLeadingCommentRanges(sourceFile.text, arg.pos); - if (ranges === undefined || ranges.length !== 1 || ranges[0].kind !== ts.SyntaxKind.MultiLineCommentTrivia) { - ctx.addFailureAtNode(arg, "Tag argument with parameter name"); - return; - } - - const range = ranges[0]; - const argStart = arg.getStart(sourceFile); - if (range.end + 1 !== argStart && sourceFile.text.slice(range.end, argStart).indexOf("\n") === -1) { - ctx.addFailureAtNode(arg, "There should be 1 space between an argument and its comment."); - } - } - - function isTrivia(arg: ts.Expression): boolean { - switch (arg.kind) { - case ts.SyntaxKind.TrueKeyword: - case ts.SyntaxKind.FalseKeyword: - case ts.SyntaxKind.NullKeyword: - return true; - case ts.SyntaxKind.Identifier: - return (arg as ts.Identifier).originalKeywordKind === ts.SyntaxKind.UndefinedKeyword; - default: - return false; - } - } -} diff --git a/scripts/tslint/rules/debugAssertRule.ts b/scripts/tslint/rules/debugAssertRule.ts deleted file mode 100644 index 933b27697b01b..0000000000000 --- a/scripts/tslint/rules/debugAssertRule.ts +++ /dev/null @@ -1,45 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -export class Rule extends Lint.Rules.AbstractRule { - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, ctx => walk(ctx)); - } -} - -function walk(ctx: Lint.WalkContext): void { - ts.forEachChild(ctx.sourceFile, function recur(node) { - if (ts.isCallExpression(node)) { - checkCall(node); - } - ts.forEachChild(node, recur); - }); - - function checkCall(node: ts.CallExpression) { - if (!isDebugAssert(node.expression) || node.arguments.length < 2) { - return; - } - - const message = node.arguments[1]; - if (!ts.isStringLiteral(message)) { - ctx.addFailureAtNode(message, "Second argument to 'Debug.assert' should be a string literal."); - } - - if (node.arguments.length < 3) { - return; - } - - const message2 = node.arguments[2]; - if (!ts.isStringLiteral(message2) && !ts.isArrowFunction(message2)) { - ctx.addFailureAtNode(message, "Third argument to 'Debug.assert' should be a string literal or arrow function."); - } - } - - function isDebugAssert(expr: ts.Node): boolean { - return ts.isPropertyAccessExpression(expr) && isName(expr.expression, "Debug") && isName(expr.name, "assert"); - } - - function isName(expr: ts.Node, text: string): boolean { - return ts.isIdentifier(expr) && expr.text === text; - } -} diff --git a/scripts/tslint/rules/nextLineRule.ts b/scripts/tslint/rules/nextLineRule.ts deleted file mode 100644 index 9de80793c62e3..0000000000000 --- a/scripts/tslint/rules/nextLineRule.ts +++ /dev/null @@ -1,67 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -const OPTION_CATCH = "check-catch"; -const OPTION_ELSE = "check-else"; - -export class Rule extends Lint.Rules.AbstractRule { - public static CATCH_FAILURE_STRING = "'catch' should not be on the same line as the preceeding block's curly brace"; - public static ELSE_FAILURE_STRING = "'else' should not be on the same line as the preceeding block's curly brace"; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - const options = this.getOptions().ruleArguments; - const checkCatch = options.indexOf(OPTION_CATCH) !== -1; - const checkElse = options.indexOf(OPTION_ELSE) !== -1; - return this.applyWithFunction(sourceFile, ctx => walk(ctx, checkCatch, checkElse)); - } -} - -function walk(ctx: Lint.WalkContext, checkCatch: boolean, checkElse: boolean): void { - const { sourceFile } = ctx; - ts.forEachChild(sourceFile, function recur(node) { - switch (node.kind) { - case ts.SyntaxKind.IfStatement: - checkIf(node as ts.IfStatement); - break; - case ts.SyntaxKind.TryStatement: - checkTry(node as ts.TryStatement); - break; - } - ts.forEachChild(node, recur); - }); - - function checkIf(node: ts.IfStatement): void { - const { thenStatement, elseStatement } = node; - if (!elseStatement) { - return; - } - - // find the else keyword - const elseKeyword = getFirstChildOfKind(node, ts.SyntaxKind.ElseKeyword); - if (checkElse && !!elseKeyword) { - const thenStatementEndLoc = sourceFile.getLineAndCharacterOfPosition(thenStatement.getEnd()); - const elseKeywordLoc = sourceFile.getLineAndCharacterOfPosition(elseKeyword.getStart(sourceFile)); - if (thenStatementEndLoc.line === elseKeywordLoc.line) { - ctx.addFailureAtNode(elseKeyword, Rule.ELSE_FAILURE_STRING); - } - } - } - - function checkTry({ tryBlock, catchClause }: ts.TryStatement): void { - if (!checkCatch || !catchClause) { - return; - } - - const tryClosingBrace = tryBlock.getLastToken(sourceFile)!; - const catchKeyword = catchClause.getFirstToken(sourceFile)!; - const tryClosingBraceLoc = sourceFile.getLineAndCharacterOfPosition(tryClosingBrace.getEnd()); - const catchKeywordLoc = sourceFile.getLineAndCharacterOfPosition(catchKeyword.getStart(sourceFile)); - if (tryClosingBraceLoc.line === catchKeywordLoc.line) { - ctx.addFailureAtNode(catchKeyword, Rule.CATCH_FAILURE_STRING); - } - } -} - -function getFirstChildOfKind(node: ts.Node, kind: ts.SyntaxKind) { - return node.getChildren().filter((child) => child.kind === kind)[0]; -} diff --git a/scripts/tslint/rules/noBomRule.ts b/scripts/tslint/rules/noBomRule.ts deleted file mode 100644 index 105e2d2d68c01..0000000000000 --- a/scripts/tslint/rules/noBomRule.ts +++ /dev/null @@ -1,16 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -export class Rule extends Lint.Rules.AbstractRule { - public static FAILURE_STRING = "This file has a BOM."; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - if (ctx.sourceFile.text[0] === "\ufeff") { - ctx.addFailure(0, 1, Rule.FAILURE_STRING); - } -} diff --git a/scripts/tslint/rules/noDoubleSpaceRule.ts b/scripts/tslint/rules/noDoubleSpaceRule.ts deleted file mode 100644 index 34ab470ebced3..0000000000000 --- a/scripts/tslint/rules/noDoubleSpaceRule.ts +++ /dev/null @@ -1,54 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -export class Rule extends Lint.Rules.AbstractRule { - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - const { sourceFile } = ctx; - const lines = sourceFile.text.split("\n"); - const strings = getLiterals(sourceFile); - lines.forEach((line, idx) => { - // Skip indentation. - const firstNonSpace = /\S/.exec(line); - if (firstNonSpace === null) { - return; - } - // Allow common uses of double spaces - // * To align `=` or `!=` signs - // * To align comments at the end of lines - // * To indent inside a comment - // * To use two spaces after a period - // * To include aligned `->` in a comment - const rgx = /[^/*. ] [^-!/= ]/g; - rgx.lastIndex = firstNonSpace.index; - const doubleSpace = rgx.exec(line); - // Also allow to align comments after `@param` - if (doubleSpace !== null && !line.includes("@param")) { - const pos = lines.slice(0, idx).reduce((len, line) => len + 1 + line.length, 0) + doubleSpace.index; - if (!strings.some(s => s.getStart() <= pos && s.end > pos)) { - ctx.addFailureAt(pos + 1, 2, "Use only one space."); - } - } - }); -} - -function getLiterals(sourceFile: ts.SourceFile): ReadonlyArray { - const out: ts.Node[] = []; - sourceFile.forEachChild(function cb(node) { - switch (node.kind) { - case ts.SyntaxKind.StringLiteral: - case ts.SyntaxKind.TemplateHead: - case ts.SyntaxKind.TemplateMiddle: - case ts.SyntaxKind.TemplateTail: - case ts.SyntaxKind.NoSubstitutionTemplateLiteral: - case ts.SyntaxKind.RegularExpressionLiteral: - out.push(node); - } - node.forEachChild(cb); - }); - return out; -} diff --git a/scripts/tslint/rules/noInOperatorRule.ts b/scripts/tslint/rules/noInOperatorRule.ts deleted file mode 100644 index 95f052ccaa62e..0000000000000 --- a/scripts/tslint/rules/noInOperatorRule.ts +++ /dev/null @@ -1,19 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -export class Rule extends Lint.Rules.AbstractRule { - public static FAILURE_STRING = "Don't use the 'in' keyword - use 'hasProperty' to check for key presence instead"; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - ts.forEachChild(ctx.sourceFile, recur); - function recur(node: ts.Node): void { - if (node.kind === ts.SyntaxKind.InKeyword && node.parent.kind === ts.SyntaxKind.BinaryExpression) { - ctx.addFailureAtNode(node, Rule.FAILURE_STRING); - } - } -} diff --git a/scripts/tslint/rules/noIncrementDecrementRule.ts b/scripts/tslint/rules/noIncrementDecrementRule.ts deleted file mode 100644 index 007d25919e183..0000000000000 --- a/scripts/tslint/rules/noIncrementDecrementRule.ts +++ /dev/null @@ -1,55 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -export class Rule extends Lint.Rules.AbstractRule { - public static POSTFIX_FAILURE_STRING = "Don't use '++' or '--' postfix operators outside statements or for loops."; - public static PREFIX_FAILURE_STRING = "Don't use '++' or '--' prefix operators."; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - ts.forEachChild(ctx.sourceFile, recur); - function recur(node: ts.Node): void { - switch (node.kind) { - case ts.SyntaxKind.PrefixUnaryExpression: - const { operator } = node as ts.PrefixUnaryExpression; - if (operator === ts.SyntaxKind.PlusPlusToken || operator === ts.SyntaxKind.MinusMinusToken) { - check(node as ts.PrefixUnaryExpression); - } - break; - - case ts.SyntaxKind.PostfixUnaryExpression: - check(node as ts.PostfixUnaryExpression); - break; - } - } - - function check(node: ts.UnaryExpression): void { - if (!isAllowedLocation(node.parent)) { - ctx.addFailureAtNode(node, Rule.POSTFIX_FAILURE_STRING); - } - } -} - -function isAllowedLocation(node: ts.Node): boolean { - switch (node.kind) { - // Can be a statement - case ts.SyntaxKind.ExpressionStatement: - return true; - - // Can be directly in a for-statement - case ts.SyntaxKind.ForStatement: - return true; - - // Can be in a comma operator in a for statement (`for (let a = 0, b = 10; a < b; a++, b--)`) - case ts.SyntaxKind.BinaryExpression: - return (node as ts.BinaryExpression).operatorToken.kind === ts.SyntaxKind.CommaToken && - node.parent.kind === ts.SyntaxKind.ForStatement; - - default: - return false; - } -} diff --git a/scripts/tslint/rules/noTypeAssertionWhitespaceRule.ts b/scripts/tslint/rules/noTypeAssertionWhitespaceRule.ts deleted file mode 100644 index 37017fb60e477..0000000000000 --- a/scripts/tslint/rules/noTypeAssertionWhitespaceRule.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -export class Rule extends Lint.Rules.AbstractRule { - public static TRAILING_FAILURE_STRING = "Excess trailing whitespace found around type assertion."; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - ts.forEachChild(ctx.sourceFile, recur); - function recur(node: ts.Node) { - if (node.kind === ts.SyntaxKind.TypeAssertionExpression) { - const refined = node as ts.TypeAssertion; - const leftSideWhitespaceStart = refined.type.getEnd() + 1; - const rightSideWhitespaceEnd = refined.expression.getStart(); - if (leftSideWhitespaceStart !== rightSideWhitespaceEnd) { - ctx.addFailure(leftSideWhitespaceStart, rightSideWhitespaceEnd, Rule.TRAILING_FAILURE_STRING); - } - } - ts.forEachChild(node, recur); - } -} diff --git a/scripts/tslint/rules/objectLiteralSurroundingSpaceRule.ts b/scripts/tslint/rules/objectLiteralSurroundingSpaceRule.ts deleted file mode 100644 index 8546aa6c973c3..0000000000000 --- a/scripts/tslint/rules/objectLiteralSurroundingSpaceRule.ts +++ /dev/null @@ -1,44 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -export class Rule extends Lint.Rules.AbstractRule { - public static LEADING_FAILURE_STRING = "No leading whitespace found on single-line object literal."; - public static TRAILING_FAILURE_STRING = "No trailing whitespace found on single-line object literal."; - public static LEADING_EXCESS_FAILURE_STRING = "Excess leading whitespace found on single-line object literal."; - public static TRAILING_EXCESS_FAILURE_STRING = "Excess trailing whitespace found on single-line object literal."; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - const { sourceFile } = ctx; - ts.forEachChild(sourceFile, recur); - function recur(node: ts.Node): void { - if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) { - check(node as ts.ObjectLiteralExpression); - } - ts.forEachChild(node, recur); - } - - function check(node: ts.ObjectLiteralExpression): void { - const text = node.getText(sourceFile); - if (!text.match(/^{[^\n]+}$/g)) { - return; - } - - if (text.charAt(1) !== " ") { - ctx.addFailureAtNode(node, Rule.LEADING_FAILURE_STRING); - } - if (text.charAt(2) === " ") { - ctx.addFailureAt(node.pos + 2, 1, Rule.LEADING_EXCESS_FAILURE_STRING); - } - if (text.charAt(text.length - 2) !== " ") { - ctx.addFailureAtNode(node, Rule.TRAILING_FAILURE_STRING); - } - if (text.charAt(text.length - 3) === " ") { - ctx.addFailureAt(node.pos + node.getWidth() - 3, 1, Rule.TRAILING_EXCESS_FAILURE_STRING); - } - } -} diff --git a/scripts/tslint/rules/typeOperatorSpacingRule.ts b/scripts/tslint/rules/typeOperatorSpacingRule.ts deleted file mode 100644 index 82dccfe0eace5..0000000000000 --- a/scripts/tslint/rules/typeOperatorSpacingRule.ts +++ /dev/null @@ -1,30 +0,0 @@ -import * as Lint from "tslint/lib"; -import * as ts from "typescript"; - -export class Rule extends Lint.Rules.AbstractRule { - public static FAILURE_STRING = "The '|' and '&' operators must be surrounded by spaces"; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext): void { - const { sourceFile } = ctx; - sourceFile.forEachChild(function cb(node: ts.Node): void { - if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node)) { - check(node); - } - node.forEachChild(cb); - }); - - function check(node: ts.UnionTypeNode | ts.IntersectionTypeNode): void { - const list = node.getChildren().find(child => child.kind === ts.SyntaxKind.SyntaxList)!; - for (const child of list.getChildren()) { - if ((child.kind === ts.SyntaxKind.BarToken || child.kind === ts.SyntaxKind.AmpersandToken) - && (/\S/.test(sourceFile.text[child.getStart(sourceFile) - 1]) || /\S/.test(sourceFile.text[child.end]))) { - ctx.addFailureAtNode(child, Rule.FAILURE_STRING); - } - } - } -} diff --git a/scripts/tslint/tsconfig.json b/scripts/tslint/tsconfig.json deleted file mode 100644 index e9f90ad42669b..0000000000000 --- a/scripts/tslint/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compilerOptions": { - "lib": ["es6"], - "sourceMap": false, - "declaration": false, - "noImplicitAny": true, - "noImplicitReturns": true, - "noImplicitThis": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "strictNullChecks": true, - "module": "commonjs", - "outDir": "../../built/local/tslint", - "baseUrl": "../..", - "types": ["node"], - "paths": { - "typescript": ["lib/typescript.d.ts"] - } - } -} \ No newline at end of file diff --git a/tslint.json b/tslint.json deleted file mode 100644 index 5b75ed1a55b74..0000000000000 --- a/tslint.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "extends": "tslint:latest", - "rulesDirectory": "built/local/tslint/rules", - "linterOptions": { - "exclude": [ - "tests/**/*" - ] - }, - "rules": { - "no-unnecessary-type-assertion": true, - - "array-type": [true, "array"], - "ban": [ - true, - "setInterval", - "setTimeout" - ], - "ban-types": { - "options": [ - ["Object", "Avoid using the `Object` type. Did you mean `object`?"], - ["Function", "Avoid using the `Function` type. Prefer a specific function type, like `() => void`, or use `ts.AnyFunction`."], - ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], - ["Number", "Avoid using the `Number` type. Did you mean `number`?"], - ["String", "Avoid using the `String` type. Did you mean `string`?"] - ] - }, - "boolean-trivia": true, - "class-name": true, - "comment-format": [true, - "check-space" - ], - "curly":[true, "ignore-same-line"], - "debug-assert": true, - "indent": [true, - "spaces" - ], - "interface-name": [true, "never-prefix"], - "interface-over-type-literal": true, - "jsdoc-format": true, - "linebreak-style": [true, "CRLF"], - "next-line": [true, - "check-catch", - "check-else" - ], - "no-bom": true, - "no-double-space": true, - "no-eval": true, - "no-in-operator": true, - "no-increment-decrement": true, - "no-inferrable-types": true, - "no-internal-module": true, - "no-null-keyword": true, - "no-switch-case-fall-through": true, - "no-trailing-whitespace": [true, "ignore-template-strings"], - "no-type-assertion-whitespace": true, - "no-unnecessary-qualifier": true, - "no-var-keyword": true, - "object-literal-shorthand": true, - "object-literal-surrounding-space": true, - "one-line": [true, - "check-open-brace", - "check-whitespace" - ], - "prefer-const": true, - "quotemark": [true, - "double", - "avoid-escape" - ], - "semicolon": [true, "always", "ignore-bound-class-methods"], - "space-within-parens": true, - "triple-equals": true, - "type-operator-spacing": true, - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - }, - { - "call-signature": "onespace", - "index-signature": "onespace", - "parameter": "onespace", - "property-declaration": "onespace", - "variable-declaration": "onespace" - } - ], - "whitespace": [true, - "check-branch", - "check-decl", - "check-operator", - "check-module", - "check-separator", - "check-type" - ], - - // Config different from tslint:latest - "no-implicit-dependencies": [true, "dev"], - "object-literal-key-quotes": [true, "consistent-as-needed"], - "variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore"], - - // TODO - "arrow-parens": false, // [true, "ban-single-arg-parens"] - "arrow-return-shorthand": false, - "ban-types": false, - "forin": false, - "member-access": false, // [true, "no-public"] - "no-conditional-assignment": false, - "no-console": false, - "no-debugger": false, - "no-empty-interface": false, - "no-object-literal-type-assertion": false, - "no-shadowed-variable": false, - "no-submodule-imports": false, - "no-var-requires": false, - "ordered-imports": false, - "prefer-conditional-expression": false, - "radix": false, - "trailing-comma": false, - - // These should be done automatically by a formatter. https://github.com/Microsoft/TypeScript/issues/18340 - "align": false, - "eofline": false, - "max-line-length": false, - "no-consecutive-blank-lines": false, - "space-before-function-paren": false, - - // Not doing - "ban-comma-operator": false, - "max-classes-per-file": false, - "member-ordering": false, - "no-angle-bracket-type-assertion": false, - "no-bitwise": false, - "no-namespace": false, - "no-reference": false, - "object-literal-sort-keys": false, - "one-variable-per-declaration": false - } -} From f6ccfb39cc1742a51287a8e979a0a5733a61bf8a Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 09:46:02 +0300 Subject: [PATCH 002/108] @typescript-eslint/semi --- .eslintrc | 2 +- scripts/authors.ts | 2 +- scripts/buildProtocol.ts | 8 ++++---- scripts/configurePrerelease.ts | 2 +- .../importDefinitelyTypedTests.ts | 12 ++++++------ scripts/open-cherry-pick-pr.ts | 6 +++--- scripts/processDiagnosticMessages.ts | 2 +- src/typingsInstaller/nodeTypingsInstaller.ts | 4 ++-- 8 files changed, 19 insertions(+), 19 deletions(-) diff --git a/.eslintrc b/.eslintrc index 9d473154a846f..769447e12958a 100644 --- a/.eslintrc +++ b/.eslintrc @@ -46,7 +46,7 @@ "@typescript-eslint/prefer-interface": "off", "@typescript-eslint/prefer-namespace-keyword": "off", "semi": "off", - "@typescript-eslint/semi": "off", + "@typescript-eslint/semi": "error", "@typescript-eslint/type-annotation-spacing": "off", "@typescript-eslint/unified-signatures": "off", diff --git a/scripts/authors.ts b/scripts/authors.ts index f92511ed6efdb..c05d7106913b9 100644 --- a/scripts/authors.ts +++ b/scripts/authors.ts @@ -71,7 +71,7 @@ function getKnownAuthorMaps() { } function deduplicate(array: T[]): T[] { - let result: T[] = [] + let result: T[] = []; if (array) { for (const item of array) { if (result.indexOf(item) < 0) { diff --git a/scripts/buildProtocol.ts b/scripts/buildProtocol.ts index 006608323cf1f..08dd56b565788 100644 --- a/scripts/buildProtocol.ts +++ b/scripts/buildProtocol.ts @@ -28,11 +28,11 @@ class DeclarationsWalker { : ""; if (walker.removedTypes) { text += "\ndeclare namespace ts {\n"; - text += " // these types are empty stubs for types from services and should not be used directly\n" + text += " // these types are empty stubs for types from services and should not be used directly\n"; for (const type of walker.removedTypes) { text += ` export type ${type.symbol!.name} = never;\n`; } - text += "}" + text += "}"; } return text; } @@ -142,7 +142,7 @@ function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptSer getCanonicalFileName: function (f) { return f; }, getCurrentDirectory: function() { return '.'; }, getNewLine: function() { return "\r\n"; } - } + }; const diags = emitResult.diagnostics.map(d => ts.formatDiagnostic(d, diagHost)).join("\r\n"); throw new Error(`Declaration file for protocol.ts is not generated:\r\n${diags}`); } @@ -161,7 +161,7 @@ function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptSer return ts.createSourceFile(fileName, protocolDts, options.target); } return originalGetSourceFile.apply(host, [fileName]); - } + }; const rootFiles = includeTypeScriptServices ? [protocolFileName, typeScriptServicesDts] : [protocolFileName]; return ts.createProgram(rootFiles, options, host); } diff --git a/scripts/configurePrerelease.ts b/scripts/configurePrerelease.ts index 5e3ac5653d72e..68befbb8bcd0e 100644 --- a/scripts/configurePrerelease.ts +++ b/scripts/configurePrerelease.ts @@ -48,7 +48,7 @@ function main(): void { // Finally write the changes to disk. // Modify the package.json structure packageJsonValue.version = `${majorMinor}.${prereleasePatch}`; - writeFileSync(packageJsonFilePath, JSON.stringify(packageJsonValue, /*replacer:*/ undefined, /*space:*/ 4)) + writeFileSync(packageJsonFilePath, JSON.stringify(packageJsonValue, /*replacer:*/ undefined, /*space:*/ 4)); writeFileSync(tsFilePath, modifiedTsFileContents); } diff --git a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts index 1ae3725fff211..e984a72a2d0e4 100644 --- a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts +++ b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts @@ -11,16 +11,16 @@ declare var process: { argv: string[]; env: Map; exit(exitCode?: number): void; -} +}; main(); function main() { const [, progName, tscRoot, definitelyTypedRoot] = process.argv; if (process.argv.length !== 4) { if (process.argv.length < 2) { - throw "Expected at least 2 argv elements." + throw "Expected at least 2 argv elements."; } - console.log("Usage:") + console.log("Usage:"); console.log(` node ${path.relative(__dirname, progName)} [TypeScript Repo Root] [DefinitelyTyped Repo Root]`); return; } @@ -52,7 +52,7 @@ function importDefinitelyTypedTest(tscPath: string, rwcTestPath: string, testCas cmd += " @" + responseFile; } - let testDirectoryName = testCaseName + "_" + Math.floor((Math.random() * 10000) + 1); + let testDirectoryName = testCaseName + "_" + Math.floor((Math.random() * 10000) + 1); let testDirectoryPath = path.join(process.env["temp"], testDirectoryName); if (fs.existsSync(testDirectoryPath)) { throw new Error("Could not create test directory"); @@ -156,6 +156,6 @@ function importDefinitelyTypedTests(tscPath: string, rwcTestPath: string, defini } } }); - }) + }); }); -} \ No newline at end of file +} diff --git a/scripts/open-cherry-pick-pr.ts b/scripts/open-cherry-pick-pr.ts index 8bdeb05e4a210..eed8f33d374c6 100644 --- a/scripts/open-cherry-pick-pr.ts +++ b/scripts/open-cherry-pick-pr.ts @@ -34,7 +34,7 @@ async function main() { logText = `Cherry-pick PR #${process.env.SOURCE_ISSUE} into ${process.env.TARGET_BRANCH} Component commits: -${logText.trim()}` +${logText.trim()}`; const logpath = path.join(__dirname, "../", "logmessage.txt"); runSequence([ ["git", ["checkout", "-b", "temp-branch"]], @@ -51,7 +51,7 @@ ${logText.trim()}` runSequence([ ["git", ["checkout", process.env.TARGET_BRANCH]], // checkout the target branch ["git", ["checkout", "-b", branchName]], // create a new branch - ["git", ["cherry-pick", squashSha.trim()]], // + ["git", ["cherry-pick", squashSha.trim()]], // ["git", ["remote", "add", "fork", remoteUrl]], // Add the remote fork ["git", ["push", "--set-upstream", "fork", branchName, "-f"]] // push the branch ]); @@ -102,4 +102,4 @@ main().catch(async e => { body: `Hey @${process.env.REQUESTING_USER}, I couldn't open a PR with the cherry-pick. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary)). You may need to squash and pick this PR into ${process.env.TARGET_BRANCH} manually.` }); } -}); \ No newline at end of file +}); diff --git a/scripts/processDiagnosticMessages.ts b/scripts/processDiagnosticMessages.ts index f296a62de78ed..cc93117f4d0e6 100644 --- a/scripts/processDiagnosticMessages.ts +++ b/scripts/processDiagnosticMessages.ts @@ -20,7 +20,7 @@ function main(): void { function writeFile(fileName: string, contents: string) { fs.writeFile(path.join(path.dirname(inputFilePath), fileName), contents, { encoding: "utf-8" }, err => { if (err) throw err; - }) + }); } const inputFilePath = process.argv[2].replace(/\\/g, "/"); diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 27be0107d8f40..56b490e709d54 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -15,7 +15,7 @@ namespace ts.server.typingsInstaller { isEnabled = () => { return typeof this.logFile === "string"; - } + }; writeLine = (text: string) => { if (typeof this.logFile !== "string") return; @@ -25,7 +25,7 @@ namespace ts.server.typingsInstaller { catch (e) { this.logFile = undefined; } - } + }; } /** Used if `--npmLocation` is not passed. */ From 1ccb4d2d82e6e184c5f66a2438f5ac9a513a1501 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:00:33 +0300 Subject: [PATCH 003/108] microsoft-typescript/debug-assert --- .eslintrc | 2 +- src/services/services.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.eslintrc b/.eslintrc index 769447e12958a..8e1f6d2486c5d 100644 --- a/.eslintrc +++ b/.eslintrc @@ -57,7 +57,7 @@ "microsoft-typescript/no-double-space": "off", "microsoft-typescript/boolean-trivia": "off", "microsoft-typescript/no-in-operator": "off", - "microsoft-typescript/debug-assert": "off", + "microsoft-typescript/debug-assert": "error", "microsoft-typescript/no-keywords": "off", "arrow-body-style": "off", diff --git a/src/services/services.ts b/src/services/services.ts index 6c882bbb28f0e..f5808731791c8 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -35,7 +35,7 @@ namespace ts { } private assertHasRealPosition(message?: string) { - // tslint:disable-next-line:debug-assert + // eslint-disable-next-line microsoft-typescript/debug-assert Debug.assert(!positionIsSynthesized(this.pos) && !positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); } From f96fb53e4c5ad699451740786ad8c4cea22941ed Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:12:06 +0300 Subject: [PATCH 004/108] no-restricted-globals --- .eslintrc | 8 +++++++- src/harness/harnessLanguageService.ts | 5 ++++- src/testRunner/parallel/host.ts | 9 ++++++--- src/tsserver/server.ts | 6 +++++- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/.eslintrc b/.eslintrc index 8e1f6d2486c5d..edd1712fc983f 100644 --- a/.eslintrc +++ b/.eslintrc @@ -92,7 +92,13 @@ "no-new-wrappers": "error", "no-redeclare": "off", "no-return-await": "error", - "no-restricted-globals": "off", + "no-restricted-globals": ["error", + { "name": "setTimeout" }, + { "name": "setInterval" }, + { "name": "clearTimeout" }, + { "name": "setImmediate" }, + { "name": "clearImmediate" } + ], "no-sequences": "off", "no-shadow": "off", "no-sparse-arrays": "error", diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 03ccbb5d6de93..897cbddbf3e00 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -769,19 +769,22 @@ namespace Harness.LanguageService { } setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any { - // tslint:disable-next-line:ban + // eslint-disable-next-line no-restricted-globals return setTimeout(callback, ms, args); } clearTimeout(timeoutId: any): void { + // eslint-disable-next-line no-restricted-globals clearTimeout(timeoutId); } setImmediate(callback: (...args: any[]) => void, _ms: number, ...args: any[]): any { + // eslint-disable-next-line no-restricted-globals return setImmediate(callback, args); } clearImmediate(timeoutId: any): void { + // eslint-disable-next-line no-restricted-globals clearImmediate(timeoutId); } diff --git a/src/testRunner/parallel/host.ts b/src/testRunner/parallel/host.ts index 3e531561e581a..1f0205e2b5bb6 100644 --- a/src/testRunner/parallel/host.ts +++ b/src/testRunner/parallel/host.ts @@ -297,12 +297,15 @@ namespace Harness.Parallel.Host { return process.exit(2); } case "timeout": { - if (worker.timer) clearTimeout(worker.timer); + if (worker.timer) { + // eslint-disable-next-line no-restricted-globals + clearTimeout(worker.timer); + } if (data.payload.duration === "reset") { worker.timer = undefined; } else { - // tslint:disable-next-line:ban + // eslint-disable-next-line no-restricted-globals worker.timer = setTimeout(killChild, data.payload.duration, data.payload); } break; @@ -624,7 +627,7 @@ namespace Harness.Parallel.Host { shimNoopTestInterface(global); } - // tslint:disable-next-line:ban + // eslint-disable-next-line no-restricted-globals setTimeout(() => startDelayed(perfData, totalCost), 0); // Do real startup on next tick, so all unit tests have been collected } } diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 43dc4638418ab..ad999091919fa 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -482,6 +482,7 @@ namespace ts.server { // so we defer until the next tick. // // Construction should finish before the next tick fires, so we do not need to do this recursively. + // eslint-disable-next-line no-restricted-globals setImmediate(() => this.event(body, eventName)); } }; @@ -698,7 +699,7 @@ namespace ts.server { // stat due to inconsistencies of fs.watch // and efficiency of stat on modern filesystems function startWatchTimer() { - // tslint:disable-next-line:ban + // eslint-disable-next-line no-restricted-globals setInterval(() => { let count = 0; let nextToCheck = nextFileToCheck; @@ -881,10 +882,13 @@ namespace ts.server { }; }; + /* eslint-disable no-restricted-globals */ sys.setTimeout = setTimeout; sys.clearTimeout = clearTimeout; sys.setImmediate = setImmediate; sys.clearImmediate = clearImmediate; + /* eslint-enable no-restricted-globals */ + if (typeof global !== "undefined" && global.gc) { sys.gc = () => global.gc(); } From d8796d5eaf8a9bc7c8bd6114d84612c0f6288c28 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:16:19 +0300 Subject: [PATCH 005/108] @typescript-eslint/no-this-alias --- .eslintrc | 2 +- src/testRunner/externalCompileRunner.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.eslintrc b/.eslintrc index edd1712fc983f..966f58e82e39b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -35,7 +35,7 @@ "@typescript-eslint/no-namespace": "off", "@typescript-eslint/no-object-literal-type-assertion": "off", "@typescript-eslint/no-parameter-properties": "off", - "@typescript-eslint/no-this-alias": "off", + "@typescript-eslint/no-this-alias": "error", "@typescript-eslint/no-triple-slash-reference": "off", "@typescript-eslint/no-unnecessary-qualifier": "off", "@typescript-eslint/no-unnecessary-type-assertion": "off", diff --git a/src/testRunner/externalCompileRunner.ts b/src/testRunner/externalCompileRunner.ts index c3b2ef3e6ec29..f21d7ea9b90d2 100644 --- a/src/testRunner/externalCompileRunner.ts +++ b/src/testRunner/externalCompileRunner.ts @@ -26,7 +26,7 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { // Read in and evaluate the test list const testList = this.tests && this.tests.length ? this.tests : this.enumerateTestFiles(); - // tslint:disable-next-line:no-this-assignment + // eslint-disable-next-line @typescript-eslint/no-this-alias const cls = this; describe(`${this.kind()} code samples`, function(this: Mocha.ISuiteCallbackContext) { this.timeout(600_000); // 10 minutes @@ -36,7 +36,7 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { }); } private runTest(directoryName: string) { - // tslint:disable-next-line:no-this-assignment + // eslint-disable-next-line @typescript-eslint/no-this-alias const cls = this; const timeout = 600_000; // 10 minutes describe(directoryName, function(this: Mocha.ISuiteCallbackContext) { From 123ca0d6394200f5b5401248593e522950ca5ebc Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:21:51 +0300 Subject: [PATCH 006/108] no-empty --- .eslintrc | 2 +- src/compiler/builder.ts | 2 +- src/server/session.ts | 2 +- src/testRunner/unittests/builder.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.eslintrc b/.eslintrc index 966f58e82e39b..bef1efdd3e634 100644 --- a/.eslintrc +++ b/.eslintrc @@ -82,7 +82,7 @@ "no-debugger": "off", "no-duplicate-case": "error", "no-duplicate-imports": "error", - "no-empty": "off", + "no-empty": "error", "no-eval": "off", "no-extra-bind": "error", "no-fallthrough": "off", diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index d4c2132d36baa..066db10098317 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -957,7 +957,7 @@ namespace ts { // When semantic builder asks for diagnostics of the whole program, // ensure that all the affected files are handled - // tslint:disable-next-line no-empty + // eslint-disable-next-line no-empty while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) { } diff --git a/src/server/session.ts b/src/server/session.ts index 2e9d6948b1a5c..90c8fbdea9fde 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -669,7 +669,7 @@ namespace ts.server { msg += `\n\nFile text of ${fileRequest.file}:${indent(text)}\n`; } } - catch { } // tslint:disable-line no-empty + catch { } // eslint-disable-line no-empty } if (err.message && err.message.indexOf(`Could not find sourceFile:`) !== -1) { diff --git a/src/testRunner/unittests/builder.ts b/src/testRunner/unittests/builder.ts index 709222a4dff92..962ee037f875b 100644 --- a/src/testRunner/unittests/builder.ts +++ b/src/testRunner/unittests/builder.ts @@ -78,7 +78,7 @@ namespace ts { const program = getProgram(); builderProgram = createEmitAndSemanticDiagnosticsBuilderProgram(program, host, builderProgram); const outputFileNames: string[] = []; - // tslint:disable-next-line no-empty + // eslint-disable-next-line no-empty while (builderProgram.emitNextAffectedFile(fileName => outputFileNames.push(fileName))) { } assert.deepEqual(outputFileNames, fileNames); From 1cc0ff22c1a7371299f926b0d863de3ab8bb7a4b Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:25:02 +0300 Subject: [PATCH 007/108] no-eval --- .eslintrc | 2 +- src/harness/evaluator.ts | 4 ++-- src/harness/fourslash.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.eslintrc b/.eslintrc index bef1efdd3e634..4ae3557076454 100644 --- a/.eslintrc +++ b/.eslintrc @@ -83,7 +83,7 @@ "no-duplicate-case": "error", "no-duplicate-imports": "error", "no-empty": "error", - "no-eval": "off", + "no-eval": "error", "no-extra-bind": "error", "no-fallthrough": "off", "no-invalid-this": "off", diff --git a/src/harness/evaluator.ts b/src/harness/evaluator.ts index a22bdb958bc5f..32314d1dbd81a 100644 --- a/src/harness/evaluator.ts +++ b/src/harness/evaluator.ts @@ -56,7 +56,7 @@ namespace evaluator { } const evaluateText = `(function (module, exports, require, __dirname, __filename, ${globalNames.join(", ")}) { ${output.text} })`; - // tslint:disable-next-line:no-eval + // eslint-disable-next-line no-eval const evaluateThunk = eval(evaluateText) as (module: any, exports: any, require: (id: string) => any, dirname: string, filename: string, ...globalArgs: any[]) => void; const module: { exports: any; } = { exports: {} }; evaluateThunk.call(globals, module, module.exports, noRequire, vpath.dirname(output.file), output.file, FakeSymbol, ...globalArgs); @@ -66,4 +66,4 @@ namespace evaluator { export function evaluateTypeScript(sourceText: string, options?: ts.CompilerOptions, globals?: Record) { return evaluate(compile(sourceText, options), globals); } -} \ No newline at end of file +} diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 345709ca550df..bac70e8b7a0b3 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -3193,7 +3193,7 @@ ${code} const debug = new FourSlashInterface.Debug(state); const format = new FourSlashInterface.Format(state); const cancellation = new FourSlashInterface.Cancellation(state); - // tslint:disable-next-line:no-eval + // eslint-disable-next-line no-eval const f = eval(wrappedCode); f(test, goTo, plugins, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlashInterface.Completion, verifyOperationIsCancelled); } From d7f5def5a33cc5b542d0f726569f8e6b1a06ccf5 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:33:03 +0300 Subject: [PATCH 008/108] space-in-parens --- .eslintrc | 2 +- .../importDefinitelyTypedTests/importDefinitelyTypedTests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.eslintrc b/.eslintrc index 4ae3557076454..3e66ec82df38f 100644 --- a/.eslintrc +++ b/.eslintrc @@ -119,7 +119,7 @@ "radix": "off", "sort-keys": "off", "space-before-function-paren": "off", - "space-in-parens": "off", + "space-in-parens": "error", "unicode-bom": ["error", "never"], "use-isnan": "error", "valid-typeof": "off" diff --git a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts index e984a72a2d0e4..3fa36faab2f66 100644 --- a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts +++ b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts @@ -46,7 +46,7 @@ function copyFileSync(source: string, destination: string) { fs.writeFileSync(destination, text); } -function importDefinitelyTypedTest(tscPath: string, rwcTestPath: string, testCaseName: string, testFiles: string[], responseFile: string ) { +function importDefinitelyTypedTest(tscPath: string, rwcTestPath: string, testCaseName: string, testFiles: string[], responseFile: string) { let cmd = "node " + tscPath + " --module commonjs " + testFiles.join(" "); if (responseFile) { cmd += " @" + responseFile; From 8896c676beee3ab471058c05251c655028fbd2e9 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:38:45 +0300 Subject: [PATCH 009/108] object-shorthand --- .eslintrc | 2 +- scripts/buildProtocol.ts | 6 +++--- scripts/word2md.ts | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.eslintrc b/.eslintrc index 3e66ec82df38f..87c93f7030bea 100644 --- a/.eslintrc +++ b/.eslintrc @@ -110,7 +110,7 @@ "no-unused-expressions": "off", "no-unused-labels": "error", "no-var": "off", - "object-shorthand": "off", + "object-shorthand": "error", "one-var": "off", "prefer-const": "off", "prefer-object-spread": "error", diff --git a/scripts/buildProtocol.ts b/scripts/buildProtocol.ts index 08dd56b565788..b25574ef37913 100644 --- a/scripts/buildProtocol.ts +++ b/scripts/buildProtocol.ts @@ -139,9 +139,9 @@ function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptSer if (protocolDts === undefined) { const diagHost: ts.FormatDiagnosticsHost = { - getCanonicalFileName: function (f) { return f; }, - getCurrentDirectory: function() { return '.'; }, - getNewLine: function() { return "\r\n"; } + getCanonicalFileName(f) { return f; }, + getCurrentDirectory() { return '.'; }, + getNewLine() { return "\r\n"; } }; const diags = emitResult.diagnostics.map(d => ts.formatDiagnostic(d, diagHost)).join("\r\n"); throw new Error(`Declaration file for protocol.ts is not generated:\r\n${diags}`); diff --git a/scripts/word2md.ts b/scripts/word2md.ts index f602c700ff9cb..e9a41dfa39ad7 100644 --- a/scripts/word2md.ts +++ b/scripts/word2md.ts @@ -141,7 +141,7 @@ var sys = (function () { args[i] = WScript.Arguments.Item(i); } return { - args: args, + args, createObject: (typeName: string) => new ActiveXObject(typeName), write(s: string): void { WScript.StdOut.Write(s); From 550a99e839c5ae8ddf3964fe134cd5cbaffa94c2 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:44:19 +0300 Subject: [PATCH 010/108] dot-notation --- .eslintrc | 2 +- scripts/authors.ts | 2 +- scripts/errorCheck.ts | 6 +++--- .../importDefinitelyTypedTests.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.eslintrc b/.eslintrc index 87c93f7030bea..feb8cd9754aa8 100644 --- a/.eslintrc +++ b/.eslintrc @@ -67,7 +67,7 @@ "complexity": "off", "constructor-super": "error", "curly": ["error", "multi-line"], - "dot-notation": "off", + "dot-notation": "error", "eol-last": "off", "eqeqeq": "error", "guard-for-in": "off", diff --git a/scripts/authors.ts b/scripts/authors.ts index c05d7106913b9..34b7ab766b551 100644 --- a/scripts/authors.ts +++ b/scripts/authors.ts @@ -169,7 +169,7 @@ var args = process.argv.slice(2); if (args.length < 1) { console.log('Usage: node authors.js [command]'); console.log('List of commands: '); - Object.keys(Commands).forEach(k => console.log(` ${k}: ${(Commands as any)[k]['description']}`)); + Object.keys(Commands).forEach(k => console.log(` ${k}: ${(Commands as any)[k].description}`)); } else { var cmd: Function = (Commands as any)[args[0]]; if (cmd === undefined) { diff --git a/scripts/errorCheck.ts b/scripts/errorCheck.ts index a5cb27417f16e..92e738c00ba6b 100644 --- a/scripts/errorCheck.ts +++ b/scripts/errorCheck.ts @@ -13,7 +13,7 @@ fs.readFile('src/compiler/diagnosticMessages.json', 'utf-8', (err, data) => { console.log('Loaded ' + keys.length + ' errors'); for (let k of keys) { - messages[k]['seen'] = false; + messages[k].seen = false; } let errRegex = /\(\d+,\d+\): error TS([^:]+):/g; @@ -30,7 +30,7 @@ fs.readFile('src/compiler/diagnosticMessages.json', 'utf-8', (err, data) => { while (g = errRegex.exec(baseline)) { var errCode = +g[1]; let msg = keys.filter(k => messages[k].code === errCode)[0]; - messages[msg]['seen'] = true; + messages[msg].seen = true; } done(); @@ -41,7 +41,7 @@ fs.readFile('src/compiler/diagnosticMessages.json', 'utf-8', (err, data) => { console.log('== List of errors not present in baselines =='); let count = 0; for (let k of keys) { - if (messages[k]['seen'] !== true) { + if (messages[k].seen !== true) { console.log(k); count++; } diff --git a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts index 3fa36faab2f66..f14eff609b109 100644 --- a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts +++ b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts @@ -53,7 +53,7 @@ function importDefinitelyTypedTest(tscPath: string, rwcTestPath: string, testCas } let testDirectoryName = testCaseName + "_" + Math.floor((Math.random() * 10000) + 1); - let testDirectoryPath = path.join(process.env["temp"], testDirectoryName); + let testDirectoryPath = path.join(process.env.temp, testDirectoryName); if (fs.existsSync(testDirectoryPath)) { throw new Error("Could not create test directory"); } From bea1bcb466a840f34aae3917e0b7e7d24cf605c9 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:51:09 +0300 Subject: [PATCH 011/108] brace-style --- .eslintrc | 2 +- scripts/authors.ts | 6 ++++-- scripts/bisect-test.ts | 16 ++++++++++------ src/testRunner/rwcRunner.ts | 3 ++- src/testRunner/unittests/tsserver/projects.ts | 9 ++++++--- src/tsserver/server.ts | 11 ++++------- 6 files changed, 27 insertions(+), 20 deletions(-) diff --git a/.eslintrc b/.eslintrc index feb8cd9754aa8..04d9c7ce38de2 100644 --- a/.eslintrc +++ b/.eslintrc @@ -62,7 +62,7 @@ "arrow-body-style": "off", "arrow-parens": "off", - "brace-style": "off", + "brace-style": ["error", "stroustrup", { "allowSingleLine": true }], "comma-dangle": "off", "complexity": "off", "constructor-super": "error", diff --git a/scripts/authors.ts b/scripts/authors.ts index 34b7ab766b551..0c88d1f434502 100644 --- a/scripts/authors.ts +++ b/scripts/authors.ts @@ -170,11 +170,13 @@ if (args.length < 1) { console.log('Usage: node authors.js [command]'); console.log('List of commands: '); Object.keys(Commands).forEach(k => console.log(` ${k}: ${(Commands as any)[k].description}`)); -} else { +} +else { var cmd: Function = (Commands as any)[args[0]]; if (cmd === undefined) { console.log('Unknown command ' + args[1]); - } else { + } + else { cmd.apply(undefined, args.slice(1)); } } diff --git a/scripts/bisect-test.ts b/scripts/bisect-test.ts index d66e0b7106132..fb56dad9b8513 100644 --- a/scripts/bisect-test.ts +++ b/scripts/bisect-test.ts @@ -25,35 +25,39 @@ jake.on('close', jakeExitCode => { if ((tscExitCode === 0) === (args[1] === 'compiles')) { console.log('Good'); process.exit(0); // Good - } else { + } + else { console.log('Bad'); process.exit(1); // Bad } }); - } else if (args[1] === 'emits' || args[1] === '!emits') { + } + else if (args[1] === 'emits' || args[1] === '!emits') { tsc(args[0], tscExitCode => { fs.readFile(args[2], 'utf-8', (err, data) => { var doesContains = data.indexOf(args[3]) >= 0; if (doesContains === (args[1] === 'emits')) { console.log('Good'); process.exit(0); // Good - } else { + } + else { console.log('Bad'); process.exit(1); // Bad } }); }); - } else { + } + else { console.log('Unknown command line arguments.'); console.log('Usage (compile errors): git bisect run ts-node scripts\bisect-test.ts "../failure.ts --module amd" !compiles'); console.log('Usage (emit check): git bisect run ts-node scripts\bisect-test.ts bar.ts emits bar.js "_this = this"'); // Aborts the 'git bisect run' process process.exit(-1); } - } else { + } + else { // Compiler build failed; skip this commit console.log('Skip'); process.exit(125); // bisect skip } }); - \ No newline at end of file diff --git a/src/testRunner/rwcRunner.ts b/src/testRunner/rwcRunner.ts index 729ed167fffc0..081c11cd0b97b 100644 --- a/src/testRunner/rwcRunner.ts +++ b/src/testRunner/rwcRunner.ts @@ -11,7 +11,8 @@ namespace RWC { try { fn(oldIO); - } finally { + } + finally { wrappedIO.endReplay(); Harness.IO = oldIO; } diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts index 409ce5c525f74..0e349bd1cdbcb 100644 --- a/src/testRunner/unittests/tsserver/projects.ts +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -366,7 +366,8 @@ namespace ts.projectSystem { const proj = projectService.externalProjects[0]; assert.deepEqual(proj.getFileNames(/*excludeFilesFromExternalLibraries*/ true), [file1.path]); assert.deepEqual(proj.getTypeAcquisition().include, ["duck-types"]); - } finally { + } + finally { projectService.resetSafeList(); } }); @@ -464,7 +465,8 @@ namespace ts.projectSystem { const proj = projectService.externalProjects[0]; assert.deepEqual(proj.getFileNames(/*excludeFilesFromExternalLibraries*/ true), [file1.path]); assert.deepEqual(proj.getTypeAcquisition().include, ["kendo-ui", "office"]); - } finally { + } + finally { projectService.resetSafeList(); } }); @@ -504,7 +506,8 @@ namespace ts.projectSystem { projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles([file1.path, file2.path]), typeAcquisition: { enable: true } }); const proj = projectService.externalProjects[0]; assert.deepEqual(proj.getFileNames(), [file2.path]); - } finally { + } + finally { projectService.resetSafeList(); } }); diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index ad999091919fa..ad4d30a203aa0 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -911,14 +911,11 @@ namespace ts.server { cancellationToken = nullCancellationToken; } - let eventPort: number | undefined; - { - const str = findArgument("--eventPort"); - const v = str === undefined ? undefined : parseInt(str); - if (v !== undefined && !isNaN(v)) { - eventPort = v; - } + function parseEventPort(eventPortStr: string | undefined) { + const eventPort = eventPortStr === undefined ? undefined : parseInt(eventPortStr); + return eventPort !== undefined && !isNaN(eventPort) ? eventPort : undefined; } + const eventPort: number | undefined = parseEventPort(findArgument("--eventPort")); const localeStr = findArgument("--locale"); if (localeStr) { From 12e195c24e2a3b11c1c679d4227bde3218fef0e5 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 10:54:11 +0300 Subject: [PATCH 012/108] no-throw-literal --- .eslintrc | 2 +- .../importDefinitelyTypedTests/importDefinitelyTypedTests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.eslintrc b/.eslintrc index 04d9c7ce38de2..ca3ca2a7da5a8 100644 --- a/.eslintrc +++ b/.eslintrc @@ -103,7 +103,7 @@ "no-shadow": "off", "no-sparse-arrays": "error", "no-template-curly-in-string": "off", - "no-throw-literal": "off", + "no-throw-literal": "error", "no-trailing-spaces": "off", "no-undef-init": "error", "no-unsafe-finally": "error", diff --git a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts index f14eff609b109..9291714e929f9 100644 --- a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts +++ b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts @@ -18,7 +18,7 @@ function main() { const [, progName, tscRoot, definitelyTypedRoot] = process.argv; if (process.argv.length !== 4) { if (process.argv.length < 2) { - throw "Expected at least 2 argv elements."; + throw new Error("Expected at least 2 argv elements."); } console.log("Usage:"); console.log(` node ${path.relative(__dirname, progName)} [TypeScript Repo Root] [DefinitelyTyped Repo Root]`); From 4e6fb72737759f6004dfe970cdde9361950f0af6 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:02:15 +0300 Subject: [PATCH 013/108] no-new-func --- .eslintrc | 2 +- src/harness/fourslash.ts | 2 +- src/harness/harness.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.eslintrc b/.eslintrc index ca3ca2a7da5a8..03beb28578392 100644 --- a/.eslintrc +++ b/.eslintrc @@ -88,7 +88,7 @@ "no-fallthrough": "off", "no-invalid-this": "off", "no-multiple-empty-lines": "off", - "no-new-func": "off", + "no-new-func": "error", "no-new-wrappers": "error", "no-redeclare": "off", "no-return-await": "error", diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index bac70e8b7a0b3..80fb27508d928 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -600,7 +600,7 @@ namespace FourSlash { throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName); } - const evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)(); // tslint:disable-line:function-constructor + const evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)(); // eslint-disable-line no-new-func if (evaluation !== value) { this.raiseError(`Expected evaluation of expression "${expr}" to equal "${value}", but got "${evaluation}"`); } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index f03103d023938..029ff5c593d05 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -28,7 +28,7 @@ var assert: typeof _chai.assert = _chai.assert; }; } -var global: NodeJS.Global = Function("return this").call(undefined); // tslint:disable-line:function-constructor +var global: NodeJS.Global = Function("return this").call(undefined); // eslint-disable-line no-new-func declare var window: {}; declare var XMLHttpRequest: new() => XMLHttpRequest; From a96a08a3291b73124b49a70e0aedd7c522f16435 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:17:49 +0300 Subject: [PATCH 014/108] microsoft-typescript/boolean-trivia --- .eslintrc | 2 +- scripts/word2md.ts | 15 +++++++++++++-- src/compiler/sourcemap.ts | 2 +- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.eslintrc b/.eslintrc index 03beb28578392..7ccca7425f019 100644 --- a/.eslintrc +++ b/.eslintrc @@ -55,7 +55,7 @@ "microsoft-typescript/type-operator-spacing": "off", "microsoft-typescript/only-arrow-functions": "off", "microsoft-typescript/no-double-space": "off", - "microsoft-typescript/boolean-trivia": "off", + "microsoft-typescript/boolean-trivia": "error", "microsoft-typescript/no-in-operator": "off", "microsoft-typescript/debug-assert": "error", "microsoft-typescript/no-keywords": "off", diff --git a/scripts/word2md.ts b/scripts/word2md.ts index e9a41dfa39ad7..8d651ecfcc73d 100644 --- a/scripts/word2md.ts +++ b/scripts/word2md.ts @@ -205,7 +205,18 @@ function convertDocumentToMarkdown(doc: Word.Document): string { var replace = find.replacement; replace.clearFormatting(); setProperties(replace, replaceOptions); - find.execute(findText, false, false, false, false, false, true, 0, true, replaceText, 2); + find.execute(findText, + /* matchCase */ false, + /* matchWholeWord */ false, + /* matchWildcards */ false, + /* matchSoundsLike */ false, + /* matchAllWordForms */ false, + /* forward */ true, + 0, + /* format */ true, + replaceText, + 2 + ); } function fixHyperlinks() { @@ -405,7 +416,7 @@ function main(args: string[]) { var app: Word.Application = sys.createObject("Word.Application"); var doc = app.documents.open(args[0]); sys.writeFile(args[1], convertDocumentToMarkdown(doc)); - doc.close(false); + doc.close(/* saveChanges */ false); app.quit(); } diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index b33536bab2a5e..e592437171e87 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -73,7 +73,7 @@ namespace ts { if (content !== null) { if (!sourcesContent) sourcesContent = []; while (sourcesContent.length < sourceIndex) { - // tslint:disable-next-line:no-null-keyword boolean-trivia + // eslint-disable-next-line microsoft-typescript/boolean-trivia sourcesContent.push(null); } sourcesContent[sourceIndex] = content; From 3fb48d3f24905d68c345358b9fc75031384fb9bd Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:21:43 +0300 Subject: [PATCH 015/108] @typescript-eslint/no-inferrable-types --- .eslintrc | 2 +- scripts/errorCheck.ts | 2 +- scripts/word2md.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.eslintrc b/.eslintrc index 7ccca7425f019..78d24476c139c 100644 --- a/.eslintrc +++ b/.eslintrc @@ -30,7 +30,7 @@ "@typescript-eslint/no-angle-bracket-type-assertion": "off", "@typescript-eslint/no-empty-interface": "off", "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-inferrable-types": "off", + "@typescript-eslint/no-inferrable-types": "error", "@typescript-eslint/no-misused-new": "error", "@typescript-eslint/no-namespace": "off", "@typescript-eslint/no-object-literal-type-assertion": "off", diff --git a/scripts/errorCheck.ts b/scripts/errorCheck.ts index 92e738c00ba6b..4c1dbf7af3525 100644 --- a/scripts/errorCheck.ts +++ b/scripts/errorCheck.ts @@ -59,7 +59,7 @@ fs.readFile('src/compiler/diagnosticInformationMap.generated.ts', 'utf-8', (err, errorNames.push(errMatch[1]); } - let allSrc: string = ''; + let allSrc = ''; glob('./src/**/*.ts', {}, (err, files) => { console.log('Reading ' + files.length + ' source files'); for (let file of files) { diff --git a/scripts/word2md.ts b/scripts/word2md.ts index 8d651ecfcc73d..bba748084c144 100644 --- a/scripts/word2md.ts +++ b/scripts/word2md.ts @@ -177,7 +177,7 @@ interface FindReplaceOptions { function convertDocumentToMarkdown(doc: Word.Document): string { - var result: string = ""; + var result = ""; var lastStyle: string; var lastInTable: boolean; var tableColumnCount: number; From afb5c9bfcf7a1a0f0f2e89167de2f2179db53585 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:25:18 +0300 Subject: [PATCH 016/108] @typescript-eslint/prefer-interface --- .eslintrc | 2 +- scripts/authors.ts | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.eslintrc b/.eslintrc index 78d24476c139c..8c5e5ae2ebba9 100644 --- a/.eslintrc +++ b/.eslintrc @@ -43,7 +43,7 @@ "@typescript-eslint/no-var-requires": "off", "@typescript-eslint/prefer-for-of": "error", "@typescript-eslint/prefer-function-type": "off", - "@typescript-eslint/prefer-interface": "off", + "@typescript-eslint/prefer-interface": "error", "@typescript-eslint/prefer-namespace-keyword": "off", "semi": "off", "@typescript-eslint/semi": "error", diff --git a/scripts/authors.ts b/scripts/authors.ts index 0c88d1f434502..639b5e4008644 100644 --- a/scripts/authors.ts +++ b/scripts/authors.ts @@ -2,15 +2,17 @@ import fs = require('fs'); import path = require('path'); import child_process = require("child_process"); -type Author = { +interface Author { displayNames: string[]; preferredName?: string; emails: string[]; }; -type AuthorMap = { [s: string]: Author }; +interface AuthorMap { + [s: string]: Author +}; -type Command = { +interface Command { (...arg: string[]): void; description?: string; }; From c3517c073e22601f576ac1d28dc4c30fe8c9dd4e Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:29:00 +0300 Subject: [PATCH 017/108] @typescript-eslint/type-annotation-spacing --- .eslintrc | 2 +- scripts/authors.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.eslintrc b/.eslintrc index 8c5e5ae2ebba9..fa822cf9122a9 100644 --- a/.eslintrc +++ b/.eslintrc @@ -47,7 +47,7 @@ "@typescript-eslint/prefer-namespace-keyword": "off", "semi": "off", "@typescript-eslint/semi": "error", - "@typescript-eslint/type-annotation-spacing": "off", + "@typescript-eslint/type-annotation-spacing": "error", "@typescript-eslint/unified-signatures": "off", "microsoft-typescript/object-literal-surrounding-space": "off", diff --git a/scripts/authors.ts b/scripts/authors.ts index 639b5e4008644..72f2997f6b71f 100644 --- a/scripts/authors.ts +++ b/scripts/authors.ts @@ -111,7 +111,7 @@ namespace Commands { }; listKnownAuthors.description = "List known authors as listed in .mailmap file."; - export const listAuthors: Command = function (...specs:string[]) { + export const listAuthors: Command = function (...specs: string[]) { const cmd = "git shortlog -se " + specs.join(" "); console.log(cmd); const outputRegExp = /\d+\s+([^<]+)<([^>]+)>/; From f1a399b3911ae0f196475dff9901bfa87b76a373 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:40:10 +0300 Subject: [PATCH 018/108] exclude *.generated.d.ts files --- .eslintignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.eslintignore b/.eslintignore index ffe06abf2d682..404b4177c9773 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,4 @@ /built/local/** /tests/** -/lib/** \ No newline at end of file +/lib/** +/src/lib/*.generated.d.ts \ No newline at end of file From 012c76e8970d0c02b505a884a64cb089fef098de Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:45:45 +0300 Subject: [PATCH 019/108] microsoft-typescript/object-literal-surrounding-space --- .eslintrc | 2 +- scripts/word2md.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.eslintrc b/.eslintrc index fa822cf9122a9..b59cdc47dca41 100644 --- a/.eslintrc +++ b/.eslintrc @@ -50,7 +50,7 @@ "@typescript-eslint/type-annotation-spacing": "error", "@typescript-eslint/unified-signatures": "off", - "microsoft-typescript/object-literal-surrounding-space": "off", + "microsoft-typescript/object-literal-surrounding-space": "error", "microsoft-typescript/no-type-assertion-whitespace": "error", "microsoft-typescript/type-operator-spacing": "off", "microsoft-typescript/only-arrow-functions": "off", diff --git a/scripts/word2md.ts b/scripts/word2md.ts index bba748084c144..8b63b1a08ac32 100644 --- a/scripts/word2md.ts +++ b/scripts/word2md.ts @@ -388,8 +388,8 @@ function convertDocumentToMarkdown(doc: Word.Document): string { findReplace("<", { style: "Terminal" }, "<", {}); findReplace("", { font: { subscript: true } }, "^&", { font: { subscript: false } }); findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 /* default font */ }); - findReplace("", { style: "Production" }, "*^&*", { style: -66 /* default font */}); - findReplace("", { style: "Terminal" }, "`^&`", { style: -66 /* default font */}); + findReplace("", { style: "Production" }, "*^&*", { style: -66 /* default font */ }); + findReplace("", { style: "Terminal" }, "`^&`", { style: -66 /* default font */ }); findReplace("", { font: { bold: true, italic: true } }, "***^&***", { font: { bold: false, italic: false } }); findReplace("", { font: { italic: true } }, "*^&*", { font: { italic: false } }); From 65ddc1fef2722aafd320fa80cdb3abe9fef5b42e Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:48:52 +0300 Subject: [PATCH 020/108] microsoft-typescript/type-operator-spacing --- .eslintrc | 2 +- src/lib/es2019.array.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.eslintrc b/.eslintrc index b59cdc47dca41..f873c3c76195c 100644 --- a/.eslintrc +++ b/.eslintrc @@ -52,7 +52,7 @@ "microsoft-typescript/object-literal-surrounding-space": "error", "microsoft-typescript/no-type-assertion-whitespace": "error", - "microsoft-typescript/type-operator-spacing": "off", + "microsoft-typescript/type-operator-spacing": "error", "microsoft-typescript/only-arrow-functions": "off", "microsoft-typescript/no-double-space": "off", "microsoft-typescript/boolean-trivia": "error", diff --git a/src/lib/es2019.array.d.ts b/src/lib/es2019.array.d.ts index 33bee0c205efe..07fc76a9c77b5 100644 --- a/src/lib/es2019.array.d.ts +++ b/src/lib/es2019.array.d.ts @@ -11,7 +11,7 @@ interface ReadonlyArray { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, + callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, thisArg?: This ): U[] @@ -125,7 +125,7 @@ interface Array { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, + callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, thisArg?: This ): U[] From f611ec68ed1cf7fe42ccd61853a2f8b424c6d774 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:52:48 +0300 Subject: [PATCH 021/108] microsoft-typescript/no-double-space --- .eslintrc | 2 +- src/lib/es2015.core.d.ts | 2 +- src/lib/es2017.object.d.ts | 2 +- src/services/signatureHelp.ts | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.eslintrc b/.eslintrc index f873c3c76195c..4cf339e94d8d4 100644 --- a/.eslintrc +++ b/.eslintrc @@ -54,7 +54,7 @@ "microsoft-typescript/no-type-assertion-whitespace": "error", "microsoft-typescript/type-operator-spacing": "error", "microsoft-typescript/only-arrow-functions": "off", - "microsoft-typescript/no-double-space": "off", + "microsoft-typescript/no-double-space": "error", "microsoft-typescript/boolean-trivia": "error", "microsoft-typescript/no-in-operator": "off", "microsoft-typescript/debug-assert": "error", diff --git a/src/lib/es2015.core.d.ts b/src/lib/es2015.core.d.ts index 4d48d5cf40aaf..2f337b0eecf7c 100644 --- a/src/lib/es2015.core.d.ts +++ b/src/lib/es2015.core.d.ts @@ -312,7 +312,7 @@ interface ObjectConstructor { is(value1: any, value2: any): boolean; /** - * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * Sets the prototype of a specified object o to object proto or null. Returns the object o. * @param o The object to change its prototype. * @param proto The value of the new prototype or null. */ diff --git a/src/lib/es2017.object.d.ts b/src/lib/es2017.object.d.ts index 1790ce76894af..b3ace85bef182 100644 --- a/src/lib/es2017.object.d.ts +++ b/src/lib/es2017.object.d.ts @@ -3,7 +3,7 @@ interface ObjectConstructor { * Returns an array of values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - values(o: { [s: string]: T } | ArrayLike): T[]; + values(o: { [s: string]: T } | ArrayLike): T[]; /** * Returns an array of values of the enumerable properties of an object diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 998e45bd4616c..40d4a703dd2c8 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -394,11 +394,11 @@ namespace ts.SignatureHelp { // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // - // tslint:disable no-double-space + /* eslint-disable microsoft-typescript/no-double-space */ // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 - // tslint:enable no-double-space + /* eslint-enable microsoft-typescript/no-double-space */ Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (isTemplateLiteralToken(node)) { if (isInsideTemplateLiteral(node, position, sourceFile)) { From 650600c5e4d7d5a617e40ec65449bb8665676d69 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Fri, 14 Jun 2019 11:58:42 +0300 Subject: [PATCH 022/108] linebreak-style --- .eslintrc | 2 +- .../generateLocalizedDiagnosticMessages.ts | 354 +++++++++--------- src/lib/es2019.symbol.d.ts | 12 +- 3 files changed, 184 insertions(+), 184 deletions(-) diff --git a/.eslintrc b/.eslintrc index 4cf339e94d8d4..7855d4f6277b2 100644 --- a/.eslintrc +++ b/.eslintrc @@ -71,7 +71,7 @@ "eol-last": "off", "eqeqeq": "error", "guard-for-in": "off", - "linebreak-style": "off", + "linebreak-style": ["error", "windows"], "max-classes-per-file": "off", "max-len": "off", "new-parens": "error", diff --git a/scripts/generateLocalizedDiagnosticMessages.ts b/scripts/generateLocalizedDiagnosticMessages.ts index 98bae170baa39..abfe6a3cff93e 100644 --- a/scripts/generateLocalizedDiagnosticMessages.ts +++ b/scripts/generateLocalizedDiagnosticMessages.ts @@ -1,177 +1,177 @@ -import * as fs from "fs"; -import * as path from "path"; -import * as xml2js from "xml2js"; - -function main(): void { - const args = process.argv.slice(2); - if (args.length !== 3) { - console.log("Usage:"); - console.log("\tnode generateLocalizedDiagnosticMessages.js "); - return; - } - - const inputPath = args[0]; - const outputPath = args[1]; - const diagnosticsMapFilePath = args[2]; - - // generate the lcg file for enu - generateLCGFile(); - - // generate other langs - fs.readdir(inputPath, (err, files) => { - handleError(err); - files.forEach(visitDirectory); - }); - - return; - - function visitDirectory(name: string) { - const inputFilePath = path.join(inputPath, name, "diagnosticMessages", "diagnosticMessages.generated.json.lcl"); - - fs.readFile(inputFilePath, (err, data) => { - handleError(err); - xml2js.parseString(data.toString(), (err, result) => { - handleError(err); - if (!result || !result.LCX || !result.LCX.$ || !result.LCX.$.TgtCul) { - console.error("Unexpected XML file structure. Expected to find result.LCX.$.TgtCul."); - process.exit(1); - } - const outputDirectoryName = getPreferredLocaleName(result.LCX.$.TgtCul).toLowerCase(); - if (!outputDirectoryName) { - console.error(`Invalid output locale name for '${result.LCX.$.TgtCul}'.`); - process.exit(1); - } - writeFile(path.join(outputPath, outputDirectoryName, "diagnosticMessages.generated.json"), xmlObjectToString(result)); - }); - }); - } - - /** - * A locale name is based on the language tagging conventions of RFC 4646 (Windows Vista - * and later), and is represented by LOCALE_SNAME. - * Generally, the pattern - is used. Here, language is a lowercase ISO 639 - * language code. The codes from ISO 639-1 are used when available. Otherwise, codes from - * ISO 639-2/T are used. REGION specifies an uppercase ISO 3166-1 country/region identifier. - * For example, the locale name for English (United States) is "en-US" and the locale name - * for Divehi (Maldives) is "dv-MV". - * - * If the locale is a neutral locale (no region), the LOCALE_SNAME value follows the - * pattern . If it is a neutral locale for which the script is significant, the - * pattern is -