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 standardrb linter #742

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ _**Note:** The behavior of actions like this one is currently limited in the con
- **Ruby:**
- [ERB Lint](https://github.com/Shopify/erb-lint)
- [RuboCop](https://rubocop.readthedocs.io)
- [StandardRB](https://github.com/standardrb/standard)
- **Rust:**
- [clippy](https://github.com/rust-lang/rust-clippy)
- [rustfmt](https://github.com/rust-lang/rustfmt)
Expand Down Expand Up @@ -386,7 +387,7 @@ With `auto_fix` set to `true`, by default the action will try and fix code issue

### Linter-specific options

`[linter]` can be one of `autopep8`, `black`, `clang_format`, `dotnet_format`, `erblint`, `eslint`, `flake8`, `gofmt`, `golint`, `mypy`, `oitnb`, `php_codesniffer`, `prettier`, `pylint`, `rubocop`, `stylelint`, `swift_format_official`, `swift_format_lockwood`, `swiftlint` and `xo`:
`[linter]` can be one of `autopep8`, `black`, `clang_format`, `dotnet_format`, `erblint`, `eslint`, `flake8`, `gofmt`, `golint`, `mypy`, `oitnb`, `php_codesniffer`, `prettier`, `pylint`, `rubocop`, `standardrb`, `stylelint`, `swift_format_official`, `swift_format_lockwood`, `swiftlint` and `xo`:

- **`[linter]`:** Enables the linter in your repository. Default: `false`
- **`[linter]_args`**: Additional arguments to pass to the linter. Example: `eslint_args: "--max-warnings 0"` if ESLint checks should fail even if there are no errors and only warnings. Default: `""`
Expand Down Expand Up @@ -444,6 +445,7 @@ Some options are not available for specific linters:
| pylint | ❌ | ❌ (py) |
| rubocop | ✅ | ❌ (rb) |
| rustfmt | ✅ | ❌ (rs) |
| standardrb | ✅ | ❌ (rb) |
| stylelint | ✅ | ✅ |
| swift_format_official | ✅ | ✅ |
| swift_format_lockwood | ✅ | ❌ (swift) |
Expand Down
24 changes: 24 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,30 @@ inputs:

# Ruby

standardrb:
description: Enable or disable StandardRB checks
required: false
default: "false"
standardrb_args:
description: Additional arguments to pass to the linter
required: false
default: ""
standardrb_dir:
description: Directory where the standardrb command should be run
required: false
standardrb_extensions:
description: Extensions of files to check with standardrb
required: false
default: "rb"
standardrb_command_prefix:
description: Shell command to prepend to the linter command
required: false
default: "bundle exec"
standardrb_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"

rubocop:
description: Enable or disable RuboCop checks
required: false
Expand Down
115 changes: 115 additions & 0 deletions dist/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/linters/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const Prettier = require("./prettier");
const Pylint = require("./pylint");
const RuboCop = require("./rubocop");
const RustFmt = require("./rustfmt");
const StandardRB = require("./standardrb");
const Stylelint = require("./stylelint");
const SwiftFormatLockwood = require("./swift-format-lockwood");
const SwiftFormatOfficial = require("./swift-format-official");
Expand All @@ -33,6 +34,7 @@ const linters = {
php_codesniffer: PHPCodeSniffer,
pylint: Pylint,
rubocop: RuboCop,
standardrb: StandardRB,
stylelint: Stylelint,
swiftlint: SwiftLint,
xo: XO,
Expand Down
105 changes: 105 additions & 0 deletions src/linters/standardrb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
const { run } = require("../utils/action");
const commandExists = require("../utils/command-exists");
const { initLintResult } = require("../utils/lint-result");
const { removeTrailingPeriod } = require("../utils/string");

/** @typedef {import('../utils/lint-result').LintResult} LintResult */

// Mapping of standard severities to severities used for GitHub commit annotations
const severityMap = {
info: "warning",
convention: "warning",
refactor: "warning",
warning: "warning",
error: "error",
fatal: "error",
};

/**
* https://github.com/standardrb/standard/
*/
class StandardRB {
static get name() {
return "Standardrb";
}

/**
* 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 Ruby is installed (required to execute Standardrb)
if (!(await commandExists("ruby"))) {
throw new Error("Ruby is not installed");
}
// Verify that Standardrb is installed
try {
run(`${prefix} standardrb -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 (extensions.length !== 1 || extensions[0] !== "rb") {
throw new Error(`${this.name} error: File extensions are not configurable`);
}

const fixArg = fix ? "--fix" : "";
return run(`${prefix} standardrb --format json ${fixArg} ${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;

let outputJson;
try {
outputJson = JSON.parse(output.stdout);
} catch (err) {
throw Error(
`Error parsing ${this.name} JSON output: ${err.message}. Output: "${output.stdout}"`,
);
}

for (const file of outputJson.files) {
const { path, offenses } = file;
for (const offense of offenses) {
const { severity, message, cop_name: rule, corrected, location } = offense;
if (!corrected) {
const mappedSeverity = severityMap[severity] || "error";
lintResult[mappedSeverity].push({
path,
firstLine: location.start_line,
lastLine: location.last_line,
message: `${removeTrailingPeriod(message)} (${rule})`,
});
}
}
}

return lintResult;
}
}

module.exports = StandardRB;
2 changes: 2 additions & 0 deletions test/linters/linters.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const prettierParams = require("./params/prettier");
const pylintParams = require("./params/pylint");
const ruboCopParams = require("./params/rubocop");
const rustfmtParams = require("./params/rustfmt");
const standardRBParams = require("./params/standardrb");
const stylelintParams = require("./params/stylelint");
const swiftFormatLockwood = require("./params/swift-format-lockwood");
// const swiftFormatOfficial = require("./params/swift-format-official");
Expand All @@ -45,6 +46,7 @@ const linterParams = [
pylintParams,
ruboCopParams,
rustfmtParams,
standardRBParams,
stylelintParams,
tscParams,
xoParams,
Expand Down
69 changes: 69 additions & 0 deletions test/linters/params/standardrb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
const StandardRB = require("../../../src/linters/standardrb");

const testName = "standardrb";
const linter = StandardRB;
const args = "";
const commandPrefix = "bundle exec";
const extensions = ["rb"];

// Linting without auto-fixing
function getLintParams(dir) {
const stdoutFile1 = `{"path":"file1.rb","offenses":[{"severity":"convention","message":"Redundant \`return\` detected.","cop_name":"Style/RedundantReturn","corrected":false,"correctable":true,"location":{"start_line":5,"start_column":3,"last_line":5,"last_column":8,"length":6,"line":5,"column":3}}]}`;
const stdoutFile2 = `{"path":"file2.rb","offenses":[{"severity":"warning","message":"Useless assignment to variable - \`x\`.","cop_name":"Lint/UselessAssignment","corrected":false,"correctable":true,"location":{"start_line":4,"start_column":1,"last_line":4,"last_column":1,"length":1,"line":4,"column":1}}]}`;
return {
// Expected output of the linting function
cmdOutput: {
status: 1,
stdoutParts: [stdoutFile1, stdoutFile2],
stdout: `{"metadata":{"rubocop_version":"0.93.0","ruby_engine":"ruby","ruby_version":"2.5.3","ruby_patchlevel":"105","ruby_platform":"x86_64-darwin18"},"files":[${stdoutFile1},${stdoutFile2}],"summary":{"offense_count":2,"target_file_count":2,"inspected_file_count":2}}`,
},
// Expected output of the parsing function
lintResult: {
isSuccess: false,
warning: [
{
path: "file1.rb",
firstLine: 5,
lastLine: 5,
message: "Redundant `return` detected (Style/RedundantReturn)",
},
{
path: "file2.rb",
firstLine: 4,
lastLine: 4,
message: "Useless assignment to variable - `x` (Lint/UselessAssignment)",
},
],
error: [],
},
};
}

// Linting with auto-fixing
function getFixParams(dir) {
const stdoutFile1 = `{"path":"file1.rb","offenses":[{"severity":"convention","message":"Redundant \`return\` detected.","cop_name":"Style/RedundantReturn","corrected":true,"correctable":true,"location":{"start_line":5,"start_column":3,"last_line":5,"last_column":8,"length":6,"line":5,"column":3}}]}`;
const stdoutFile2 = `{"path":"file2.rb","offenses":[{"severity":"warning","message":"Useless assignment to variable - \`x\`.","cop_name":"Lint/UselessAssignment","corrected":false,"correctable":true,"location":{"start_line":4,"start_column":1,"last_line":4,"last_column":1,"length":1,"line":4,"column":1}}]}`;
return {
// Expected output of the linting function
cmdOutput: {
status: 1,
stdoutParts: [stdoutFile1, stdoutFile2],
stdout: `{"metadata":{"rubocop_version":"0.93.0","ruby_engine":"ruby","ruby_version":"2.5.3","ruby_patchlevel":"105","ruby_platform":"x86_64-darwin18"},"files":[${stdoutFile1},${stdoutFile2}],"summary":{"offense_count":2,"target_file_count":2,"inspected_file_count":2}}`,
},
// Expected output of the parsing function
lintResult: {
isSuccess: false,
warning: [
{
path: "file2.rb",
firstLine: 4,
lastLine: 4,
message: "Useless assignment to variable - `x` (Lint/UselessAssignment)",
},
],
error: [],
},
};
}

module.exports = [testName, linter, commandPrefix, extensions, args, getLintParams, getFixParams];
Loading
Loading