Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tsc to check TypeScript files #575

Merged
merged 8 commits into from
Jan 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ jobs:
yarn install
cd ../stylelint/
yarn install
cd ../tsc/
yarn install
cd ../xo/
yarn install

Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -441,6 +443,7 @@ Some options are not available for specific linters:
| swift_format_official | ✅ | ✅ |
| swift_format_lockwood | ✅ | ❌ (swift) |
| swiftlint | ✅ | ❌ (swift) |
| tsc | ❌ | ❌ (ts) |
| xo | ✅ | ✅ |

## Limitations
Expand Down
26 changes: 26 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: "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
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: "false"

# PHP

php_codesniffer:
Expand Down
108 changes: 108 additions & 0 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -7729,6 +7730,7 @@ const linters = {
stylelint: Stylelint,
swiftlint: SwiftLint,
xo: XO,
tsc: TSC,

// Formatters (should be run after linters)
autopep8: Autopep8,
Expand Down Expand Up @@ -8726,6 +8728,112 @@ class SwiftLint {
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);
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 = "") {
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,
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 = /^(?<file>.+)\((?<line>\d+),(?<column>\d+)\):\s(?<code>\w+)\s(?<message>.+)$/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:
Expand Down
2 changes: 2 additions & 0 deletions src/linters/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -32,6 +33,7 @@ const linters = {
stylelint: Stylelint,
swiftlint: SwiftLint,
xo: XO,
tsc: TSC,

// Formatters (should be run after linters)
autopep8: Autopep8,
Expand Down
99 changes: 99 additions & 0 deletions src/linters/tsc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
const core = require("@actions/core");

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://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 = "") {
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,
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 = /^(?<file>.+)\((?<line>\d+),(?<column>\d+)\):\s(?<code>\w+)\s(?<message>.+)$/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;
2 changes: 2 additions & 0 deletions test/linters/linters.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -41,6 +42,7 @@ const linterParams = [
pylintParams,
ruboCopParams,
stylelintParams,
tscParams,
xoParams,
];
if (process.platform === "linux") {
Expand Down
53 changes: 53 additions & 0 deletions test/linters/params/tsc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const { EOL } = require("os");

const TSC = require("../../../src/linters/tsc");

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.${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
cmdOutput: {
status: 2,
stdoutParts: [stdoutFile1, stdoutFile2],
stdout: `${stdoutFile1}\n${stdoutFile2}`,
},
// Expected output of the parsing function
lintResult: {
isSuccess: false,
warning: [], // TSC only emits errors
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'",
},
],
},
};
}

// TSC does not support auto-fixing
const getFixParams = getLintParams;

module.exports = [testName, linter, commandPrefix, extensions, getLintParams, getFixParams];
1 change: 1 addition & 0 deletions test/linters/projects/tsc/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
7 changes: 7 additions & 0 deletions test/linters/projects/tsc/file1.ts
Original file line number Diff line number Diff line change
@@ -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();
3 changes: 3 additions & 0 deletions test/linters/projects/tsc/file2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
let num = 1;

num = 'hello'; //Type 'string' is not assignable to type 'number'.ts(2322)
8 changes: 8 additions & 0 deletions test/linters/projects/tsc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "test-eslint",
"main": "index.js",
"private": true,
"devDependencies": {
"typescript": "^4.9.4"
}
}
Loading