Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

npm-groovy-lint

Package Overview
Dependencies
Maintainers
1
Versions
204
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

npm-groovy-lint

Lint, format and auto-fix your Groovy / Jenkinsfile / Gradle files

  • 8.0.0-beta.5
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
9.9K
decreased by-22.02%
Maintainers
1
Weekly downloads
 
Created
Source

NPM GROOVY LINT (+ Format & Auto-fix)

Version Downloads/week Downloads/total Test codecov Mega-Linter GitHub contributors GitHub stars Docker Pulls Docker Stars License PRs Welcome

Groovy & Jenkinsfile Linter, Formatter and Auto-fixer

Based on CodeNarc , this out of the box package allows to track groovy errors and correct a part of them

  • Use option --format to format & prettify source code
  • Use option --fix to activate autofixing of fixable rules

Easy to integrate in a CD/CI process (Jenkins Pipeline,CircleCI...) to lint your groovy or Jenkinsfile at each build :)

You can also use this package in :

https://github.com/nvuillam/npm-groovy-lint/raw/master/doc/images/npm-groovy-lint-results.png

See CHANGELOG

Any question, problem or enhancement request ? Ask here :)

INSTALLATION

    npm install -g npm-groovy-lint

Node.js >= 12 is required to run this package. If you can't upgrade, you can use nvm to have different node versions on your computer

USAGE

    npm-groovy-lint OPTIONS
ParameterTypeDescription
-p
--path
StringDirectory containing the files to lint
Example: ./path/to/my/groovy/files
-f
--files
StringComma-separated list of Ant-style file patterns specifying files that must be included.
Default: "**/*.groovy,**/Jenkinsfile,**/*.gradle"
Examples:
- "**/Jenkinsfile"
- "**/*.groovy"
- "**/*.gradle"
-o
--output
StringOutput format (txt,json,html,xml), or path to a file with one of these extensions
Default: txt
Examples:
- "txt"
- "json"
- "./logs/myLintResults.txt"
- "./logs/myLintResults.json"
- "./logs/myLintResults.html"
- "./logs/myLintResults.xml"
-l
--loglevel
StringLog level (error,warning or info)
Default: info
--failonStringDefines the error level where CLI will fail (return code = 1). error,warning,info or none. Each failure level includes the more critical ones.
-c
--config
StringCustom path to GroovyLint config file, or preset config `recommended
--parseBooleanTry to compile the source code and return parse errors (since v5.7.0, default to true, use --no-parse to deactivate)
--formatBooleanFormat source code
--fixBooleanAutomatically fix problems when possible
See Autofixable rules
-x
--fixrules
StringOption for --fix argument: List of rule identifiers to fix (if not specified, all available fixes will be applied). See Autofixable rules
Examples:
- "SpaceBeforeClosingBrace,SpaceAfterClosingBrace,UnusedImport"
- "Indentation"
--nolintafterBooleanWhen format or fix is called, a new lint is performed after the fixes to update the returned error list. If you just want the updated source code and do not care about the error logs, use this parameter to improve performances
-r
--rulesets
StringRuleSet file(s) to use for linting, if you do not want to use recommended rules or .groovylintrc.js defined rules.
If list of comma separated strings corresponding to CodeNarc rules, a RuleSet file will be dynamically generated
Examples:
- "./config/codenarc/RuleSet-Custom.groovy"
- "./path/to/my/ruleset/files"
- Indentation{"spacesPerIndentLevel":2,"severity":"warning"},UnnecessarySemicolon,UnnecessaryGString
--rulesetsoverridetypeStringIf list of rules sent in rulesets option, defines if they replace rules defined in .groovylintrc.json, or if they are appended
Values: replaceConfig (default), appendConfig
-s
--source
StringIf path and files are not set, you can directly send the source code string to analyze
-v
--verbose
BooleanMore outputs in console, including performed fixes
-i
--ignorepattern
StringComma-separated list of Ant-style file patterns specifying files that must be ignored
Default: none
Example: "**/test/*""
--noserverBooleannpm-groovy-lint launches a microservice to avoid performance issues caused by loading java/groovy each time,that auto kills itself after 1h idle. Use this argument if you do not want to use this feature
--returnrulesBooleanReturn rules descriptions and URL if set
--javaexecutableStringOverride java executable to use
Default: java
Example: C:\Program Files\Java\jdk1.8.0_144\bin\java.exe
--javaoptionsStringOverride java options to use
Default: "-Xms256m,-Xmx2048m"
--no-insightBooleannpm-groovy-lint collects anonymous usage statistics using amplitude, in order to make new improvements based on how users use this package.
Summary charts are available at https://tinyurl.com/groovy-stats.
Analytics obviously does not receive sensitive information like your code, as you can see in analytics.js.
If you want to disable anonymous usage statistics, use --no-insight option.
--codenarcargsStringUse core CodeNarc arguments (all npm-groovy-lint arguments will be ignored)
Doc: http://codenarc.github.io/CodeNarc/codenarc-command-line.html
Example: npm-groovy-lint --codenarcargs -basedir="lib/example" -rulesetfiles="file:lib/example/RuleSet-Groovy.groovy" -maxPriority1Violations=0 -report="xml:ReportTestCodenarc.xml
-h
--help
BooleanShow help (npm-groovy-lint -h OPTIONNAME to see option detail with examples)

CONFIGURATION

Default rules definition (recommended, based on all tracks a lot of errors, do not hesitate to ignore some of them (like NoDef ou RequiredVariableType) if they are too mean for your project.

Create a file named .groovylintrc.json in the current or any parent directory of where your files to analyze are located

  • your-repo-root-folder
    • src
      • groovy
        • mygroovyfile.groovy
    • Jenkinsfile
    • .groovylintrc.json (do not forget the dot at the beginning of the file name)

If you are using VsCode Groovy Lint extension, just use QuickFix Ignore in all files and it will generate groovylintrc.json file

Format

  • extends: Name of a base configuration (recommended, recommended-jenkinsfile, all)
  • rules: List of rules definition, following format "RuleSection.RuleName": ruleParameters or "RuleName": ruleParameters
    • RuleName: any of the CodeNarc rules
    • ruleParameters: can be just a severity override ( "off", "error", "warning", "info" ) , or a property list :

OR

  • codenarcRulesets: Comma-separated string containing the list of .xml or .groovy CodeNarc RuleSet files (in case you already are a CodeNarc user and do not wish to switch to npm-groovy-lint config format)

Examples

{
    "extends": "recommended",
    "rules": {
        "comments.ClassJavadoc": "off",
        "formatting.Indentation": {
            "spacesPerIndentLevel": 4,
            "severity": "info"
        },
        "UnnecessaryReturnKeyword": "error"
    }
}
{
    "extends": "recommended-jenkinsfile",
    "rules": {
        "CouldBeElvis": "off",
        "CouldBeSwitchStatement": "off",
        "VariableName": {
            "severity": "info"
        }
    }
}
{
    "codenarcRulesets": "RuleSet-1.groovy,RuleSet-2.groovy"
}

EXAMPLE CALLS

  • Lint groovy with JSON output
    npm-groovy-lint --output json
  • Advanced config
    npm-groovy-lint --path "./path/to/my/groovy/files" --files "**/*.groovy" --config "./config/codenarc/.groovylintrcCustom.js" --loglevel warning --output txt
  • Lint using core CodeNarc parameters and generate HTML report file
    npm-groovy-lint --codenarcargs -basedir="lib/example" -rulesetfiles="file:lib/example/RuleSet-Groovy.groovy" -title="TestTitleCodenarc" -maxPriority1Violations=0' -report="html:ReportTestCodenarc.html"

DISABLING RULES IN SOURCE

You can disable rules directly by adding comment in file, using eslint style

To temporarily disable rule warnings in your file, use block comments in the following format:

/* groovylint-disable */

def variable = 1;

/* groovylint-enable */

You can also disable or enable warnings for specific rules:

/* groovylint-disable NoDef, UnnecessarySemicolon */

def variable = 1;

/* groovylint-enable NoDef, UnnecessarySemicolon */

To disable rule warnings in an entire file, put a /* groovylint-disable */ block comment at the top of the file:

/* groovylint-disable */

def variable = 1;

You can also disable or enable specific rules for an entire file:

/* groovylint-disable NoDef */

def variable = 1;

To disable all rules on a specific line, use a line or block comment in one of the following formats:

def variable = 1; // groovylint-disable-line

// groovylint-disable-next-line
def variable = 1;

/* groovylint-disable-next-line */
def variable = 1;

def variable = 1; /* groovylint-disable-line */

To disable a specific rule on a specific line:

def variable = 1; // groovylint-disable-line NoDef

// groovylint-disable-next-line NoDef
def variable = 1;

def variable = 1; /* groovylint-disable-line NoDef */

/* groovylint-disable-next-line NoDef */
def variable = 1;

To disable multiple rules on a specific line:

def variable = 1; // groovylint-disable-line NoDef, UnnecessarySemicolon

// groovylint-disable-next-line NoDef, UnnecessarySemicolon
def variable = 1;

def variable = 1; /* groovylint-disable-line NoDef, UnnecessarySemicolon */

/* groovylint-disable-next-line NoDef, UnnecessarySemicolon */
def variable = 1;

AUTO-FIXABLE RULES

  • AssignmentInConditional
  • BlankLineBeforePackage
  • BlockEndsWithBlankLine
  • BlockStartsWithBlankLine
  • BracesForClass
  • BracesForForLoop
  • BracesForIfElse
  • BracesForMethod
  • BracesForTryCatchFinally
  • ClassEndsWithBlankLine
  • ClassStartsWithBlankLine
  • ClosingBraceNotAlone
  • ConsecutiveBlankLines
  • DuplicateImport
  • ElseBlockBraces
  • ExplicitArrayListInstantiation
  • ExplicitLinkedListInstantiation
  • FileEndsWithoutNewline
  • IfStatementBraces
  • Indentation
  • IndentationClosingBraces
  • IndentationComments
  • InsecureRandom
  • MisorderedStaticImports
  • MissingBlankLineAfterImports
  • MissingBlankLineAfterPackage
  • NoTabCharacter
  • SpaceAfterCatch
  • SpaceAfterComma
  • SpaceAfterFor
  • SpaceAfterIf
  • SpaceAfterOpeningBrace
  • SpaceAfterSemicolon
  • SpaceAfterSwitch
  • SpaceAfterWhile
  • SpaceAroundOperator
  • SpaceBeforeClosingBrace
  • SpaceBeforeOpeningBrace
  • TrailingWhitespace
  • UnnecessaryDefInFieldDeclaration
  • UnnecessaryDefInMethodDeclaration
  • UnnecessaryDefInVariableDeclaration
  • UnnecessaryDotClass
  • UnnecessaryFinalOnPrivateMethod
  • UnnecessaryGString
  • UnnecessaryGroovyImport
  • UnnecessaryPackageReference
  • UnnecessaryParenthesesForMethodCallWithClosure
  • UnnecessarySemicolon
  • UnnecessaryToString
  • UnusedImport

Contribute to add more rules fixes :)

CALL VIA DOCKER

You can run npm-groovy-lint using its official docker image

Shell example

Run with default settings

docker run -u "$(id -u):$(id -g)" -w=/tmp -v "$PWD":/tmp nvuillam/npm-groovy-lint

Run with additional flags by simply appending them at after docker image name:

docker run -u "$(id -u):$(id -g)" -w=/tmp -v "$PWD":/tmp nvuillam/npm-groovy-lint --failon warning --verbose

CircleCI example

# .circleci/config.yml
version: 2.1
jobs:
  lint:
    docker:
      - image: nvuillam/npm-groovy-lint
    steps:
      - checkout

      - run: |
          npm-groovy-lint

workflows:
  version: 2
  "lint":
    jobs:
       - lint

Jenkinsfile example

node {
    checkout scm
    docker.image('nvuillam/npm-groovy-lint').inside {
        sh 'npm-groovy-lint'
    }
}

CALL VIA JS MODULE

You can import npm-groovy-lint into your NPM package and call lint & fix via module, using the same options than from npm-groovy-lint command line

Example

    npm install npm-groovy-lint --save
    const NpmGroovyLint = require("npm-groovy-lint/groovy-lint.js");
    const fse = require("fs-extra");

    const npmGroovyLintConfig = {
        source: fse.readFileSync('./lib/example/SampleFile.groovy').toString(),
        fix: true,
        loglevel: 'warning',
        output: 'none'
    };
    const linter = new NpmGroovyLint(npmGroovyLintConfig, {});
    await linter.run();
    console.log(JSON.stringify(linter.lintResult));

TROUBLESHOOTING

  • On some environments, it has been observed that installed Groovy version must match Groovy embedded jars delivered with npm-groovy-lint (Groovy 3.0.5)

CONTRIBUTE

Contributions are very welcome !

Please follow Contribution instructions

THANKS

Other packages used

  • CodeNarc: groovy lint
  • java-caller: Easy call Java commands from Node
  • slf4j: logging for CodeNarc
  • log4j: logging for CodeNarc
  • GMetrics: Code measures for CodeNarc
  • Inspiration from eslint about configuration and run patterns

Contributors

nvuillamDave GallantwarhodpawelkopkadocwhatCatSue
Nicolas VuillamyDave GallantHoward LoPawel KopkadocwhatCatSue

RELEASE NOTES

[8.0.0] Unreleased

  • Upgrade to CodeNarc 2.0.0
    • Upgrade jars
    • Adapt Indentation rule to new behaviour
    • Use codenarc --ruleset arg instead of temp ruleset file
  • Replace super-linter by Mega-Linter
  • Fixes
    • (#127) Formatting breaks code, converting else if into elseif in some cases

[7.6.2] 2020-09-09

[7.6.0] 2020-09-08

  • Add GitHub Action GitHub Super-Linter to the repository
  • Update Dockerfile to pass Docker lint rules

[7.5.5] 2020-09-05

[7.5.4] 2020-09-04

  • Update frameworks detection

[7.5.1] 2020-09-02

  • Fix (#96) --fix adds redundant space into ${VARIABLE} (SpaceBeforeOpeningBrace fix rule error)
  • Fix grails framework detection
  • Fix Groovy parsing parsing when multiple files
  • Add .gvy and .nf in default browsed files extensions

[7.4.3] 2020-08-29

  • Upgrade java-caller to v2.2.0
    • Fix CLASSPATH on windows in case there are spaces in paths

[7.4.2] 2020-08-26

  • Fix (#90) When log level is specified number of linted files appear to be off

[7.4.1] 2020-08-23

  • (88) Fix Docker image to allow to use extra parameters (by Howard Lo)

[7.4.0] 2020-08-17

[7.3.0] 2020-08-15

  • Allow to link to CodeNarc RuleSet files from .groovylintrc.json, using property "codeNarcRulesets". Warning: doing so means that all other properties of config file will be ignored.

[7.1.1] 2020-08-11

[7.1.0] 2020-08-10

  • Externalize JavaCaller class into a separate package java-caller and use it

[7.0.0] 2020-08-07

  • New default recommended rules (activate/deactivate/change severity)
  • Allow to call --config recommended-jenkinsfile to use delivered .groovylintrc-recommended-jenkinsfile.json

PREVIOUS VERSIONS

See complete CHANGELOG

Keywords

FAQs

Package last updated on 14 Nov 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc