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

Staticcheck #772

Closed
wants to merge 9 commits into from
Closed
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
7 changes: 6 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,14 @@ jobs:

- name: Install Go dependencies
run: |
cd ./test/linters/projects/golint
cd ./test/linters/projects/golint/
go install golang.org/x/lint/golint@latest

- name: Install Go staticcheck
run: |
cd ./test/linters/projects/staticcheck/
go install honnef.co/go/tools/cmd/staticcheck@latest

# Node.js

- name: Set up Node.js
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ _**Note:** The behavior of actions like this one is currently limited in the con
- **Go:**
- [gofmt](https://golang.org/cmd/gofmt)
- [golint](https://github.com/golang/lint)
- [staticcheck](https://staticcheck.dev/)
- **JavaScript:**
- [ESLint](https://eslint.org)
- [Prettier](https://prettier.io)
Expand Down Expand Up @@ -437,6 +438,7 @@ Some options are not available for specific linters:
| flake8 | ❌ | ✅ |
| gofmt | ✅ | ❌ (go) |
| golint | ❌ | ❌ (go) |
| staticcheck | ❌ | ❌ (go) |
| mypy | ❌ | ❌ (py) |
| oitnb | ✅ | ✅ |
| php_codesniffer | ❌ | ✅ |
Expand Down
20 changes: 20 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,26 @@ inputs:
required: false
default: "false"

staticcheck:
description: Enable or disable staticcheck checks
required: false
default: "false"
staticcheck_dir:
description: Directory where the staticcheck command should be run
required: false
staticcheck_args:
description: Additional arguments to pass to the linter
required: false
default: ""
staticcheck_extensions:
description: Extensions of files to check with staticcheck
required: false
default: "go"
staticcheck_command_prefix:
description: Shell command to prepend to the linter command
required: false
default: ""

# JavaScript

eslint:
Expand Down
77 changes: 77 additions & 0 deletions src/linters/staticcheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
const { run } = require("../utils/action");
const commandExists = require("../utils/command-exists");
const { initLintResult } = require("../utils/lint-result");
const { capitalizeFirstLetter } = require("../utils/string");

const PARSE_REGEX = /^(.+):([0-9]+):[0-9]+: (.+)$/gm;

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

/**
* https://github.com/golang/lint
*/
class Staticcheck {
static get name() {
return "staticcheck";
}

/**
* 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 golint is installed
if (!(await commandExists("staticcheck"))) {
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] !== "go") {
throw new Error(`${this.name} error: File extensions are not configurable`);
}

return run(`${prefix} staticcheck -f text ${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;

const matches = output.stdout.matchAll(PARSE_REGEX);
for (const match of matches) {
const [_, path, line, text] = match;
const lineNr = parseInt(line, 10);
lintResult.error.push({
path,
firstLine: lineNr,
lastLine: lineNr,
message: capitalizeFirstLetter(text),
});
}

return lintResult;
}
}

module.exports = Staticcheck;
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 staticcheckParams = require("./params/staticcheck");
const stylelintParams = require("./params/stylelint");
const swiftFormatLockwood = require("./params/swift-format-lockwood");
// const swiftFormatOfficial = require("./params/swift-format-official");
Expand All @@ -39,6 +40,7 @@ const linterParams = [
flake8Params,
gofmtParams,
golintParams,
staticcheckParams,
mypyParams,
phpCodeSnifferParams,
prettierParams,
Expand Down
72 changes: 72 additions & 0 deletions test/linters/params/staticcheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
const Staticcheck = require("../../../src/linters/staticcheck");

const testName = "staticcheck";
const linter = Staticcheck;
const commandPrefix = "";
const args = "";
const extensions = ["go"];

// Linting without auto-fixing
function getLintParams(dir) {
const stdoutFile1 =
"file1.go:20:2: this value of err is never used (SA4006)\nfile1.go:20:9: New doesn't have side effects and its return value is ignored (SA4017)\nfile1.go:31:6: func main1 is unused (U1000)";
const stdoutFile2 = `file2.go:11:3: this linter directive didn't match anything; should it be removed? (staticcheck)\nfile2.go:12:19: calling regexp.MatchString in a loop has poor performance, consider using regexp.Compile (SA6000)\nfile2.go:25:6: func main2 is unused (U1000)`;
return {
// Expected output of the linting function
cmdOutput: {
status: 1,
// stdoutParts: [stdoutFile1, stdoutFile2],
stdout: `${stdoutFile1}\n${stdoutFile2}`,
},
// Expected output of the parsing function
lintResult: {
isSuccess: false,
warning: [],
error: [
{
path: "file1.go",
firstLine: 20,
lastLine: 20,
message: "This value of err is never used (SA4006)",
},
{
path: "file1.go",
firstLine: 20,
lastLine: 20,
message: "New doesn't have side effects and its return value is ignored (SA4017)",
},
{
path: "file1.go",
firstLine: 31,
lastLine: 31,
message: "Func main1 is unused (U1000)",
},
{
path: "file2.go",
firstLine: 11,
lastLine: 11,
message:
"This linter directive didn't match anything; should it be removed? (staticcheck)",
},
{
path: "file2.go",
firstLine: 12,
lastLine: 12,
message:
"Calling regexp.MatchString in a loop has poor performance, consider using regexp.Compile (SA6000)",
},
{
path: "file2.go",
firstLine: 25,
lastLine: 25,
message: "Func main2 is unused (U1000)",
},
],
},
};
}

// Linting with auto-fixing
const getFixParams = getLintParams; // Does not support auto-fixing -> option has no effect

module.exports = [testName, linter, commandPrefix, extensions, args, getLintParams, getFixParams];
37 changes: 37 additions & 0 deletions test/linters/projects/staticcheck/file1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package main

import (
"errors"
"fmt"
"log"
)

type Result struct {
Entries []string
}

func Query() (Result, error) {
return Result{
Entries: []string{},
}, nil
}

func ResultEntries() (Result, error) {
err := errors.New("no entries found")
result, err := Query()
if err != nil {
return Result{}, err
}
if len(result.Entries) == 0 {
return Result{}, err
}
return result, nil
}

func main1() {
result, err := ResultEntries()
if err != nil {
log.Fatal(err)
}
fmt.Printf("result=%v, err=%v", result, err)
}
34 changes: 34 additions & 0 deletions test/linters/projects/staticcheck/file2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"fmt"
"log"
"regexp"
)

func ValidateEmails(addrs []string) (bool, error) {
for _, email := range addrs {
//lint:ignore SA1000 we love invalid regular expressions!
matched, err := regexp.MatchString("^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]*$", email)
if err != nil {
return false, err
}

if !matched {
return false, nil
}
}

return true, nil
}

func main2() {
emails := []string{"[email protected]", "[email protected]", "[email protected]"}

matched, err := ValidateEmails(emails)
if err != nil {
log.Fatal(err)
}

fmt.Println(matched)
}
3 changes: 3 additions & 0 deletions test/linters/projects/staticcheck/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module linting-test

go 1.21.6
Loading