npm-groovy-lint 9.3.2 → 9.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,23 @@
2
2
 
3
3
  ## UNRELEASED
4
4
 
5
+ - Add your updates here :)
6
+
7
+ ## [9.5.0] 2022-04-12
8
+
9
+ - Disable Amplitude anonymous stats by default (use `--insight` to enable them)
10
+
11
+ ## [9.4.1] 2022-01-22
12
+
13
+ - Upgrade node-sarif-builder to 2.0.1 and send npm-groovy-lint version in SARIF logs
14
+ - New range detection for rules:
15
+ - MethodReturnTypeRequired
16
+ - UnusedImport
17
+
18
+ ## [9.4.0] 2022-01-11
19
+
20
+ - Add [SARIF](https://sarifweb.azurewebsites.net/) output format using [node-sarif-builder](https://github.com/nvuillam/node-sarif-builder)
21
+
5
22
  ## [9.3.2] 2022-01-09
6
23
 
7
24
  - Upgrade cli-progress to avoid [colors lib boring but harmless hack](https://github.com/Marak/colors.js/issues/285)
package/README.md CHANGED
@@ -43,32 +43,32 @@ Any **question**, **problem** or **enhancement request** ? Ask [**here**](https:
43
43
  npm-groovy-lint OPTIONS
44
44
  ```
45
45
 
46
- | Parameter | Type | Description |
47
- |-------------------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
48
- | -p<br/> --path | String | Directory containing the files to lint<br/> Example: `./path/to/my/groovy/files` |
49
- | -f<br/> --files | String | Comma-separated list of Ant-style file patterns specifying files that must be included.<br/> Default: `"**/*.groovy,**/Jenkinsfile,**/*.gradle"`<br/>Examples:<br/> - `"**/Jenkinsfile"`<br/> - `"**/*.groovy"`<br/> - `"**/*.gradle"`<br/> - `"**/mySingleFile.groovy"` |
50
- | -o<br/> --output | String | Output format (txt,json,html,xml), or path to a file with one of these extensions<br/> Default: `txt`<br/> Examples:<br/> - `"txt"`<br/> - `"json"`<br/> - `"./logs/myLintResults.txt"`<br/> - `"./logs/myLintResults.json"`<br/> - `"./logs/myLintResults.html"`<br/> - `"./logs/myLintResults.xml"` |
51
- | -l<br/> --loglevel | String | Log level (error,warning or info)<br/>Default: info |
52
- | --failon | String | Defines the error level where CLI will fail (return code = 1). error,warning,info or none. Each failure level includes the more critical ones. |
53
- | -c<br/> --config | String | Custom path to [GroovyLint config file](#Configuration), or preset config `recommended|recommended-jenkinsfile|all`<br/> Default: Browse current directory to find `.groovylintrc.json|js|yml|package.json` config file, or default npm-groovy-lint config if not defined.<br/>Note: command-line arguments have priority on config file properties |
54
- | --parse | Boolean | Try to compile the source code and return parse errors (since v5.7.0, default to true, use --no-parse to deactivate) |
55
- | --format | Boolean | Format source code |
56
- | --fix | Boolean | Automatically fix problems when possible<br/> See [Autofixable rules](#Autofixable-rules) |
57
- | -x<br/> --fixrules | String | Option for --fix argument: List of rule identifiers to fix (if not specified, all available fixes will be applied). See [Autofixable rules](#Autofixable-rules) <br/> Examples:<br/> - `"SpaceBeforeClosingBrace,SpaceAfterClosingBrace,UnusedImport"`<br/> - `"Indentation"`<br/> |
58
- | --nolintafter | Boolean | When 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 |
59
- | -r<br/> --rulesets | String | [RuleSet file(s)](http://codenarc.github.io/CodeNarc/codenarc-creating-ruleset.html) to use for linting, if you do not want to use recommended rules or .groovylintrc.js defined rules.<br/>If list of comma separated strings corresponding to CodeNarc rules, a RuleSet file will be dynamically generated </br> Examples:<br/> - `"./config/codenarc/RuleSet-Custom.groovy"`<br/> - `"./path/to/my/ruleset/files"`<br/>- `Indentation{"spacesPerIndentLevel":2,"severity":"warning"},UnnecessarySemicolon,UnnecessaryGString` |
60
- | --rulesetsoverridetype | String | If list of rules sent in rulesets option, defines if they replace rules defined in .groovylintrc.json, or if they are appended<br/> Values: `replaceConfig` (default), `appendConfig` |
61
- | -s<br/> --source | String | If path and files are not set, you can directly send the source code string to analyze |
62
- | --verbose | Boolean | More outputs in console, including performed fixes |
63
- | -i<br/> --ignorepattern | String | Comma-separated list of Ant-style file patterns specifying files that must be ignored<br/> Default: none<br/> Example: `"**/test/*""` |
64
- | --noserver | Boolean | npm-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 |
65
- | --returnrules | Boolean | Return rules descriptions and URL if set |
66
- | --javaexecutable | String | Override java executable to use <br/>Default: java<br/>Example: C:\\Program Files\\Java\\jdk1.8.0_144\\bin\\java.exe |
67
- | --javaoptions | String | Override java options to use <br/>Default: "-Xms256m,-Xmx2048m" |
68
- | --no-insight | Boolean | npm-groovy-lint collects anonymous usage statistics using [amplitude](https://www.npmjs.com/package/amplitude), in order to make new improvements based on how users use this package. <br/> Summary charts are available at [https://tinyurl.com/groovy-stats](https://tinyurl.com/groovy-stats).<br/> Analytics obviously does not receive sensitive information like your code, as you can see in [analytics.js](https://github.com/nvuillam/npm-groovy-lint/blob/master/lib/analytics.js).<br/> If you want to disable anonymous usage statistics, use `--no-insight` option. |
69
- | --codenarcargs | String | Use core CodeNarc arguments (all npm-groovy-lint arguments will be ignored)<br/> Doc: <http://codenarc.github.io/CodeNarc/codenarc-command-line.html><br/> Example: `npm-groovy-lint --codenarcargs -basedir="lib/example" -rulesetfiles="file:lib/example/RuleSet-Groovy.groovy" -maxPriority1Violations=0 -report="xml:ReportTestCodenarc.xml` |
70
- | -h<br/> --help | Boolean | Show help (npm-groovy-lint -h OPTIONNAME to see option detail with examples) |
71
- | -v<br/> --version | Boolean | Show npm-groovy-lint version (with CodeNarc version) |
46
+ | Parameter | Type | Description |
47
+ |-------------------------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
48
+ | -p<br/> --path | String | Directory containing the files to lint<br/> Example: `./path/to/my/groovy/files` |
49
+ | -f<br/> --files | String | Comma-separated list of Ant-style file patterns specifying files that must be included.<br/> Default: `"**/*.groovy,**/Jenkinsfile,**/*.gradle"`<br/>Examples:<br/> - `"**/Jenkinsfile"`<br/> - `"**/*.groovy"`<br/> - `"**/*.gradle"`<br/> - `"**/mySingleFile.groovy"` |
50
+ | -o<br/> --output | String | Output format (txt,json,sarif,html,xml), or path to a file with one of these extensions<br/> Default: `txt`<br/> Examples:<br/> - `"txt"`<br/> - `"json"`<br/> - `"./logs/myLintResults.txt"`<br/> - `"./logs/myLintResults.sarif"`<br/> - `"./logs/myLintResults.html"`<br/> - `"./logs/myLintResults.xml"` |
51
+ | -l<br/> --loglevel | String | Log level (error,warning or info)<br/>Default: info |
52
+ | --failon | String | Defines the error level where CLI will fail (return code = 1). error,warning,info or none. Each failure level includes the more critical ones. |
53
+ | -c<br/> --config | String | Custom path to [GroovyLint config file](#Configuration), or preset config `recommended|recommended-jenkinsfile|all`<br/> Default: Browse current directory to find `.groovylintrc.json|js|yml|package.json` config file, or default npm-groovy-lint config if not defined.<br/>Note: command-line arguments have priority on config file properties |
54
+ | --parse | Boolean | Try to compile the source code and return parse errors (since v5.7.0, default to true, use --no-parse to deactivate) |
55
+ | --format | Boolean | Format source code |
56
+ | --fix | Boolean | Automatically fix problems when possible<br/> See [Autofixable rules](#Autofixable-rules) |
57
+ | -x<br/> --fixrules | String | Option for --fix argument: List of rule identifiers to fix (if not specified, all available fixes will be applied). See [Autofixable rules](#Autofixable-rules) <br/> Examples:<br/> - `"SpaceBeforeClosingBrace,SpaceAfterClosingBrace,UnusedImport"`<br/> - `"Indentation"`<br/> |
58
+ | --nolintafter | Boolean | When 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 |
59
+ | -r<br/> --rulesets | String | [RuleSet file(s)](http://codenarc.github.io/CodeNarc/codenarc-creating-ruleset.html) to use for linting, if you do not want to use recommended rules or .groovylintrc.js defined rules.<br/>If list of comma separated strings corresponding to CodeNarc rules, a RuleSet file will be dynamically generated </br> Examples:<br/> - `"./config/codenarc/RuleSet-Custom.groovy"`<br/> - `"./path/to/my/ruleset/files"`<br/>- `Indentation{"spacesPerIndentLevel":2,"severity":"warning"},UnnecessarySemicolon,UnnecessaryGString` |
60
+ | --rulesetsoverridetype | String | If list of rules sent in rulesets option, defines if they replace rules defined in .groovylintrc.json, or if they are appended<br/> Values: `replaceConfig` (default), `appendConfig` |
61
+ | -s<br/> --source | String | If path and files are not set, you can directly send the source code string to analyze |
62
+ | --verbose | Boolean | More outputs in console, including performed fixes |
63
+ | -i<br/> --ignorepattern | String | Comma-separated list of Ant-style file patterns specifying files that must be ignored<br/> Default: none<br/> Example: `"**/test/*""` |
64
+ | --noserver | Boolean | npm-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 |
65
+ | --returnrules | Boolean | Return rules descriptions and URL if set |
66
+ | --javaexecutable | String | Override java executable to use <br/>Default: java<br/>Example: C:\\Program Files\\Java\\jdk1.8.0_144\\bin\\java.exe |
67
+ | --javaoptions | String | Override java options to use <br/>Default: "-Xms256m,-Xmx2048m" |
68
+ | --insight | Boolean | npm-groovy-lint collects anonymous usage statistics using [amplitude](https://www.npmjs.com/package/amplitude), in order to make new improvements based on how users use this package. <br/> Summary charts are available at [https://tinyurl.com/groovy-stats](https://tinyurl.com/groovy-stats).<br/> Analytics obviously does not receive sensitive information like your code, as you can see in [analytics.js](https://github.com/nvuillam/npm-groovy-lint/blob/master/lib/analytics.js).<br/> If you want to enable anonymous usage statistics, use `--insight` option. |
69
+ | --codenarcargs | String | Use core CodeNarc arguments (all npm-groovy-lint arguments will be ignored)<br/> Doc: <http://codenarc.github.io/CodeNarc/codenarc-command-line.html><br/> Example: `npm-groovy-lint --codenarcargs -basedir="lib/example" -rulesetfiles="file:lib/example/RuleSet-Groovy.groovy" -maxPriority1Violations=0 -report="xml:ReportTestCodenarc.xml` |
70
+ | -h<br/> --help | Boolean | Show help (npm-groovy-lint -h OPTIONNAME to see option detail with examples) |
71
+ | -v<br/> --version | Boolean | Show npm-groovy-lint version (with CodeNarc version) |
72
72
 
73
73
  ## Installation
74
74
 
@@ -92,7 +92,7 @@ Create a file named **.groovylintrc.json** in the current or any parent director
92
92
  - Jenkinsfile
93
93
  - **.groovylintrc.json** _(do not forget the dot at the beginning of the file name)_
94
94
 
95
- *If you are using [VsCode Groovy Lint extension](https://marketplace.visualstudio.com/items?itemName=NicolasVuillamy.vscode-groovy-lint), just use QuickFix* ***Ignore in all files*** *and it will generate groovylintrc.json file*
95
+ *If you are using [VsCode Groovy Lint extension](https://marketplace.visualstudio.com/items?itemName=NicolasVuillamy.vscode-groovy-lint), just use QuickFix* ***Ignore in all files*** _and it will generate groovylintrc.json file_
96
96
 
97
97
  ### Format
98
98
 
@@ -304,7 +304,7 @@ class CodeNarcCaller {
304
304
  });
305
305
 
306
306
  if (this.serverStatus === "running") {
307
- console.log(c.green(`GroovyLint: Started CodeNarc Server`));
307
+ debug(c.green(`GroovyLint: Started CodeNarc Server`));
308
308
  return true;
309
309
  } else {
310
310
  return false;
@@ -35,7 +35,7 @@ async function prepareCodeNarcCall(options) {
35
35
  const pathParse = path.parse(options.sourcefilepath);
36
36
  cnPath = cnPath + "/codeNarcTmpDir_" + Math.random();
37
37
  await fs.ensureDir(cnPath, { mode: "0777" });
38
- const pathBase = pathParse.base.replace(/ /g, '_');
38
+ const pathBase = pathParse.base.replace(/ /g, "_");
39
39
  result.tmpGroovyFileName = path.resolve(cnPath + "/" + pathBase);
40
40
  cnFiles = "**/" + pathBase;
41
41
  }
@@ -91,8 +91,14 @@ async function prepareCodeNarcCall(options) {
91
91
 
92
92
  // Output
93
93
  result.output = options.output.replace(/^"(.*)"$/, "$1");
94
- if (["txt", "json", "none"].includes(result.output) || result.output.endsWith(".txt") || result.output.endsWith(".json")) {
95
- result.outputType = result.output.endsWith(".txt") ? "txt" : result.output.endsWith(".json") ? "json" : result.output;
94
+ if (["txt", "json", "sarif", "none"].includes(result.output) ||
95
+ result.output.endsWith(".txt") ||
96
+ result.output.endsWith(".sarif") ||
97
+ result.output.endsWith(".json")) {
98
+ result.outputType = result.output.endsWith(".txt") ? "txt"
99
+ : result.output.endsWith(".json") ? "json"
100
+ : result.output.endsWith(".sarif") ? "sarif"
101
+ : result.output;
96
102
  result.codenarcArgs.push(`-report=json:stdout`);
97
103
  } else if (["html", "xml"].includes(result.output.split(".").pop())) {
98
104
  result.outputType = result.output
@@ -101,11 +107,11 @@ async function prepareCodeNarcCall(options) {
101
107
  .endsWith("html")
102
108
  ? "html"
103
109
  : result.output
104
- .split(".")
105
- .pop()
106
- .endsWith("xml")
107
- ? "xml"
108
- : "";
110
+ .split(".")
111
+ .pop()
112
+ .endsWith("xml")
113
+ ? "xml"
114
+ : "";
109
115
  const ext = result.output.split(".").pop();
110
116
  result.codenarcArgs.push(`-report=${ext}:${result.output}`);
111
117
 
@@ -266,7 +272,7 @@ async function parseCodeNarcResult(options, codeNarcBaseDir, codeNarcJsonResult,
266
272
  }
267
273
 
268
274
  // Parse error definitions & build url if not already done and not noreturnrules option
269
- if (result.rules == null && options.returnrules === true) {
275
+ if (result.rules == null && (options.returnrules === true || options.output.includes("sarif"))) {
270
276
  const configAllFileName = await getConfigFileName(__dirname, null, [".groovylintrc-all.json"]);
271
277
  const grooylintrcAllRules = Object.keys(JSON.parse(fs.readFileSync(configAllFileName, "utf8").toString()).rules);
272
278
  const rules = {};
@@ -338,8 +344,8 @@ async function buildRuleSets(options) {
338
344
  typeof ruleFromConfig === "object"
339
345
  ? Object.assign(ruleFromConfig, ruleOptions)
340
346
  : Object.keys(ruleOptions).length > 0
341
- ? ruleOptions
342
- : ruleFromConfig;
347
+ ? ruleOptions
348
+ : ruleFromConfig;
343
349
  const ruleDef = buildCodeNarcRule(ruleName, mergedRuleConfig);
344
350
  return ruleDef;
345
351
  });
@@ -356,8 +362,8 @@ async function buildRuleSets(options) {
356
362
  typeof ruleDef === "object"
357
363
  ? Object.assign(ruleDef, ruleFromRuleSetsArg)
358
364
  : Object.keys(ruleFromRuleSetsArg).length > 0
359
- ? ruleFromRuleSetsArg
360
- : ruleDef;
365
+ ? ruleFromRuleSetsArg
366
+ : ruleDef;
361
367
  }
362
368
  // Add in the list of rules to test , except if it is disabled
363
369
  if (!(ruleDef === "off" || ruleDef.disabled === true || ruleDef.enabled === false)) {
@@ -10,7 +10,7 @@ const { NPM_GROOVY_LINT_CONSTANTS, loadConfig, getConfigFileName } = require("./
10
10
  const optionsDefinition = require("./options");
11
11
  const { computeStats, processOutput } = require("./output.js");
12
12
  const { recordAnonymousEvent } = require("./analytics.js");
13
- const { getSourceLines, isErrorInLogLevelScope } = require("./utils");
13
+ const { getNpmGroovyLintVersion, getSourceLines, isErrorInLogLevelScope } = require("./utils");
14
14
 
15
15
  class NpmGroovyLint {
16
16
  "use strict";
@@ -161,7 +161,7 @@ class NpmGroovyLint {
161
161
  }
162
162
 
163
163
  // Manage anonymous stats
164
- if (["initialCall", "index"].includes(this.origin) && this.options.insight !== false) {
164
+ if (["initialCall", "index"].includes(this.origin) && this.options.insight === true) {
165
165
  this.startElapse = performance.now();
166
166
  }
167
167
 
@@ -179,16 +179,7 @@ class NpmGroovyLint {
179
179
 
180
180
  // Show version
181
181
  if (this.options.version) {
182
- let v = process.env.npm_package_version;
183
- if (!v) {
184
- try {
185
- const FindPackageJson = require("find-package-json");
186
- const finder = FindPackageJson(__dirname);
187
- v = finder.next().value.version;
188
- } catch {
189
- v = "error";
190
- }
191
- }
182
+ const v = getNpmGroovyLintVersion();
192
183
 
193
184
  const codeNarcVersionLinter = await new NpmGroovyLint([process.execPath, "", "--codenarcargs", "-version"], {}).run();
194
185
  const codeNarcVersionLines = [(await getSourceLines(codeNarcVersionLinter.codeNarcStdOut))[0]];
@@ -304,7 +295,7 @@ class NpmGroovyLint {
304
295
  }
305
296
 
306
297
  // Manage anonymous usage stats (except if current lint has been cancelled by a duplicate call)
307
- if (this.startElapse && this.options.insight !== false && this.status !== 9) {
298
+ if (this.startElapse && this.options.insight === true && this.status !== 9) {
308
299
  const elapsedTimeMs = parseInt(performance.now() - this.startElapse);
309
300
  const callerKey = this.origin === "index" ? "cli" : "module";
310
301
  const actionKey = this.options.format ? "format" : this.options.fix ? "fix" : "lint";
package/lib/options.js CHANGED
@@ -119,8 +119,8 @@ module.exports = optionator({
119
119
  alias: "o",
120
120
  type: "String",
121
121
  default: "txt",
122
- description: "Output format (txt,json,html,xml), or path to a file with one of these extensions",
123
- example: ["txt", "json", "./logs/myLintResults.txt", "./logs/myLintResults.json", "./logs/myLintResults.html", "./logs/myLintResults.xml"]
122
+ description: "Output format (txt,json,sarif,html,xml), or path to a file with one of these extensions",
123
+ example: ["txt", "json", "sarif", "./logs/myLintResults.txt", "./logs/myLintResults.json","./logs/myLintResults.sarif", "./logs/myLintResults.html", "./logs/myLintResults.xml"]
124
124
  },
125
125
  {
126
126
  option: "loglevel",
@@ -221,8 +221,9 @@ module.exports = optionator({
221
221
  {
222
222
  option: "insight",
223
223
  type: "Boolean",
224
+ default: false,
224
225
  description:
225
- "npm-groovy-lint collects anonymous usage statistics using package https://www.npmjs.com/package/insight. If you do not want to share them, use --no-insight option"
226
+ "npm-groovy-lint collects anonymous usage statistics using package https://www.npmjs.com/package/insight. If you want to enable them, use --insight option"
226
227
  },
227
228
  {
228
229
  option: "help",
package/lib/output.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // Output management
2
2
  const c = require("ansi-colors");
3
3
  const fse = require("fs-extra");
4
+ const { SarifBuilder, SarifRunBuilder, SarifResultBuilder, SarifRuleBuilder } = require("node-sarif-builder");
4
5
  const path = require("path");
5
- const { isErrorInLogLevelScope } = require("./utils");
6
+ const { isErrorInLogLevelScope, getNpmGroovyLintVersion } = require("./utils");
6
7
 
7
8
  // Compute statistics for output
8
9
  function computeStats(lintResult) {
@@ -204,8 +205,81 @@ async function processOutput(outputType, output, lintResult, options, fixer = nu
204
205
  outputString = JSON.stringify(lintResult);
205
206
  console.log(outputString);
206
207
  }
208
+ } else if (outputType === "sarif") {
209
+ const sarifJsonString = buildSarifResult(lintResult);
210
+ // SARIF file
211
+ if (output.endsWith(".sarif")) {
212
+ fse.writeFileSync(output, sarifJsonString);
213
+ const absolutePath = path.resolve(".", output);
214
+ outputString = "GroovyLint: Logged SARIF results in file " + absolutePath;
215
+ console.info(outputString);
216
+ } else {
217
+ // SARIF in stdout
218
+ outputString = sarifJsonString;
219
+ console.log(sarifJsonString);
220
+ }
207
221
  }
208
222
  return outputString;
209
223
  }
210
224
 
225
+ function buildSarifResult(lintResult) {
226
+ // SARIF builder
227
+ const sarifBuilder = new SarifBuilder();
228
+ // SARIF Run builder
229
+ const sarifRunBuilder = new SarifRunBuilder().initSimple({
230
+ toolDriverName: "npm-groovy-lint",
231
+ toolDriverVersion: getNpmGroovyLintVersion(),
232
+ url: "https://nvuillam.github.io/npm-groovy-lint/"
233
+ });
234
+ // SARIF rules
235
+ for (const ruleId of Object.keys(lintResult.rules || {})) {
236
+ const rule = lintResult.rules[ruleId];
237
+ const sarifRuleBuilder = new SarifRuleBuilder().initSimple({
238
+ ruleId: ruleId,
239
+ shortDescriptionText: rule.description,
240
+ helpUri: rule.docUrl
241
+ });
242
+ sarifRunBuilder.addRule(sarifRuleBuilder);
243
+ }
244
+ // Add SARIF results (individual errors)
245
+ for (const fileNm of Object.keys(lintResult.files)) {
246
+ const fileErrors = lintResult.files[fileNm].errors;
247
+ for (const err of fileErrors) {
248
+ const sarifResultBuilder = new SarifResultBuilder();
249
+ const sarifResultInit = {
250
+ level: err.severity === "info" ? "note" : err.severity, // Other values can be "warning" or "error"
251
+ messageText: err.msg,
252
+ ruleId: err.rule,
253
+ fileUri: process.env.SARIF_URI_ABSOLUTE
254
+ ? "file:///" + fileNm.replace(/\\/g, "/")
255
+ : path.relative(process.cwd(), fileNm)
256
+ };
257
+ if (err && err.range && err.range.start && (err.range.start.line === 0 || err.range.start.line > 0)) {
258
+ sarifResultInit.startLine = fixLine(err.range.start.line);
259
+ sarifResultInit.startColumn = fixCol(err.range.start.character);
260
+ sarifResultInit.endLine = fixLine(err.range.end.line);
261
+ sarifResultInit.endColumn = fixCol(err.range.end.character);
262
+ }
263
+ sarifResultBuilder.initSimple(sarifResultInit);
264
+ sarifRunBuilder.addResult(sarifResultBuilder);
265
+ }
266
+ }
267
+ sarifBuilder.addRun(sarifRunBuilder);
268
+ return sarifBuilder.buildSarifJsonString({ indent: false });
269
+ }
270
+
271
+ function fixLine(val) {
272
+ if (val === null) {
273
+ return undefined;
274
+ }
275
+ return val === 0 ? 1 : val;
276
+ }
277
+
278
+ function fixCol(val) {
279
+ if (val === null) {
280
+ return undefined;
281
+ }
282
+ return val === 0 ? 1 : val + 1;
283
+ }
284
+
211
285
  module.exports = { computeStats, processOutput };
@@ -0,0 +1,21 @@
1
+ // Too many methods in a class
2
+
3
+ const { getVariableRange } = require("../utils");
4
+
5
+ const rule = {
6
+ variables: [
7
+ {
8
+ name: "METHODNAME",
9
+ regex: /Method "(.*)" has a dynamic return type/,
10
+ regexPos: 1
11
+ }
12
+ ],
13
+ range: {
14
+ type: "function",
15
+ func: (errLine, errItem, evaluatedVars) => {
16
+ return getVariableRange(errLine, evaluatedVars, "METHODNAME", errItem);
17
+ }
18
+ }
19
+ };
20
+
21
+ module.exports = { rule };
@@ -1,6 +1,6 @@
1
1
  // Unused import
2
2
 
3
- const { getVariable } = require("../utils");
3
+ const { getVariable, getVariableRange } = require("../utils");
4
4
 
5
5
  const rule = {
6
6
  scope: "file",
@@ -12,6 +12,12 @@ const rule = {
12
12
  regexPos: 1
13
13
  }
14
14
  ],
15
+ range: {
16
+ type: "function",
17
+ func: (errLine, errItem, evaluatedVars) => {
18
+ return getVariableRange(errLine, evaluatedVars, "CLASSNAME", errItem);
19
+ }
20
+ },
15
21
  fix: {
16
22
  label: "Remove unused import",
17
23
  type: "function",
package/lib/utils.js CHANGED
@@ -394,6 +394,20 @@ function splitMulti(str, tokens) {
394
394
  return str;
395
395
  }
396
396
 
397
+ function getNpmGroovyLintVersion(){
398
+ let v = process.env.npm_package_version;
399
+ if (!v) {
400
+ try {
401
+ const FindPackageJson = require("find-package-json");
402
+ const finder = FindPackageJson(__dirname);
403
+ v = finder.next().value.version;
404
+ } catch {
405
+ v = "error";
406
+ }
407
+ }
408
+ return v ;
409
+ }
410
+
397
411
  module.exports = {
398
412
  addImport,
399
413
  addSpaceAfterChar,
@@ -405,6 +419,7 @@ module.exports = {
405
419
  findRangeBetweenStrings,
406
420
  getIndentLength,
407
421
  getLastStringRange,
422
+ getNpmGroovyLintVersion,
408
423
  getOutOfBracesStrings,
409
424
  getSourceLines,
410
425
  getStringRange,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "npm-groovy-lint",
3
- "version": "9.3.2",
3
+ "version": "9.5.0",
4
4
  "description": "Lint, format and auto-fix your Groovy / Jenkinsfile / Gradle files",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -58,6 +58,7 @@
58
58
  "import-fresh": "^3.2.1",
59
59
  "ip": "^1.1.5",
60
60
  "java-caller": "^2.2.4",
61
+ "node-sarif-builder": "^2.0.1",
61
62
  "optionator": "^0.8.3",
62
63
  "semver": "^7.1.3",
63
64
  "strip-json-comments": "^3.0.1",
@@ -75,7 +76,7 @@
75
76
  "eslint-plugin-standard": "^5.0.0",
76
77
  "mocha": "^7.0.1",
77
78
  "nyc": "^15.1.0",
78
- "prettier": "1.19.1",
79
+ "prettier": "^1.19.1",
79
80
  "rimraf": "^3.0.2",
80
81
  "which": "^2.0.2"
81
82
  },