From d719037cef35235ba1729c41a82f6d88f3521a8f Mon Sep 17 00:00:00 2001 From: zirkelc Date: Wed, 11 Jan 2023 18:35:20 +0100 Subject: [PATCH 1/8] implement tsc linter --- src/linters/tsc.js | 107 ++++++++++++++++++++++++ test/linters/linters.test.js | 2 + test/linters/params/tsc.js | 97 +++++++++++++++++++++ test/linters/projects/tsc/.gitignore | 1 + test/linters/projects/tsc/file1.ts | 7 ++ test/linters/projects/tsc/file2.ts | 3 + test/linters/projects/tsc/package.json | 8 ++ test/linters/projects/tsc/tsconfig.json | 103 +++++++++++++++++++++++ test/linters/projects/tsc/yarn.lock | 8 ++ 9 files changed, 336 insertions(+) create mode 100644 src/linters/tsc.js create mode 100644 test/linters/params/tsc.js create mode 100644 test/linters/projects/tsc/.gitignore create mode 100644 test/linters/projects/tsc/file1.ts create mode 100644 test/linters/projects/tsc/file2.ts create mode 100644 test/linters/projects/tsc/package.json create mode 100644 test/linters/projects/tsc/tsconfig.json create mode 100644 test/linters/projects/tsc/yarn.lock diff --git a/src/linters/tsc.js b/src/linters/tsc.js new file mode 100644 index 00000000..5912dc30 --- /dev/null +++ b/src/linters/tsc.js @@ -0,0 +1,107 @@ +const { run } = require("../utils/action"); +const commandExists = require("../utils/command-exists"); +const { initLintResult } = require("../utils/lint-result"); +const { getNpmBinCommand } = require("../utils/npm/get-npm-bin-command"); +const { removeTrailingPeriod } = require("../utils/string"); + +/** @typedef {import('../utils/lint-result').LintResult} LintResult */ + +/** + * https://eslint.org + */ +class TSC { + static get name() { + return "TypeScript"; + } + + /** + * Verifies that all required programs are installed. Throws an error if programs are missing + * @param {string} dir - Directory to run the linting program in + * @param {string} prefix - Prefix to the lint command + */ + static async verifySetup(dir, prefix = "") { + // Verify that NPM is installed (required to execute ESLint) + if (!(await commandExists("npm"))) { + throw new Error("NPM is not installed"); + } + + // Verify that ESLint is installed + const commandPrefix = prefix || getNpmBinCommand(dir); + try { + run(`${commandPrefix} tsc -v`, { dir }); + } catch (err) { + throw new Error(`${this.name} is not installed`); + } + } + + /** + * Runs the linting program and returns the command output + * @param {string} dir - Directory to run the linter in + * @param {string[]} extensions - File extensions which should be linted + * @param {string} args - Additional arguments to pass to the linter + * @param {boolean} fix - Whether the linter should attempt to fix code style issues automatically + * @param {string} prefix - Prefix to the lint command + * @returns {{status: number, stdout: string, stderr: string}} - Output of the lint command + */ + static lint(dir, extensions, args = "", fix = false, prefix = "") { + // const extensionsArg = extensions.map((ext) => `.${ext}`).join(","); + // const fixArg = fix ? "--fix" : ""; + const commandPrefix = prefix || getNpmBinCommand(dir); + return run( + `${commandPrefix} tsc --noEmit --pretty false`, + { + dir, + ignoreErrors: true, + }, + ); + } + + /** + * Parses the output of the lint command. Determines the success of the lint process and the + * severity of the identified code style violations + * @param {string} dir - Directory in which the linter has been run + * @param {{status: number, stdout: string, stderr: string}} output - Output of the lint command + * @returns {LintResult} - Parsed lint result + */ + static parseOutput(dir, output) { + const lintResult = initLintResult(); + lintResult.isSuccess = output.status === 0; + +const regex = /^(?.+)\((?\d+),(?\d+)\):\s(?\w+)\s(?.+)$/gm; + + const errors = []; + const matches = output.stdout.matchAll(regex); + + for (const match of matches) { + const { file, line, column, code, message } = match.groups; + errors.push({ file, line, column, code, message }); + } + + + for (const error of errors) { + const { file, line, message } = error; + // const path = file.substring(dir.length + 1); + + // column = column || 0; + + const entry = { + path: file, + firstLine: Number(line), + lastLine: Number(line), + message: `${removeTrailingPeriod(message)}`, + }; + + lintResult.error.push(entry); + // if (severity === 1) { + // lintResult.warning.push(entry); + // } else if (severity === 2) { + // lintResult.error.push(entry); + // } + + } + + return lintResult; + } +} + +module.exports = TSC; diff --git a/test/linters/linters.test.js b/test/linters/linters.test.js index d23303ee..a92030dd 100644 --- a/test/linters/linters.test.js +++ b/test/linters/linters.test.js @@ -22,6 +22,7 @@ const stylelintParams = require("./params/stylelint"); const swiftFormatLockwood = require("./params/swift-format-lockwood"); // const swiftFormatOfficial = require("./params/swift-format-official"); const swiftlintParams = require("./params/swiftlint"); +const tscParams = require("./params/tsc"); const xoParams = require("./params/xo"); const linterParams = [ @@ -41,6 +42,7 @@ const linterParams = [ pylintParams, ruboCopParams, stylelintParams, + tscParams, xoParams, ]; if (process.platform === "linux") { diff --git a/test/linters/params/tsc.js b/test/linters/params/tsc.js new file mode 100644 index 00000000..b95f89b5 --- /dev/null +++ b/test/linters/params/tsc.js @@ -0,0 +1,97 @@ +const TSC = require("../../../src/linters/tsc"); +// const { joinDoubleBackslash } = require("../../test-utils"); + +const testName = "tsc"; +const linter = TSC; +const commandPrefix = ""; +const extensions = ["js"]; + +// Linting without auto-fixing +function getLintParams(dir) { + const stdoutFile1 = `file1.ts(1,5): error TS7034: Variable 'str' implicitly has type 'any' in some locations where its type cannot be determined.\nfile1.ts(4,25): error TS7005: Variable 'str' implicitly has an 'any' type.`; + const stdoutFile2 = `file2.ts(3,1): error TS2322: Type 'string' is not assignable to type 'number'.`; + return { + // Expected output of the linting function + cmdOutput: { + status: 2, + stdoutParts: [stdoutFile1, stdoutFile2], + stdout: `${stdoutFile1}\n${stdoutFile2}`, + }, + // Expected output of the parsing function + lintResult: { + isSuccess: false, + warning: [ + // { + // path: "file1.js", + // firstLine: 5, + // lastLine: 5, + // message: "Unexpected 'todo' comment: 'TODO: Change something' (no-warning-comments)", + // }, + ], + error: [ + { + path: "file1.ts", + firstLine: 1, + lastLine: 1, + message: "TS7034: Variable 'str' implicitly has type 'any' in some locations where its type cannot be determined", + }, + { + path: "file1.ts", + firstLine: 4, + lastLine: 4, + message: "TS7005: Variable 'str' implicitly has an 'any' type", + }, + { + path: "file2.ts", + firstLine: 3, + lastLine: 3, + message: "TS2322: Type 'string' is not assignable to type 'number'", + }, + ], + }, + }; +} + +const getFixParams = getLintParams; + +// // Linting with auto-fixing +// function getFixParams(dir) { +// const stdoutFile1 = `{"filePath":"${joinDoubleBackslash( +// dir, +// "file1.js", +// )}","messages":[{"ruleId":"no-warning-comments","severity":1,"message":"Unexpected 'todo' comment: 'TODO: Change something'.","line":5,"column":31,"nodeType":"Line","messageId":"unexpectedComment","endLine":5,"endColumn":56}],"suppressedMessages":[],"errorCount":0,"fatalErrorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"output":"const str = 'world'; // \\"prefer-const\\" warning\\n\\nfunction main() {\\n\\t// \\"no-warning-comments\\" error\\n\\tconsole.log('hello ' + str); // TODO: Change something\\n}\\n\\nmain();\\n","usedDeprecatedRules":[]}`; +// const stdoutFile2 = `{"filePath":"${joinDoubleBackslash( +// dir, +// "file2.js", +// )}","messages":[{"ruleId":"no-unused-vars","severity":2,"message":"'str' is assigned a value but never used.","line":1,"column":7,"nodeType":"Identifier","messageId":"unusedVar","endLine":1,"endColumn":10}],"suppressedMessages":[],"errorCount":1,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"source":"const str = 'Hello world'; // \\"no-unused-vars\\" error\\n","usedDeprecatedRules":[]}`; +// return { +// // Expected output of the linting function +// cmdOutput: { +// status: 1, +// stdoutParts: [stdoutFile1, stdoutFile2], +// stdout: `[${stdoutFile1},${stdoutFile2}]`, +// }, +// // Expected output of the parsing function +// lintResult: { +// isSuccess: false, +// warning: [ +// { +// path: "file1.js", +// firstLine: 5, +// lastLine: 5, +// message: "Unexpected 'todo' comment: 'TODO: Change something' (no-warning-comments)", +// }, +// ], +// error: [ +// { +// path: "file2.js", +// firstLine: 1, +// lastLine: 1, +// message: "'str' is assigned a value but never used (no-unused-vars)", +// }, +// ], +// }, +// }; +// } + +module.exports = [testName, linter, commandPrefix, extensions, getLintParams, getFixParams]; diff --git a/test/linters/projects/tsc/.gitignore b/test/linters/projects/tsc/.gitignore new file mode 100644 index 00000000..c2658d7d --- /dev/null +++ b/test/linters/projects/tsc/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/test/linters/projects/tsc/file1.ts b/test/linters/projects/tsc/file1.ts new file mode 100644 index 00000000..ad97e8c2 --- /dev/null +++ b/test/linters/projects/tsc/file1.ts @@ -0,0 +1,7 @@ +let str; // Variable 'str' implicitly has type 'any' in some locations where its type cannot be determined.ts(7034) + +function main(): void { + console.log('hello ' + str); // Variable 'str' implicitly has type 'any' in some locations where its type cannot be determined.ts(7034) +} + +main(); diff --git a/test/linters/projects/tsc/file2.ts b/test/linters/projects/tsc/file2.ts new file mode 100644 index 00000000..d34fe2c3 --- /dev/null +++ b/test/linters/projects/tsc/file2.ts @@ -0,0 +1,3 @@ +let num = 1; + +num = 'hello'; //Type 'string' is not assignable to type 'number'.ts(2322) diff --git a/test/linters/projects/tsc/package.json b/test/linters/projects/tsc/package.json new file mode 100644 index 00000000..268dfa25 --- /dev/null +++ b/test/linters/projects/tsc/package.json @@ -0,0 +1,8 @@ +{ + "name": "test-eslint", + "main": "index.js", + "private": true, + "devDependencies": { + "typescript": "^4.9.4" + } +} diff --git a/test/linters/projects/tsc/tsconfig.json b/test/linters/projects/tsc/tsconfig.json new file mode 100644 index 00000000..75dcaeac --- /dev/null +++ b/test/linters/projects/tsc/tsconfig.json @@ -0,0 +1,103 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} diff --git a/test/linters/projects/tsc/yarn.lock b/test/linters/projects/tsc/yarn.lock new file mode 100644 index 00000000..a5d656b2 --- /dev/null +++ b/test/linters/projects/tsc/yarn.lock @@ -0,0 +1,8 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +typescript@^4.9.4: + version "4.9.4" + resolved "https://registry.npmjs.org/typescript/-/typescript-4.9.4.tgz" + integrity sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg== From 943557256ecf0c83b744c42890ed78fa8af47553 Mon Sep 17 00:00:00 2001 From: zirkelc Date: Thu, 12 Jan 2023 08:59:36 +0100 Subject: [PATCH 2/8] remove obsolete code and comments --- src/linters/tsc.js | 32 ++++++++---------------- test/linters/params/tsc.js | 51 ++------------------------------------ 2 files changed, 13 insertions(+), 70 deletions(-) diff --git a/src/linters/tsc.js b/src/linters/tsc.js index 5912dc30..4baef001 100644 --- a/src/linters/tsc.js +++ b/src/linters/tsc.js @@ -7,7 +7,7 @@ const { removeTrailingPeriod } = require("../utils/string"); /** @typedef {import('../utils/lint-result').LintResult} LintResult */ /** - * https://eslint.org + * https://www.typescriptlang.org/docs/handbook/compiler-options.html */ class TSC { static get name() { @@ -44,11 +44,10 @@ class TSC { * @returns {{status: number, stdout: string, stderr: string}} - Output of the lint command */ static lint(dir, extensions, args = "", fix = false, prefix = "") { - // const extensionsArg = extensions.map((ext) => `.${ext}`).join(","); - // const fixArg = fix ? "--fix" : ""; + // TSC does not support auto-fixing const commandPrefix = prefix || getNpmBinCommand(dir); return run( - `${commandPrefix} tsc --noEmit --pretty false`, + `${commandPrefix} tsc --noEmit --pretty false ${args}`, { dir, ignoreErrors: true, @@ -67,7 +66,8 @@ class TSC { const lintResult = initLintResult(); lintResult.isSuccess = output.status === 0; -const regex = /^(?.+)\((?\d+),(?\d+)\):\s(?\w+)\s(?.+)$/gm; + // example: file1.ts(4,25): error TS7005: Variable 'str' implicitly has an 'any' type. + const regex = /^(?.+)\((?\d+),(?\d+)\):\s(?\w+)\s(?.+)$/gm; const errors = []; const matches = output.stdout.matchAll(regex); @@ -77,27 +77,17 @@ const regex = /^(?.+)\((?\d+),(?\d+)\):\s(?\w+)\s(? Date: Thu, 12 Jan 2023 09:08:20 +0100 Subject: [PATCH 3/8] add tsc to action.yml --- action.yml | 26 ++++++++++ dist/index.js | 103 +++++++++++++++++++++++++++++++++++++ src/linters/index.js | 2 + src/linters/tsc.js | 11 ++-- test/linters/params/tsc.js | 3 +- 5 files changed, 137 insertions(+), 8 deletions(-) diff --git a/action.yml b/action.yml index c089a1e9..351eafb1 100644 --- a/action.yml +++ b/action.yml @@ -194,6 +194,32 @@ inputs: required: false default: "true" + # TypeScript + + tsc: + description: Enable or disable TypeScript checks + required: false + default: "false" + tsc_args: + description: Additional arguments to pass to the linter + required: false + default: "" + tsc_dir: + description: Directory where the TSC command should be run + required: false + tsc_extensions: + description: Extensions of files to check with TSC + required: false + default: "js" + tsc_command_prefix: + description: Shell command to prepend to the linter command. Will default to `npx --no-install` for NPM and `yarn run --silent` for Yarn. + required: false + default: "" + tsc_auto_fix: + description: Whether this linter should try to fix code style issues automatically. If set to `true`, it will only work if "auto_fix" is set to `true` as well + required: false + default: "true" + # PHP php_codesniffer: diff --git a/dist/index.js b/dist/index.js index 9e49443c..ee146cd6 100644 --- a/dist/index.js +++ b/dist/index.js @@ -7714,6 +7714,7 @@ const Stylelint = __nccwpck_require__(194); const SwiftFormatLockwood = __nccwpck_require__(8983); const SwiftFormatOfficial = __nccwpck_require__(1828); const SwiftLint = __nccwpck_require__(1439); +const TSC = __nccwpck_require__(7540); const XO = __nccwpck_require__(728); const linters = { @@ -7729,6 +7730,7 @@ const linters = { stylelint: Stylelint, swiftlint: SwiftLint, xo: XO, + tsc: TSC, // Formatters (should be run after linters) autopep8: Autopep8, @@ -8726,6 +8728,107 @@ class SwiftLint { module.exports = SwiftLint; +/***/ }), + +/***/ 7540: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { run } = __nccwpck_require__(9575); +const commandExists = __nccwpck_require__(5265); +const { initLintResult } = __nccwpck_require__(9149); +const { getNpmBinCommand } = __nccwpck_require__(1838); +const { removeTrailingPeriod } = __nccwpck_require__(9321); + +/** @typedef {import('../utils/lint-result').LintResult} LintResult */ + +/** + * https://www.typescriptlang.org/docs/handbook/compiler-options.html + */ +class TSC { + static get name() { + return "TypeScript"; + } + + /** + * Verifies that all required programs are installed. Throws an error if programs are missing + * @param {string} dir - Directory to run the linting program in + * @param {string} prefix - Prefix to the lint command + */ + static async verifySetup(dir, prefix = "") { + // Verify that NPM is installed (required to execute ESLint) + if (!(await commandExists("npm"))) { + throw new Error("NPM is not installed"); + } + + // Verify that ESLint is installed + const commandPrefix = prefix || getNpmBinCommand(dir); + try { + run(`${commandPrefix} tsc -v`, { dir }); + } catch (err) { + throw new Error(`${this.name} is not installed`); + } + } + + /** + * Runs the linting program and returns the command output + * @param {string} dir - Directory to run the linter in + * @param {string[]} extensions - File extensions which should be linted + * @param {string} args - Additional arguments to pass to the linter + * @param {boolean} fix - Whether the linter should attempt to fix code style issues automatically + * @param {string} prefix - Prefix to the lint command + * @returns {{status: number, stdout: string, stderr: string}} - Output of the lint command + */ + static lint(dir, extensions, args = "", fix = false, prefix = "") { + // TSC does not support auto-fixing + const commandPrefix = prefix || getNpmBinCommand(dir); + return run(`${commandPrefix} tsc --noEmit --pretty false ${args}`, { + dir, + ignoreErrors: true, + }); + } + + /** + * Parses the output of the lint command. Determines the success of the lint process and the + * severity of the identified code style violations + * @param {string} dir - Directory in which the linter has been run + * @param {{status: number, stdout: string, stderr: string}} output - Output of the lint command + * @returns {LintResult} - Parsed lint result + */ + static parseOutput(dir, output) { + const lintResult = initLintResult(); + lintResult.isSuccess = output.status === 0; + + // example: file1.ts(4,25): error TS7005: Variable 'str' implicitly has an 'any' type. + const regex = /^(?.+)\((?\d+),(?\d+)\):\s(?\w+)\s(?.+)$/gm; + + const errors = []; + const matches = output.stdout.matchAll(regex); + + for (const match of matches) { + const { file, line, column, code, message } = match.groups; + errors.push({ file, line, column, code, message }); + } + + for (const error of errors) { + const { file, line, message } = error; + + const entry = { + path: file, + firstLine: Number(line), + lastLine: Number(line), + message: `${removeTrailingPeriod(message)}`, + }; + + lintResult.error.push(entry); + } + + return lintResult; + } +} + +module.exports = TSC; + + /***/ }), /***/ 728: diff --git a/src/linters/index.js b/src/linters/index.js index 30a79582..c4172956 100644 --- a/src/linters/index.js +++ b/src/linters/index.js @@ -17,6 +17,7 @@ const Stylelint = require("./stylelint"); const SwiftFormatLockwood = require("./swift-format-lockwood"); const SwiftFormatOfficial = require("./swift-format-official"); const SwiftLint = require("./swiftlint"); +const TSC = require("./tsc"); const XO = require("./xo"); const linters = { @@ -32,6 +33,7 @@ const linters = { stylelint: Stylelint, swiftlint: SwiftLint, xo: XO, + tsc: TSC, // Formatters (should be run after linters) autopep8: Autopep8, diff --git a/src/linters/tsc.js b/src/linters/tsc.js index 4baef001..f7e988e3 100644 --- a/src/linters/tsc.js +++ b/src/linters/tsc.js @@ -46,13 +46,10 @@ class TSC { static lint(dir, extensions, args = "", fix = false, prefix = "") { // TSC does not support auto-fixing const commandPrefix = prefix || getNpmBinCommand(dir); - return run( - `${commandPrefix} tsc --noEmit --pretty false ${args}`, - { - dir, - ignoreErrors: true, - }, - ); + return run(`${commandPrefix} tsc --noEmit --pretty false ${args}`, { + dir, + ignoreErrors: true, + }); } /** diff --git a/test/linters/params/tsc.js b/test/linters/params/tsc.js index 0ed92bc7..f6ec886b 100644 --- a/test/linters/params/tsc.js +++ b/test/linters/params/tsc.js @@ -25,7 +25,8 @@ function getLintParams(dir) { path: "file1.ts", firstLine: 1, lastLine: 1, - message: "TS7034: Variable 'str' implicitly has type 'any' in some locations where its type cannot be determined", + message: + "TS7034: Variable 'str' implicitly has type 'any' in some locations where its type cannot be determined", }, { path: "file1.ts", From fad0b3cb961017f634a742203668246b0800a7d4 Mon Sep 17 00:00:00 2001 From: zirkelc Date: Thu, 12 Jan 2023 15:45:38 +0100 Subject: [PATCH 4/8] add tsc to test.yml --- .github/workflows/test.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index df30d454..a12aa4b3 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -75,6 +75,8 @@ jobs: yarn install cd ../stylelint/ yarn install + cd ../tsc/ + yarn install cd ../xo/ yarn install From 3eb49a4f4507af7b8da04ab9754eb0fdefa82e17 Mon Sep 17 00:00:00 2001 From: zirkelc Date: Fri, 13 Jan 2023 12:54:03 +0100 Subject: [PATCH 5/8] add warning when autofix=true and fix windows EOL bug --- action.yml | 4 ++-- src/linters/tsc.js | 7 ++++++- test/linters/params/tsc.js | 4 +++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/action.yml b/action.yml index 351eafb1..d5f646e6 100644 --- a/action.yml +++ b/action.yml @@ -210,7 +210,7 @@ inputs: tsc_extensions: description: Extensions of files to check with TSC required: false - default: "js" + default: "ts" tsc_command_prefix: description: Shell command to prepend to the linter command. Will default to `npx --no-install` for NPM and `yarn run --silent` for Yarn. required: false @@ -218,7 +218,7 @@ inputs: tsc_auto_fix: description: Whether this linter should try to fix code style issues automatically. If set to `true`, it will only work if "auto_fix" is set to `true` as well required: false - default: "true" + default: "false" # PHP diff --git a/src/linters/tsc.js b/src/linters/tsc.js index f7e988e3..cb8645bb 100644 --- a/src/linters/tsc.js +++ b/src/linters/tsc.js @@ -1,3 +1,5 @@ +const core = require("@actions/core"); + const { run } = require("../utils/action"); const commandExists = require("../utils/command-exists"); const { initLintResult } = require("../utils/lint-result"); @@ -44,7 +46,10 @@ class TSC { * @returns {{status: number, stdout: string, stderr: string}} - Output of the lint command */ static lint(dir, extensions, args = "", fix = false, prefix = "") { - // TSC does not support auto-fixing + if (fix) { + core.warning(`${this.name} does not support auto-fixing`); + } + const commandPrefix = prefix || getNpmBinCommand(dir); return run(`${commandPrefix} tsc --noEmit --pretty false ${args}`, { dir, diff --git a/test/linters/params/tsc.js b/test/linters/params/tsc.js index f6ec886b..919ec85b 100644 --- a/test/linters/params/tsc.js +++ b/test/linters/params/tsc.js @@ -1,3 +1,5 @@ +const { EOL } = require("os"); + const TSC = require("../../../src/linters/tsc"); const testName = "tsc"; @@ -7,7 +9,7 @@ const extensions = ["js"]; // Linting without auto-fixing function getLintParams(dir) { - const stdoutFile1 = `file1.ts(1,5): error TS7034: Variable 'str' implicitly has type 'any' in some locations where its type cannot be determined.\nfile1.ts(4,25): error TS7005: Variable 'str' implicitly has an 'any' type.`; + const stdoutFile1 = `file1.ts(1,5): error TS7034: Variable 'str' implicitly has type 'any' in some locations where its type cannot be determined.${EOL}file1.ts(4,25): error TS7005: Variable 'str' implicitly has an 'any' type.`; const stdoutFile2 = `file2.ts(3,1): error TS2322: Type 'string' is not assignable to type 'number'.`; return { // Expected output of the linting function From 3e2e47c2bae37b69a53d32a6d08e7d382b7aef6a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 13 Jan 2023 11:54:33 +0000 Subject: [PATCH 6/8] [auto] Update compiled version --- dist/index.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/dist/index.js b/dist/index.js index ee146cd6..b9f98d69 100644 --- a/dist/index.js +++ b/dist/index.js @@ -8733,6 +8733,8 @@ module.exports = SwiftLint; /***/ 7540: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const core = __nccwpck_require__(2186); + const { run } = __nccwpck_require__(9575); const commandExists = __nccwpck_require__(5265); const { initLintResult } = __nccwpck_require__(9149); @@ -8779,7 +8781,10 @@ class TSC { * @returns {{status: number, stdout: string, stderr: string}} - Output of the lint command */ static lint(dir, extensions, args = "", fix = false, prefix = "") { - // TSC does not support auto-fixing + if (fix) { + core.warning(`${this.name} does not support auto-fixing`); + } + const commandPrefix = prefix || getNpmBinCommand(dir); return run(`${commandPrefix} tsc --noEmit --pretty false ${args}`, { dir, From b2b82209cec4383b729705e551387fd64b85f676 Mon Sep 17 00:00:00 2001 From: zirkelc Date: Fri, 13 Jan 2023 13:18:29 +0100 Subject: [PATCH 7/8] add tsc to readme --- README.md | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 8a638e69..428efd00 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,8 @@ _**Note:** The behavior of actions like this one is currently limited in the con - [swift-format](https://github.com/apple/swift-format) (official) - [SwiftFormat](https://github.com/nicklockwood/SwiftFormat) (by Nick Lockwood) - [SwiftLint](https://github.com/realm/SwiftLint) +- **TypeScript:** + - [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html) - **VB.NET:** - [dotnet-format](https://github.com/dotnet/format) @@ -422,26 +424,27 @@ Some options are not available for specific linters: | Linter | auto-fixing | extensions | | --------------------- | :---------: | :--------: | -| autopep8 | ✅ | ❌ (py) | -| black | ✅ | ✅ | -| clang_format | ✅ | ✅ | -| dotnet_format | ✅ | ❌ (cs) | -| erblint | ❌ | ❌ (erb) | -| eslint | ✅ | ✅ | -| flake8 | ❌ | ✅ | -| gofmt | ✅ | ❌ (go) | -| golint | ❌ | ❌ (go) | -| mypy | ❌ | ❌ (py) | -| oitnb | ✅ | ✅ | -| php_codesniffer | ❌ | ✅ | -| prettier | ✅ | ✅ | -| pylint | ❌ | ❌ (py) | -| rubocop | ✅ | ❌ (rb) | -| stylelint | ✅ | ✅ | -| swift_format_official | ✅ | ✅ | -| swift_format_lockwood | ✅ | ❌ (swift) | -| swiftlint | ✅ | ❌ (swift) | -| xo | ✅ | ✅ | +| autopep8 | ✅ | ❌ (py) | +| black | ✅ | ✅ | +| clang_format | ✅ | ✅ | +| dotnet_format | ✅ | ❌ (cs) | +| erblint | ❌ | ❌ (erb) | +| eslint | ✅ | ✅ | +| flake8 | ❌ | ✅ | +| gofmt | ✅ | ❌ (go) | +| golint | ❌ | ❌ (go) | +| mypy | ❌ | ❌ (py) | +| oitnb | ✅ | ✅ | +| php_codesniffer | ❌ | ✅ | +| prettier | ✅ | ✅ | +| pylint | ❌ | ❌ (py) | +| rubocop | ✅ | ❌ (rb) | +| stylelint | ✅ | ✅ | +| swift_format_official | ✅ | ✅ | +| swift_format_lockwood | ✅ | ❌ (swift) | +| swiftlint | ✅ | ❌ (swift) | +| tsc | ❌ | ❌ (ts) | +| xo | ✅ | ✅ | ## Limitations From 327cf4448b6ef6173fb336781b9162886b3696a0 Mon Sep 17 00:00:00 2001 From: zirkelc Date: Fri, 13 Jan 2023 13:19:51 +0100 Subject: [PATCH 8/8] linted readme --- README.md | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 428efd00..7d1e088f 100644 --- a/README.md +++ b/README.md @@ -424,27 +424,27 @@ Some options are not available for specific linters: | Linter | auto-fixing | extensions | | --------------------- | :---------: | :--------: | -| autopep8 | ✅ | ❌ (py) | -| black | ✅ | ✅ | -| clang_format | ✅ | ✅ | -| dotnet_format | ✅ | ❌ (cs) | -| erblint | ❌ | ❌ (erb) | -| eslint | ✅ | ✅ | -| flake8 | ❌ | ✅ | -| gofmt | ✅ | ❌ (go) | -| golint | ❌ | ❌ (go) | -| mypy | ❌ | ❌ (py) | -| oitnb | ✅ | ✅ | -| php_codesniffer | ❌ | ✅ | -| prettier | ✅ | ✅ | -| pylint | ❌ | ❌ (py) | -| rubocop | ✅ | ❌ (rb) | -| stylelint | ✅ | ✅ | -| swift_format_official | ✅ | ✅ | -| swift_format_lockwood | ✅ | ❌ (swift) | -| swiftlint | ✅ | ❌ (swift) | -| tsc | ❌ | ❌ (ts) | -| xo | ✅ | ✅ | +| autopep8 | ✅ | ❌ (py) | +| black | ✅ | ✅ | +| clang_format | ✅ | ✅ | +| dotnet_format | ✅ | ❌ (cs) | +| erblint | ❌ | ❌ (erb) | +| eslint | ✅ | ✅ | +| flake8 | ❌ | ✅ | +| gofmt | ✅ | ❌ (go) | +| golint | ❌ | ❌ (go) | +| mypy | ❌ | ❌ (py) | +| oitnb | ✅ | ✅ | +| php_codesniffer | ❌ | ✅ | +| prettier | ✅ | ✅ | +| pylint | ❌ | ❌ (py) | +| rubocop | ✅ | ❌ (rb) | +| stylelint | ✅ | ✅ | +| swift_format_official | ✅ | ✅ | +| swift_format_lockwood | ✅ | ❌ (swift) | +| swiftlint | ✅ | ❌ (swift) | +| tsc | ❌ | ❌ (ts) | +| xo | ✅ | ✅ | ## Limitations