From 1a804b830465543223df0e18bbdbf6a2118b9181 Mon Sep 17 00:00:00 2001 From: Nicolas Vuillamy Date: Sun, 25 Aug 2024 23:12:19 +0200 Subject: [PATCH] Convert to ES Module (#412) * Update dependency strip-json-comments to v5 * v0 * Imports part 1 * More ESM * more * More ESM * Working ? ^^ * fixes * upgrade which * find-package-json * fix * chalk import * commondir * findJavaHome --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .cspell.json | 1 + CHANGELOG.md | 10 +- docs/CHANGELOG.md | 10 +- lib/codenarc-caller.js | 42 +++-- lib/codenarc-factory.js | 27 +-- lib/config.js | 30 ++-- lib/filter.js | 3 +- lib/groovy-lint-fix.js | 26 ++- lib/groovy-lint-rules.js | 22 +-- lib/groovy-lint.js | 33 ++-- lib/index.js | 6 +- lib/options.js | 15 +- lib/output.js | 26 +-- lib/rules/AssignmentInConditional.js | 4 +- lib/rules/BlankLineBeforePackage.js | 4 +- lib/rules/BlockEndsWithBlankLine.js | 4 +- lib/rules/BlockStartsWithBlankLine.js | 4 +- lib/rules/BracesForClass.js | 4 +- lib/rules/BracesForForLoop.js | 4 +- lib/rules/BracesForIfElse.js | 4 +- lib/rules/BracesForMethod.js | 4 +- lib/rules/BracesForTryCatchFinally.js | 4 +- lib/rules/CatchException.js | 4 +- lib/rules/ClassEndsWithBlankLine.js | 4 +- lib/rules/ClassStartsWithBlankLine.js | 4 +- lib/rules/ClosingBraceNotAlone.js | 2 +- lib/rules/ConsecutiveBlankLines.js | 4 +- lib/rules/DuplicateImport.js | 4 +- lib/rules/DuplicateNumberLiteral.js | 4 +- lib/rules/DuplicateStringLiteral.js | 4 +- lib/rules/ElseBlockBraces.js | 4 +- lib/rules/ExplicitArrayListInstantiation.js | 2 +- lib/rules/ExplicitLinkedListInstantiation.js | 2 +- lib/rules/FileEndsWithoutNewline.js | 4 +- lib/rules/GStringExpressionWithinString.js | 2 +- lib/rules/IfStatementBraces.js | 4 +- lib/rules/Indentation.js | 4 +- lib/rules/IndentationClosingBraces.js | 4 +- lib/rules/IndentationComments.js | 2 +- lib/rules/InsecureRandom.js | 4 +- lib/rules/JavaIoPackageAccess.js | 4 +- lib/rules/MethodCount.js | 4 +- lib/rules/MethodParameterTypeRequired.js | 4 +- lib/rules/MethodReturnTypeRequired.js | 4 +- lib/rules/MisorderedStaticImports.js | 2 +- lib/rules/MissingBlankLineAfterImports.js | 4 +- lib/rules/MissingBlankLineAfterPackage.js | 4 +- lib/rules/NoDef.js | 4 +- lib/rules/NoJavaUtilDate.js | 4 +- lib/rules/NoTabCharacter.js | 4 +- lib/rules/SimpleDateFormatMissingLocale.js | 4 +- lib/rules/SpaceAfterCatch.js | 4 +- lib/rules/SpaceAfterComma.js | 4 +- lib/rules/SpaceAfterFor.js | 4 +- lib/rules/SpaceAfterIf.js | 4 +- lib/rules/SpaceAfterMethodCallName.js | 4 +- lib/rules/SpaceAfterOpeningBrace.js | 4 +- lib/rules/SpaceAfterSemicolon.js | 4 +- lib/rules/SpaceAfterSwitch.js | 4 +- lib/rules/SpaceAfterWhile.js | 4 +- lib/rules/SpaceAroundOperator.js | 4 +- lib/rules/SpaceBeforeClosingBrace.js | 4 +- lib/rules/SpaceBeforeOpeningBrace.js | 4 +- lib/rules/SpaceInsideParentheses.js | 4 +- lib/rules/SystemExit.js | 4 +- lib/rules/TrailingWhitespace.js | 2 +- lib/rules/UnnecessaryDefInFieldDeclaration.js | 4 +- .../UnnecessaryDefInMethodDeclaration.js | 4 +- .../UnnecessaryDefInVariableDeclaration.js | 4 +- lib/rules/UnnecessaryDotClass.js | 4 +- lib/rules/UnnecessaryFinalOnPrivateMethod.js | 4 +- lib/rules/UnnecessaryGString.js | 4 +- lib/rules/UnnecessaryGroovyImport.js | 4 +- lib/rules/UnnecessaryPackageReference.js | 4 +- ...saryParenthesesForMethodCallWithClosure.js | 4 +- lib/rules/UnnecessaryPublicModifier.js | 4 +- lib/rules/UnnecessarySemicolon.js | 4 +- lib/rules/UnnecessaryToString.js | 4 +- lib/rules/UnusedImport.js | 4 +- lib/rules/UnusedMethodParameter.js | 4 +- lib/rules/UnusedVariable.js | 4 +- lib/rules/VariableName.js | 4 +- lib/rules/VariableTypeRequired.js | 4 +- lib/utils.js | 52 ++++-- package-lock.json | 165 ++++++++++++++---- package.json | 10 +- scripts/build-config-all.js | 89 +++++----- scripts/build-server.js | 19 +- scripts/deploy-in-vscode.js | 3 +- test/errors.test.js | 16 +- test/helpers/common.js | 14 +- test/helpers/init.js | 11 +- test/lint-api.test.js | 37 ++-- test/lint-build-fix.test.js | 23 ++- test/lint-build-format.test.js | 23 ++- test/lint-build.test.js | 21 ++- test/lint-comments.test.js | 7 +- test/lint-fix.rules.test.js | 16 +- test/lint-fix.test.js | 51 +++--- test/lint-format.test.js | 35 ++-- test/lint-range.rules.test.js | 16 +- test/miscellaneous.test.js | 39 +++-- test/server.test.js | 9 +- 103 files changed, 638 insertions(+), 535 deletions(-) diff --git a/.cspell.json b/.cspell.json index c211176a..527c81cb 100644 --- a/.cspell.json +++ b/.cspell.json @@ -18,6 +18,7 @@ "anymatch", "appender", "Appender", + "apos", "archy", "argparse", "arity", diff --git a/CHANGELOG.md b/CHANGELOG.md index fac61c67..464806cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,12 @@ ## Beta - - Setup renovate - - Upgrade dependencies, including base package node-java-caller - - Upgrade NodeJs to minimum version 20 - - Upgrade MegaLinter to v8 +- Convert to ES6 Module +- Setup renovate +- Upgrade dependencies, including base package node-java-caller +- Upgrade NodeJs to minimum version 20 +- Upgrade MegaLinter to v8 +- Remove decode-html-entities dependency ## [14.6.0] 2024-05-08 diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index fac61c67..464806cf 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,10 +2,12 @@ ## Beta - - Setup renovate - - Upgrade dependencies, including base package node-java-caller - - Upgrade NodeJs to minimum version 20 - - Upgrade MegaLinter to v8 +- Convert to ES6 Module +- Setup renovate +- Upgrade dependencies, including base package node-java-caller +- Upgrade NodeJs to minimum version 20 +- Upgrade MegaLinter to v8 +- Remove decode-html-entities dependency ## [14.6.0] 2024-05-08 diff --git a/lib/codenarc-caller.js b/lib/codenarc-caller.js index 4634a737..7666df20 100644 --- a/lib/codenarc-caller.js +++ b/lib/codenarc-caller.js @@ -1,20 +1,23 @@ // Call CodeNarc by server or java -const axios = require("axios").default; -const cliProgress = require("cli-progress"); -const debug = require("debug")("npm-groovy-lint"); -const trace = require("debug")("npm-groovy-lint-trace"); -const { JavaCaller } = require("java-caller"); -const optionsDefinition = require("./options"); -const { performance } = require("perf_hooks"); -const c = require("chalk"); +import axios from "axios"; +import * as cliProgress from "cli-progress"; +import Debug from "debug"; +const debug = Debug("npm-groovy-lint"); +const trace = Debug("npm-groovy-lint-trace"); +import { JavaCaller } from "java-caller"; +import { optionsDefinition } from "./options.js"; +import { performance } from "node:perf_hooks"; +import c from "chalk"; +import findJavaHome from "find-java-home"; +import * as path from "path"; +import { fileURLToPath } from "node:url"; // Request over IPv4 because Java typically prefers it. -const http = require("http"); +import http from "http"; axios.defaults.httpAgent = new http.Agent({ family: 4, keepAlive: true }); +const __dirname = path.dirname(fileURLToPath(import.meta.url)); -class CodeNarcCaller { - "use strict"; - +export class CodeNarcCaller { args = []; options; codenarcArgs; @@ -235,14 +238,11 @@ class CodeNarcCaller { reason = "It seems node.js has not been found on your computer. Please install a recent node.js: https://nodejs.org/en/download/\nIf node is already installed, make sure your PATH contains node installation folder: https://love2dev.com/blog/node-is-not-recognized-as-an-internal-or-external-command/"; } else { - await new Promise((resolve) => { - require("find-java-home")((err) => { - if (err) { - reason = - "Java is required to run npm-groovy-lint, as CodeNarc is written in Java/Groovy. Please install Java (version 8 minimum) https://www.java.com/download"; - } - resolve(); - }); + await findJavaHome({ allowJre: true }, (err) => { + if (err) { + reason = + "Java is required to run npm-groovy-lint, as CodeNarc is written in Java/Groovy. Please install Java (version 8 minimum) https://www.java.com/download"; + } }); } return { @@ -445,5 +445,3 @@ class CodeNarcCaller { } } } - -module.exports = CodeNarcCaller; diff --git a/lib/codenarc-factory.js b/lib/codenarc-factory.js index f2dae88c..114cf849 100644 --- a/lib/codenarc-factory.js +++ b/lib/codenarc-factory.js @@ -1,21 +1,21 @@ // Shared functions -"use strict"; - -const debug = require("debug")("npm-groovy-lint"); -const commondir = require("commondir"); -const fs = require("fs-extra"); -const os = require("os"); -const path = require("path"); -const { getConfigFileName } = require("./config.js"); -const { collectDisabledBlocks, isFilteredError } = require("./filter.js"); -const { getNpmGroovyLintRules } = require("./groovy-lint-rules.js"); -const { evaluateRange, evaluateRangeFromLine, evaluateVariables, getSourceLines, normalizeNewLines } = require("./utils.js"); +import Debug from "debug"; +const debug = Debug("npm-groovy-lint"); +import commondir from "commondir"; +import fs from "fs-extra"; +import * as os from "os"; +import * as path from "path"; +import { getConfigFileName } from "./config.js"; +import { collectDisabledBlocks, isFilteredError } from "./filter.js"; +import { getNpmGroovyLintRules } from "./groovy-lint-rules.js"; +import { evaluateRange, evaluateRangeFromLine, evaluateVariables, getSourceLines, normalizeNewLines } from "./utils.js"; +import { fileURLToPath } from "url"; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); //////////////////////////// // Build codenarc options // //////////////////////////// -const npmGroovyLintRules = getNpmGroovyLintRules(); const CODENARC_TMP_FILENAME_BASE = "codeNarcTmpDir_"; const CODENARC_WWW_BASE = "https://codenarc.github.io/CodeNarc"; @@ -215,6 +215,7 @@ async function parseCodeNarcResult(options, codeNarcBaseDir, codeNarcJsonResult, }, }; } + const npmGroovyLintRules = await getNpmGroovyLintRules(); const result = { summary: {} }; // Parse main result @@ -518,4 +519,4 @@ function directoryExists(resolvedPath) { } } -module.exports = { prepareCodeNarcCall, parseCodeNarcResult }; +export { prepareCodeNarcCall, parseCodeNarcResult }; diff --git a/lib/config.js b/lib/config.js index 0fb1e2d3..064876c0 100644 --- a/lib/config.js +++ b/lib/config.js @@ -1,11 +1,13 @@ // Configuration file management -"use strict"; -const debug = require("debug")("npm-groovy-lint"); -const fse = require("fs-extra"); -const importFresh = require("import-fresh"); -const path = require("path"); -const stripComments = require("strip-json-comments"); +import Debug from "debug"; +const debug = Debug("npm-groovy-lint"); +import fs from "fs-extra"; +import importFresh from "import-fresh"; +import * as path from "path"; +import stripJsonComments from "strip-json-comments"; +import { fileURLToPath } from "url"; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); const defaultConfigLintFileName = ".groovylintrc-recommended.json"; const allConfigLintFileName = ".groovylintrc-all.json"; @@ -117,7 +119,7 @@ async function getConfigFileName(startPathOrFile, sourcefilepath, fileNames = co // Find one of the config file formats are the root of the linted file (if source is sent with sourcefilepath) if ([".", process.cwd()].includes(startPathOrFile) && sourcefilepath) { try { - const stat = await fse.lstat(sourcefilepath); + const stat = await fs.lstat(sourcefilepath); const dir = stat.isDirectory() ? sourcefilepath : path.parse(sourcefilepath).dir; configFilePath = await findConfigInPath(dir, fileNames); } catch (e) { @@ -127,7 +129,7 @@ async function getConfigFileName(startPathOrFile, sourcefilepath, fileNames = co // Find one of the config file formats at the root of the project or at upper directory levels if (configFilePath == null) { try { - const stat = await fse.lstat(startPathOrFile); + const stat = await fs.lstat(startPathOrFile); const dir = stat.isDirectory ? startPathOrFile : path.parse(startPathOrFile).dir; configFilePath = await findConfigInPath(dir, fileNames); } catch (e) { @@ -154,7 +156,7 @@ async function getConfigFileName(startPathOrFile, sourcefilepath, fileNames = co async function findConfigInPath(directoryPath, configFilenamesIn) { for (const filename of configFilenamesIn) { const filePath = path.join(directoryPath, filename); - if (await fse.exists(filePath)) { + if (await fs.exists(filePath)) { if (filename === "package.json") { try { await loadPackageJSONConfigFile(filePath); @@ -218,8 +220,8 @@ async function loadJSConfigFile(filePath) { // JSON format async function loadJSONConfigFile(filePath) { try { - const fileContent = await readFile(filePath); - return JSON.parse(stripComments(fileContent)); + const fileContent = await fs.readFile(filePath); + return JSON.parse(stripJsonComments(fileContent.toString())); } catch (e) { debug(`Error reading JSON file: ${filePath}`); e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; @@ -235,7 +237,7 @@ async function loadJSONConfigFile(filePath) { // YAML format async function loadYAMLConfigFile(filePath) { // lazy load YAML to improve performance when not used - const yaml = require("js-yaml"); + const yaml = await import("js-yaml"); try { // empty YAML file can be null, so always use @@ -265,7 +267,7 @@ async function loadPackageJSONConfigFile(filePath) { // Read file async function readFile(filePath) { - const fileContent = await fse.readFile(filePath, "utf8"); + const fileContent = await fs.readFile(filePath, "utf8"); return fileContent.replace(/^\ufeff/u, ""); } @@ -279,4 +281,4 @@ async function shortenRuleNames(rules) { return shortenedRules; } -module.exports = { NPM_GROOVY_LINT_CONSTANTS, loadConfig, getConfigFileName, overriddenRules }; +export { NPM_GROOVY_LINT_CONSTANTS, loadConfig, getConfigFileName, overriddenRules }; diff --git a/lib/filter.js b/lib/filter.js index a400949b..b2c0023c 100644 --- a/lib/filter.js +++ b/lib/filter.js @@ -1,5 +1,4 @@ // Filter errors -"use strict"; // Parse source to list parts where errors must be ignored function collectDisabledBlocks(allLines) { @@ -91,4 +90,4 @@ function cleanFromCommentMarks(str) { return str.replace("/*", "").replace("//", "").replace("*/", "").trim(); } -module.exports = { collectDisabledBlocks, isFilteredError }; +export { collectDisabledBlocks, isFilteredError }; diff --git a/lib/groovy-lint-fix.js b/lib/groovy-lint-fix.js index 73aaaad7..03eb9ad6 100644 --- a/lib/groovy-lint-fix.js +++ b/lib/groovy-lint-fix.js @@ -1,15 +1,14 @@ // Imports -const fse = require("fs-extra"); -const cliProgress = require("cli-progress"); -const debug = require("debug")("npm-groovy-lint"); -const trace = require("debug")("npm-groovy-lint-trace"); -const os = require("os"); -const { getNpmGroovyLintRules, getFormattingRulesToAlwaysRun } = require("./groovy-lint-rules.js"); -const { evaluateVariables, getSourceLines } = require("./utils.js"); - -class NpmGroovyLintFix { - "use strict"; +import fs from "fs-extra"; +import * as cliProgress from "cli-progress"; +import Debug from "debug"; +const debug = Debug("npm-groovy-lint"); +const trace = Debug("npm-groovy-lint-trace"); +import * as os from "os"; +import { getNpmGroovyLintRules, getFormattingRulesToAlwaysRun } from "./groovy-lint-rules.js"; +import { evaluateVariables, getSourceLines } from "./utils.js"; +export class NpmGroovyLintFix { options = {}; updatedLintResult; @@ -30,7 +29,6 @@ class NpmGroovyLintFix { this.options = optionsIn; this.verbose = optionsIn.verbose || false; // Load available fix rules - this.npmGroovyLintRules = this.options.groovyLintRulesOverride ? require(this.options.groovyLintRulesOverride) : getNpmGroovyLintRules(); if (this.options.fixrules && this.options.fixrules !== "all") { this.fixRules = this.options.fixrules.split(","); } @@ -41,6 +39,8 @@ class NpmGroovyLintFix { // Fix errors using codenarc result and groovy lint rules async run(optns = { errorIds: null, propagate: false }) { debug(`<<<<<< NpmGroovyLintFix.run START >>>>>>`); + const npmGroovyLintRules = await getNpmGroovyLintRules(); + this.npmGroovyLintRules = this.options.groovyLintRulesOverride ? await import(this.options.groovyLintRulesOverride) : npmGroovyLintRules; // Start progress bar this.bar = new cliProgress.SingleBar( { @@ -217,7 +217,7 @@ class NpmGroovyLintFix { this.updatedLintResult.files[fileNm].updatedSource = newSources; // Write new file content if it has been updated if (this.options.save && fixedInFileNb > 0) { - fse.writeFileSync(fileNm, newSources); + fs.writeFileSync(fileNm, newSources); } }), ); @@ -351,5 +351,3 @@ class NpmGroovyLintFix { }); } } - -module.exports = NpmGroovyLintFix; diff --git a/lib/groovy-lint-rules.js b/lib/groovy-lint-rules.js index 58872473..570a0852 100644 --- a/lib/groovy-lint-rules.js +++ b/lib/groovy-lint-rules.js @@ -83,13 +83,14 @@ str = "lelamanul" ] } - module.exports = { rule } + export default { rule } */ -"use strict"; - -const fse = require("fs-extra"); +import fs from "fs-extra"; +const { readdirSync } = fs; +import * as path from "path"; +import { fileURLToPath } from "url"; // If you add a new global rule with a fix function, it's very important to think about their order. // Rules modifying the number of lines must arrive last ! @@ -158,18 +159,19 @@ const rulesFixPriorityOrder = [ // Non-CodeNarc formatting fix rules (existing only in npm-groovy-lint) must be run always const formatRulesToAlwaysRun = ["IndentationClosingBraces", "IndentationComments"]; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); const RULES_FOLDER = __dirname + "/rules"; -function getNpmGroovyLintRules(optns = { loadTests: false }) { - const ruleFiles = fse.readdirSync(RULES_FOLDER); +export async function getNpmGroovyLintRules(optns = { loadTests: false }) { + const ruleFiles = readdirSync(RULES_FOLDER); const npmGroovyLintRules = {}; for (const file of ruleFiles) { const ruleName = file.replace(".js", ""); // Remove require cache if tests must be returned (other calls delete them in the cache) if (optns && optns.loadTests === true) { - delete require.cache[require.resolve(`${RULES_FOLDER}/${file}`)]; + // delete require.cache[require.resolve(`${RULES_FOLDER}/${file}`)]; Not ESM compliant } - const { rule } = require(`${RULES_FOLDER}/${file}`); + const { rule } = await import("./rules/" + file); if (rule.disabled) { continue; } @@ -187,8 +189,6 @@ function getNpmGroovyLintRules(optns = { loadTests: false }) { return npmGroovyLintRules; } -function getFormattingRulesToAlwaysRun() { +export function getFormattingRulesToAlwaysRun() { return formatRulesToAlwaysRun; } - -module.exports = { getNpmGroovyLintRules, getFormattingRulesToAlwaysRun }; diff --git a/lib/groovy-lint.js b/lib/groovy-lint.js index 4d4061c3..80100090 100644 --- a/lib/groovy-lint.js +++ b/lib/groovy-lint.js @@ -1,22 +1,21 @@ // Imports -const debug = require("debug")("npm-groovy-lint"); -const trace = require("debug")("npm-groovy-lint-trace"); -const fs = require("fs-extra"); -const os = require("os"); -const path = require("path"); -const performance = require("perf_hooks").performance; - -const NpmGroovyLintFix = require("./groovy-lint-fix"); -const CodeNarcCaller = require("./codenarc-caller"); -const { prepareCodeNarcCall, parseCodeNarcResult } = require("./codenarc-factory"); -const { NPM_GROOVY_LINT_CONSTANTS, loadConfig, getConfigFileName } = require("./config.js"); -const optionsDefinition = require("./options"); -const { computeStats, processOutput } = require("./output.js"); -const { getNpmGroovyLintVersion, getSourceLines, isErrorInLogLevelScope } = require("./utils"); +import Debug from "debug"; +const debug = Debug("npm-groovy-lint"); +const trace = Debug("npm-groovy-lint-trace"); +import fs from "fs-extra"; +import * as os from "os"; +import * as path from "path"; +import { performance } from "node:perf_hooks"; +import { NpmGroovyLintFix } from "./groovy-lint-fix.js"; + +import { CodeNarcCaller } from "./codenarc-caller.js"; +import { prepareCodeNarcCall, parseCodeNarcResult } from "./codenarc-factory.js"; +import { NPM_GROOVY_LINT_CONSTANTS, loadConfig, getConfigFileName } from "./config.js"; +import { optionsDefinition } from "./options.js"; +import { computeStats, processOutput } from "./output.js"; +import { getNpmGroovyLintVersion, getSourceLines, isErrorInLogLevelScope } from "./utils.js"; class NpmGroovyLint { - "use strict"; - options = {}; // NpmGroovyLint options args = []; // Command line arguments @@ -530,4 +529,4 @@ class NpmGroovyLint { } } -module.exports = NpmGroovyLint; +export default NpmGroovyLint; diff --git a/lib/index.js b/lib/index.js index 2a98ba30..4745839c 100755 --- a/lib/index.js +++ b/lib/index.js @@ -1,7 +1,7 @@ #! /usr/bin/env node -"use strict"; -const NpmGroovyLint = require("./groovy-lint.js"); +import NpmGroovyLint from "./groovy-lint.js"; +import { pathToFileURL } from 'url' // Create linter/formatter/fixer with arguments const linter = new NpmGroovyLint(process.argv, { origin: "index" }); @@ -15,7 +15,7 @@ const linter = new NpmGroovyLint(process.argv, { origin: "index" }); console.error("Unexpected error: " + err.message + "\n" + err.stack); process.exitCode = 2; // Quit if called by CLI and not as a module - if (require.main === module) { + if (import.meta.url === pathToFileURL(process.argv[1]).href) { process.exit(); } } diff --git a/lib/options.js b/lib/options.js index 0346f96c..dc388114 100644 --- a/lib/options.js +++ b/lib/options.js @@ -3,13 +3,11 @@ * @author Nicolas Vuillamy */ -"use strict"; - //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ -const optionator = require("optionator"); +import optionator from "optionator"; const defaultServerPort = process.env.SERVER_PORT ? process.env.SERVER_PORT : "7484"; @@ -17,7 +15,7 @@ const defaultServerPort = process.env.SERVER_PORT ? process.env.SERVER_PORT : "7 // Initialization and Public Interface //------------------------------------------------------------------------------ -let options = optionator({ +export const optionsDefinition = optionator({ prepend: "npm-groovy-lint [options]", defaults: { concatRepeatedArrays: true, @@ -286,11 +284,4 @@ let options = optionator({ ], }); -options.defaultServerPort = defaultServerPort; - -// Export: -// - parse(args) -// - generateHelp() -// - generateHelpForOption(optionName) -// - defaultServerPort -module.exports = options; +optionsDefinition.defaultServerPort = defaultServerPort; diff --git a/lib/output.js b/lib/output.js index e398db13..7b161fb9 100644 --- a/lib/output.js +++ b/lib/output.js @@ -1,9 +1,9 @@ // Output management -const c = require("ansi-colors"); -const fse = require("fs-extra"); -const { SarifBuilder, SarifRunBuilder, SarifResultBuilder, SarifRuleBuilder } = require("node-sarif-builder"); -const path = require("path"); -const { isErrorInLogLevelScope, getNpmGroovyLintVersion } = require("./utils"); +import ansiColors from "ansi-colors"; +import fs from "fs-extra"; +import { SarifBuilder, SarifRunBuilder, SarifResultBuilder, SarifRuleBuilder } from "node-sarif-builder"; +import * as path from "path"; +import { isErrorInLogLevelScope, getNpmGroovyLintVersion } from "./utils.js"; // Compute statistics for output function computeStats(lintResult) { @@ -103,12 +103,12 @@ async function processOutput(outputType, output, lintResult, options, fixer = nu // Disable colors if output results in text file or no output result if (output.includes(".txt") || output === "none") { // Disable ansi colors if output in txt file - c.enabled = false; + ansiColors.enabled = false; } // Errors for (const fileNm of Object.keys(lintResult.files)) { const fileErrors = lintResult.files[fileNm].errors; - let fileOutputString = c.underline(fileNm) + "\n"; + let fileOutputString = ansiColors.underline(fileNm) + "\n"; let showFileInOutput = false; for (const err of fileErrors) { if (!isErrorInLogLevelScope(err.severity, options.loglevel)) { @@ -141,7 +141,7 @@ async function processOutput(outputType, output, lintResult, options, fixer = nu " " + err.line.toString().padEnd(4, " ") + " " + - c[color](err.severity.padEnd(7, " ")) + + ansiColors[color](err.severity.padEnd(7, " ")) + " " + err.msg + " " + @@ -153,7 +153,7 @@ async function processOutput(outputType, output, lintResult, options, fixer = nu outputString += fileOutputString; } } - outputString += "\nnpm-groovy-lint results in " + c.bold(lintResult.summary.totalFilesLinted) + " linted files:"; + outputString += "\nnpm-groovy-lint results in " + ansiColors.bold(lintResult.summary.totalFilesLinted) + " linted files:"; // Summary table const errorTableLine = { @@ -188,7 +188,7 @@ async function processOutput(outputType, output, lintResult, options, fixer = nu // Output text log in file if (output.endsWith(".txt")) { const fullFileContent = outputString; - fse.writeFileSync(output, fullFileContent); + fs.writeFileSync(output, fullFileContent); console.table(summaryTable, fixer ? ["Severity", "Total found", "Total fixed", "Total remaining"] : ["Severity", "Total found"]); const absolutePath = path.resolve(".", output); console.info("GroovyLint: Logged results in file " + absolutePath); @@ -203,7 +203,7 @@ async function processOutput(outputType, output, lintResult, options, fixer = nu // Output log if (output.endsWith(".json")) { const fullFileContent = JSON.stringify(lintResult, null, 2); - fse.writeFileSync(output, fullFileContent); + fs.writeFileSync(output, fullFileContent); const absolutePath = path.resolve(".", output); console.info("GroovyLint: Logged results in file " + absolutePath); } else { @@ -216,7 +216,7 @@ async function processOutput(outputType, output, lintResult, options, fixer = nu const sarifJsonString = buildSarifResult(lintResult); // SARIF file if (output.endsWith(".sarif")) { - fse.writeFileSync(output, sarifJsonString); + fs.writeFileSync(output, sarifJsonString); const absolutePath = path.resolve(".", output); outputString = "GroovyLint: Logged SARIF results in file " + absolutePath; console.info(outputString); @@ -291,4 +291,4 @@ function fixCol(val) { return val === 0 ? 1 : val + 1; } -module.exports = { computeStats, processOutput }; +export { computeStats, processOutput }; diff --git a/lib/rules/AssignmentInConditional.js b/lib/rules/AssignmentInConditional.js index bbc9ce4b..2f476259 100644 --- a/lib/rules/AssignmentInConditional.js +++ b/lib/rules/AssignmentInConditional.js @@ -1,6 +1,6 @@ // Assignment in condition -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -53,4 +53,4 @@ while (value == true && value != false) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/BlankLineBeforePackage.js b/lib/rules/BlankLineBeforePackage.js index 3f778818..15e23c88 100644 --- a/lib/rules/BlankLineBeforePackage.js +++ b/lib/rules/BlankLineBeforePackage.js @@ -1,6 +1,6 @@ // Blank line before package -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -74,4 +74,4 @@ class BuildEnv implements Serializable { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/BlockEndsWithBlankLine.js b/lib/rules/BlockEndsWithBlankLine.js index 2f5cb956..cabca42e 100644 --- a/lib/rules/BlockEndsWithBlankLine.js +++ b/lib/rules/BlockEndsWithBlankLine.js @@ -1,6 +1,6 @@ // Unused import -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -43,4 +43,4 @@ if (false) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/BlockStartsWithBlankLine.js b/lib/rules/BlockStartsWithBlankLine.js index 2b7f8181..5a30353c 100644 --- a/lib/rules/BlockStartsWithBlankLine.js +++ b/lib/rules/BlockStartsWithBlankLine.js @@ -1,6 +1,6 @@ // Unused import -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -43,4 +43,4 @@ if (false) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/BracesForClass.js b/lib/rules/BracesForClass.js index 5d2f06ee..42c10fe4 100644 --- a/lib/rules/BracesForClass.js +++ b/lib/rules/BracesForClass.js @@ -1,6 +1,6 @@ // Braces for class -const { moveOpeningBracket, findRangeBetweenStrings } = require("../utils"); +import { moveOpeningBracket, findRangeBetweenStrings } from "../utils.js"; const rule = { scope: "file", @@ -47,4 +47,4 @@ public class lelamanul { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/BracesForForLoop.js b/lib/rules/BracesForForLoop.js index d0ade554..c1b71bf7 100644 --- a/lib/rules/BracesForForLoop.js +++ b/lib/rules/BracesForForLoop.js @@ -1,6 +1,6 @@ // Braces for for loop -const { getVariable, moveOpeningBracket, findRangeBetweenStrings } = require("../utils"); +import { getVariable, moveOpeningBracket, findRangeBetweenStrings } from "../utils.js"; const rule = { scope: "file", @@ -63,4 +63,4 @@ for (int i = 0; i < toto.length ; i++) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/BracesForIfElse.js b/lib/rules/BracesForIfElse.js index 04f97c98..e5f7963a 100644 --- a/lib/rules/BracesForIfElse.js +++ b/lib/rules/BracesForIfElse.js @@ -1,6 +1,6 @@ // Braces for if else -const { moveOpeningBracket, findRangeBetweenStrings } = require("../utils"); +import { moveOpeningBracket, findRangeBetweenStrings } from "../utils.js"; const rule = { scope: "file", @@ -64,4 +64,4 @@ if (true && ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/BracesForMethod.js b/lib/rules/BracesForMethod.js index d075a7bb..f2a0a215 100644 --- a/lib/rules/BracesForMethod.js +++ b/lib/rules/BracesForMethod.js @@ -1,6 +1,6 @@ // Braces for method -const { moveOpeningBracket, findRangeBetweenStrings, getVariable } = require("../utils"); +import { moveOpeningBracket, findRangeBetweenStrings, getVariable } from "../utils.js"; const rule = { scope: "file", @@ -108,4 +108,4 @@ def someMethodName (String toto, ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/BracesForTryCatchFinally.js b/lib/rules/BracesForTryCatchFinally.js index c3c20747..4f7dffaa 100644 --- a/lib/rules/BracesForTryCatchFinally.js +++ b/lib/rules/BracesForTryCatchFinally.js @@ -1,6 +1,6 @@ // Braces for try catch finally -const { moveOpeningBracket, findRangeBetweenStrings } = require("../utils"); +import { moveOpeningBracket, findRangeBetweenStrings } from "../utils.js"; const rule = { scope: "file", @@ -43,4 +43,4 @@ try { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/CatchException.js b/lib/rules/CatchException.js index d25c7dcf..fb0fd863 100644 --- a/lib/rules/CatchException.js +++ b/lib/rules/CatchException.js @@ -1,5 +1,5 @@ // Exception type must not be used -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -10,4 +10,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/ClassEndsWithBlankLine.js b/lib/rules/ClassEndsWithBlankLine.js index 2aaaf569..31e04583 100644 --- a/lib/rules/ClassEndsWithBlankLine.js +++ b/lib/rules/ClassEndsWithBlankLine.js @@ -1,6 +1,6 @@ // Unused import -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -42,4 +42,4 @@ class NullResultsProcessor implements ResultsProcessor { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/ClassStartsWithBlankLine.js b/lib/rules/ClassStartsWithBlankLine.js index b6bac224..8cb815a9 100644 --- a/lib/rules/ClassStartsWithBlankLine.js +++ b/lib/rules/ClassStartsWithBlankLine.js @@ -1,6 +1,6 @@ // Unused import -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -42,4 +42,4 @@ class NullResultsProcessor implements ResultsProcessor { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/ClosingBraceNotAlone.js b/lib/rules/ClosingBraceNotAlone.js index 53d8bd69..eef632c5 100644 --- a/lib/rules/ClosingBraceNotAlone.js +++ b/lib/rules/ClosingBraceNotAlone.js @@ -47,4 +47,4 @@ if (a == 1) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/ConsecutiveBlankLines.js b/lib/rules/ConsecutiveBlankLines.js index c80c89b6..736cb973 100644 --- a/lib/rules/ConsecutiveBlankLines.js +++ b/lib/rules/ConsecutiveBlankLines.js @@ -1,6 +1,6 @@ // Consecutive blank lines -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -57,4 +57,4 @@ x = 1 ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/DuplicateImport.js b/lib/rules/DuplicateImport.js index bf9d50e6..6c1154bd 100644 --- a/lib/rules/DuplicateImport.js +++ b/lib/rules/DuplicateImport.js @@ -1,6 +1,6 @@ // Duplicate import -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -63,4 +63,4 @@ class Gros { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/DuplicateNumberLiteral.js b/lib/rules/DuplicateNumberLiteral.js index 85d08a2f..eb15d1be 100644 --- a/lib/rules/DuplicateNumberLiteral.js +++ b/lib/rules/DuplicateNumberLiteral.js @@ -1,6 +1,6 @@ // Duplicate number literal -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -18,4 +18,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/DuplicateStringLiteral.js b/lib/rules/DuplicateStringLiteral.js index 1fda95a9..bbd1755f 100644 --- a/lib/rules/DuplicateStringLiteral.js +++ b/lib/rules/DuplicateStringLiteral.js @@ -1,6 +1,6 @@ // Duplicate string literal -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -18,4 +18,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/ElseBlockBraces.js b/lib/rules/ElseBlockBraces.js index 82eeb7c9..62b87b62 100644 --- a/lib/rules/ElseBlockBraces.js +++ b/lib/rules/ElseBlockBraces.js @@ -1,5 +1,5 @@ // Missing else braces -const { containsOtherThan, getStringRangeMultiline, getVariable, isValidCodeLine } = require("../utils"); +import { containsOtherThan, getStringRangeMultiline, getVariable, isValidCodeLine } from "../utils.js"; const rule = { scope: "file", @@ -157,4 +157,4 @@ static getFileExtension(fileName) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/ExplicitArrayListInstantiation.js b/lib/rules/ExplicitArrayListInstantiation.js index 7740d7f9..c43f408d 100644 --- a/lib/rules/ExplicitArrayListInstantiation.js +++ b/lib/rules/ExplicitArrayListInstantiation.js @@ -27,4 +27,4 @@ List commandArray=[] ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/ExplicitLinkedListInstantiation.js b/lib/rules/ExplicitLinkedListInstantiation.js index 81621a88..fe6bc0f0 100644 --- a/lib/rules/ExplicitLinkedListInstantiation.js +++ b/lib/rules/ExplicitLinkedListInstantiation.js @@ -27,4 +27,4 @@ List printList=[] as Queue ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/FileEndsWithoutNewline.js b/lib/rules/FileEndsWithoutNewline.js index 7553775f..9fef4c93 100644 --- a/lib/rules/FileEndsWithoutNewline.js +++ b/lib/rules/FileEndsWithoutNewline.js @@ -1,5 +1,5 @@ // File ends without new line -const os = require("os"); +import * as os from "os"; const rule = { scope: "file", @@ -24,4 +24,4 @@ def b = 2 ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/GStringExpressionWithinString.js b/lib/rules/GStringExpressionWithinString.js index 52f250a1..930178e8 100644 --- a/lib/rules/GStringExpressionWithinString.js +++ b/lib/rules/GStringExpressionWithinString.js @@ -20,4 +20,4 @@ def someString = '\${SCRIPT,template=\\"mail_template_robot_results.groovy\\"}' ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/IfStatementBraces.js b/lib/rules/IfStatementBraces.js index c8d8c7aa..6fcfff5d 100644 --- a/lib/rules/IfStatementBraces.js +++ b/lib/rules/IfStatementBraces.js @@ -3,7 +3,7 @@ // nvuillam: Fix not always working, especially when embedded missing If statements ... // let's let people correct that manually for now :) -const { getOutOfBracesStrings, getStringRange, getVariable, isValidCodeLine } = require("../utils"); +import { getOutOfBracesStrings, getStringRange, getVariable, isValidCodeLine } from "../utils.js"; const rule = { scope: "file", @@ -164,4 +164,4 @@ if (a == 1 && ( x === 2) && something()) whatever() ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/Indentation.js b/lib/rules/Indentation.js index c91fbc04..b7127d41 100644 --- a/lib/rules/Indentation.js +++ b/lib/rules/Indentation.js @@ -1,7 +1,7 @@ // Indentation // Warning CodeNarc does not like tabs, better replace them by spaces ... -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { triggers: ["IndentationClosingBraces", "IndentationComments"], @@ -109,4 +109,4 @@ docker.withRegistry("https://"+ envVars.GetDockerRegistry(), envVars.GetDockerRe ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/IndentationClosingBraces.js b/lib/rules/IndentationClosingBraces.js index 1d14eb0a..8dd261ac 100644 --- a/lib/rules/IndentationClosingBraces.js +++ b/lib/rules/IndentationClosingBraces.js @@ -1,4 +1,4 @@ -const { containsExceptInsideString } = require("../utils"); +import { containsExceptInsideString } from "../utils.js"; // Indentation closing braces const rule = { @@ -102,4 +102,4 @@ docker.withRegistry("https://"+ envVars.GetDockerRegistry(), envVars.GetDockerRe ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/IndentationComments.js b/lib/rules/IndentationComments.js index 996f90f7..d0828009 100644 --- a/lib/rules/IndentationComments.js +++ b/lib/rules/IndentationComments.js @@ -45,4 +45,4 @@ const rule = { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/InsecureRandom.js b/lib/rules/InsecureRandom.js index a006216c..678c8596 100644 --- a/lib/rules/InsecureRandom.js +++ b/lib/rules/InsecureRandom.js @@ -1,5 +1,5 @@ // Insecure use of Random -const { addImport, getVariable, getVariableRange } = require("../utils"); +import { addImport, getVariable, getVariableRange } from "../utils.js"; const rule = { scope: "file", @@ -167,4 +167,4 @@ def r5 = "lelamanul"+new SecureRandom().nextDouble()+"_yeah_"+new SecureRandom() ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/JavaIoPackageAccess.js b/lib/rules/JavaIoPackageAccess.js index acf24296..9b2f5432 100644 --- a/lib/rules/JavaIoPackageAccess.js +++ b/lib/rules/JavaIoPackageAccess.js @@ -1,6 +1,6 @@ // No use of Java.io classes -const { getLastVariableRange } = require("../utils"); +import { getLastVariableRange } from "../utils.js"; //NV: TODO: finalise for when there is several occurrences of the string in the same line const rule = { @@ -20,4 +20,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/MethodCount.js b/lib/rules/MethodCount.js index e5f81ca6..d93bc7e4 100644 --- a/lib/rules/MethodCount.js +++ b/lib/rules/MethodCount.js @@ -1,6 +1,6 @@ // Too many methods in a class -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -18,4 +18,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/MethodParameterTypeRequired.js b/lib/rules/MethodParameterTypeRequired.js index 158b9981..60cd7b6e 100644 --- a/lib/rules/MethodParameterTypeRequired.js +++ b/lib/rules/MethodParameterTypeRequired.js @@ -1,6 +1,6 @@ // Too many methods in a class -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -18,4 +18,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/MethodReturnTypeRequired.js b/lib/rules/MethodReturnTypeRequired.js index a81bce14..38b81b31 100644 --- a/lib/rules/MethodReturnTypeRequired.js +++ b/lib/rules/MethodReturnTypeRequired.js @@ -1,6 +1,6 @@ // Too many methods in a class -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -18,4 +18,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/MisorderedStaticImports.js b/lib/rules/MisorderedStaticImports.js index 8c91521b..d30fa62e 100644 --- a/lib/rules/MisorderedStaticImports.js +++ b/lib/rules/MisorderedStaticImports.js @@ -234,4 +234,4 @@ import after.all.does.it.work ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/MissingBlankLineAfterImports.js b/lib/rules/MissingBlankLineAfterImports.js index 3e311868..429081ae 100644 --- a/lib/rules/MissingBlankLineAfterImports.js +++ b/lib/rules/MissingBlankLineAfterImports.js @@ -1,6 +1,6 @@ // Missing blank lines after import -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -33,4 +33,4 @@ def a = 1 ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/MissingBlankLineAfterPackage.js b/lib/rules/MissingBlankLineAfterPackage.js index 8fe79398..3f6f165e 100644 --- a/lib/rules/MissingBlankLineAfterPackage.js +++ b/lib/rules/MissingBlankLineAfterPackage.js @@ -1,6 +1,6 @@ // Missing blank lines after package -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -33,4 +33,4 @@ import g.eeee.f.g.Iiii ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/NoDef.js b/lib/rules/NoDef.js index 3ef7b269..aac51db5 100644 --- a/lib/rules/NoDef.js +++ b/lib/rules/NoDef.js @@ -1,6 +1,6 @@ // No use of def -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -11,4 +11,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/NoJavaUtilDate.js b/lib/rules/NoJavaUtilDate.js index 37578e78..393dd1a5 100644 --- a/lib/rules/NoJavaUtilDate.js +++ b/lib/rules/NoJavaUtilDate.js @@ -1,6 +1,6 @@ // No use of Java.util.date -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -11,4 +11,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/NoTabCharacter.js b/lib/rules/NoTabCharacter.js index 80ba62c1..e13e7d51 100644 --- a/lib/rules/NoTabCharacter.js +++ b/lib/rules/NoTabCharacter.js @@ -1,6 +1,6 @@ // No tab character -const { getIndentLength } = require("../utils"); +import { getIndentLength } from "../utils.js"; const rule = { scope: "file", @@ -36,4 +36,4 @@ try { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SimpleDateFormatMissingLocale.js b/lib/rules/SimpleDateFormatMissingLocale.js index 43e37e98..920dcb50 100644 --- a/lib/rules/SimpleDateFormatMissingLocale.js +++ b/lib/rules/SimpleDateFormatMissingLocale.js @@ -1,6 +1,6 @@ // Simple Date Format missing locale -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -11,4 +11,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAfterCatch.js b/lib/rules/SpaceAfterCatch.js index 4dac56ef..c2b74724 100644 --- a/lib/rules/SpaceAfterCatch.js +++ b/lib/rules/SpaceAfterCatch.js @@ -1,6 +1,6 @@ // Space after catch -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -31,4 +31,4 @@ try { } catch ( ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAfterComma.js b/lib/rules/SpaceAfterComma.js index 156bb630..e9120d47 100644 --- a/lib/rules/SpaceAfterComma.js +++ b/lib/rules/SpaceAfterComma.js @@ -1,6 +1,6 @@ // Add space after a comma -const { getStringRange, addSpaceAfterChar } = require("../utils"); +import { getStringRange, addSpaceAfterChar } from "../utils.js"; const rule = { range: { @@ -40,4 +40,4 @@ if (true) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAfterFor.js b/lib/rules/SpaceAfterFor.js index c13304b9..2c3b635f 100644 --- a/lib/rules/SpaceAfterFor.js +++ b/lib/rules/SpaceAfterFor.js @@ -1,5 +1,5 @@ // Space after for -const { getStringRange, addSpaceAfterChar } = require("../utils"); +import { getStringRange, addSpaceAfterChar } from "../utils.js"; const rule = { range: { @@ -37,4 +37,4 @@ for (child in this.children) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAfterIf.js b/lib/rules/SpaceAfterIf.js index e4e98ecd..3ebdb43c 100644 --- a/lib/rules/SpaceAfterIf.js +++ b/lib/rules/SpaceAfterIf.js @@ -1,6 +1,6 @@ // Space after if -const { getStringRange, addSpaceAfterChar } = require("../utils"); +import { getStringRange, addSpaceAfterChar } from "../utils.js"; const rule = { range: { @@ -56,4 +56,4 @@ if (lifetime) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAfterMethodCallName.js b/lib/rules/SpaceAfterMethodCallName.js index ff6342bf..f16d0d45 100644 --- a/lib/rules/SpaceAfterMethodCallName.js +++ b/lib/rules/SpaceAfterMethodCallName.js @@ -1,6 +1,6 @@ // Space after method call name -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -27,4 +27,4 @@ Utils.printlnLog('-----') ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAfterOpeningBrace.js b/lib/rules/SpaceAfterOpeningBrace.js index 578f3640..7aa67b6a 100644 --- a/lib/rules/SpaceAfterOpeningBrace.js +++ b/lib/rules/SpaceAfterOpeningBrace.js @@ -1,6 +1,6 @@ // Space after opening brace -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -50,4 +50,4 @@ class MyOtherClass extends AbstractClass { int count } ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAfterSemicolon.js b/lib/rules/SpaceAfterSemicolon.js index edfeba3a..268a0f6c 100644 --- a/lib/rules/SpaceAfterSemicolon.js +++ b/lib/rules/SpaceAfterSemicolon.js @@ -1,6 +1,6 @@ // Add space after a semicolon -const { getStringRange, addSpaceAfterChar } = require("../utils"); +import { getStringRange, addSpaceAfterChar } from "../utils.js"; const rule = { range: { @@ -28,4 +28,4 @@ for (int i=0; i * 10; i++) { } ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAfterSwitch.js b/lib/rules/SpaceAfterSwitch.js index 0320b395..ae023392 100644 --- a/lib/rules/SpaceAfterSwitch.js +++ b/lib/rules/SpaceAfterSwitch.js @@ -1,6 +1,6 @@ // Space after switch -const { getStringRange, addSpaceAfterChar } = require("../utils"); +import { getStringRange, addSpaceAfterChar } from "../utils.js"; const rule = { range: { @@ -46,4 +46,4 @@ if (a == 0) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAfterWhile.js b/lib/rules/SpaceAfterWhile.js index 03caa31d..e1678426 100644 --- a/lib/rules/SpaceAfterWhile.js +++ b/lib/rules/SpaceAfterWhile.js @@ -1,6 +1,6 @@ // Space after while -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -35,4 +35,4 @@ while (count<5) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceAroundOperator.js b/lib/rules/SpaceAroundOperator.js index 6acb3bd7..bd3f4016 100644 --- a/lib/rules/SpaceAroundOperator.js +++ b/lib/rules/SpaceAroundOperator.js @@ -1,6 +1,6 @@ // Space around operators -const { getVariable, getVariableRange, addSpaceAroundChar } = require("../utils"); +import { getVariable, getVariableRange, addSpaceAroundChar } from "../utils.js"; const rule = { variables: [ @@ -131,4 +131,4 @@ image.inside { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceBeforeClosingBrace.js b/lib/rules/SpaceBeforeClosingBrace.js index 98ef4084..caf2b8f0 100644 --- a/lib/rules/SpaceBeforeClosingBrace.js +++ b/lib/rules/SpaceBeforeClosingBrace.js @@ -1,5 +1,5 @@ // Space before opening brace -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -31,4 +31,4 @@ process2.inputStream.eachLine { Utils.printlnLog it } ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceBeforeOpeningBrace.js b/lib/rules/SpaceBeforeOpeningBrace.js index 8b3273d7..e48d7df4 100644 --- a/lib/rules/SpaceBeforeOpeningBrace.js +++ b/lib/rules/SpaceBeforeOpeningBrace.js @@ -1,5 +1,5 @@ // Space before opening brace -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -63,4 +63,4 @@ pipeline { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SpaceInsideParentheses.js b/lib/rules/SpaceInsideParentheses.js index 87555ed7..7e2e114c 100644 --- a/lib/rules/SpaceInsideParentheses.js +++ b/lib/rules/SpaceInsideParentheses.js @@ -1,6 +1,6 @@ // No space between parenthesis -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { fix: { @@ -70,4 +70,4 @@ def res = uuuurf("yessss" ) ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/SystemExit.js b/lib/rules/SystemExit.js index 1a9bb178..c5253025 100644 --- a/lib/rules/SystemExit.js +++ b/lib/rules/SystemExit.js @@ -1,6 +1,6 @@ // System.exit forbidden -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -11,4 +11,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/TrailingWhitespace.js b/lib/rules/TrailingWhitespace.js index 068d30d9..8900d2aa 100644 --- a/lib/rules/TrailingWhitespace.js +++ b/lib/rules/TrailingWhitespace.js @@ -30,4 +30,4 @@ const rule = { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryDefInFieldDeclaration.js b/lib/rules/UnnecessaryDefInFieldDeclaration.js index 9b391286..e38615e1 100644 --- a/lib/rules/UnnecessaryDefInFieldDeclaration.js +++ b/lib/rules/UnnecessaryDefInFieldDeclaration.js @@ -1,6 +1,6 @@ // Unnecessary def in field declaration (static def) -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -43,4 +43,4 @@ class lelamanul { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryDefInMethodDeclaration.js b/lib/rules/UnnecessaryDefInMethodDeclaration.js index 31186360..bbd98265 100644 --- a/lib/rules/UnnecessaryDefInMethodDeclaration.js +++ b/lib/rules/UnnecessaryDefInMethodDeclaration.js @@ -1,6 +1,6 @@ // Unnecessary def in field declaration (static def) -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -31,4 +31,4 @@ static getCommandLogAsObj(String command) { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryDefInVariableDeclaration.js b/lib/rules/UnnecessaryDefInVariableDeclaration.js index c9a5fe38..490b6d05 100644 --- a/lib/rules/UnnecessaryDefInVariableDeclaration.js +++ b/lib/rules/UnnecessaryDefInVariableDeclaration.js @@ -1,6 +1,6 @@ // Unnecessary def in variable declaration -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -43,4 +43,4 @@ const rule = { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryDotClass.js b/lib/rules/UnnecessaryDotClass.js index d0aa033c..5a0ee83f 100644 --- a/lib/rules/UnnecessaryDotClass.js +++ b/lib/rules/UnnecessaryDotClass.js @@ -1,6 +1,6 @@ // Unnecessary dot class -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -27,4 +27,4 @@ const rule = { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryFinalOnPrivateMethod.js b/lib/rules/UnnecessaryFinalOnPrivateMethod.js index 2a2c0df5..5adee4b3 100644 --- a/lib/rules/UnnecessaryFinalOnPrivateMethod.js +++ b/lib/rules/UnnecessaryFinalOnPrivateMethod.js @@ -1,6 +1,6 @@ // Unnecessary private on final method -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -31,4 +31,4 @@ const rule = { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryGString.js b/lib/rules/UnnecessaryGString.js index 5e2d678a..ca24a079 100644 --- a/lib/rules/UnnecessaryGString.js +++ b/lib/rules/UnnecessaryGString.js @@ -1,6 +1,6 @@ // Unnecessary Groovy String -const { getVariable, getVariableRange, findRangeBetweenStrings } = require("../utils"); +import { getVariable, getVariableRange, findRangeBetweenStrings } from "../utils.js"; const rule = { scope: "file", @@ -100,4 +100,4 @@ I am a string''' ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryGroovyImport.js b/lib/rules/UnnecessaryGroovyImport.js index dd1fdb9d..f3b8c883 100644 --- a/lib/rules/UnnecessaryGroovyImport.js +++ b/lib/rules/UnnecessaryGroovyImport.js @@ -1,6 +1,6 @@ // Unnecessary Groovy Import -const { getVariable } = require("../utils"); +import { getVariable } from "../utils.js"; const rule = { scope: "file", @@ -38,4 +38,4 @@ class ABC { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryPackageReference.js b/lib/rules/UnnecessaryPackageReference.js index ea478214..1c7e50a6 100644 --- a/lib/rules/UnnecessaryPackageReference.js +++ b/lib/rules/UnnecessaryPackageReference.js @@ -1,5 +1,5 @@ // Unnecessary package reference -const { getVariable, getVariableRange } = require("../utils"); +import { getVariable, getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -39,4 +39,4 @@ def body = JsonOutput.toJson(value) ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryParenthesesForMethodCallWithClosure.js b/lib/rules/UnnecessaryParenthesesForMethodCallWithClosure.js index c508f108..344bb6de 100644 --- a/lib/rules/UnnecessaryParenthesesForMethodCallWithClosure.js +++ b/lib/rules/UnnecessaryParenthesesForMethodCallWithClosure.js @@ -1,6 +1,6 @@ // Unnecessary Parenthesis for method call with closure -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -38,4 +38,4 @@ dirFile.eachFile { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryPublicModifier.js b/lib/rules/UnnecessaryPublicModifier.js index 90067db9..00428eb5 100644 --- a/lib/rules/UnnecessaryPublicModifier.js +++ b/lib/rules/UnnecessaryPublicModifier.js @@ -1,5 +1,5 @@ // Variable type required -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -10,4 +10,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessarySemicolon.js b/lib/rules/UnnecessarySemicolon.js index dc1f44dd..4092152f 100644 --- a/lib/rules/UnnecessarySemicolon.js +++ b/lib/rules/UnnecessarySemicolon.js @@ -1,6 +1,6 @@ // Unnecessary semi colon at the end of a line -const { getLastStringRange } = require("../utils"); +import { getLastStringRange } from "../utils.js"; const rule = { range: { @@ -43,4 +43,4 @@ println("test") ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnnecessaryToString.js b/lib/rules/UnnecessaryToString.js index 421f2fe5..c464fc9f 100644 --- a/lib/rules/UnnecessaryToString.js +++ b/lib/rules/UnnecessaryToString.js @@ -1,6 +1,6 @@ // Unnecessary toString() -const { getStringRange } = require("../utils"); +import { getStringRange } from "../utils.js"; const rule = { range: { @@ -30,4 +30,4 @@ String str2 = str ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnusedImport.js b/lib/rules/UnusedImport.js index 38bfc3de..ddc52619 100644 --- a/lib/rules/UnusedImport.js +++ b/lib/rules/UnusedImport.js @@ -1,6 +1,6 @@ // Unused import -const { getVariable, getVariableRange } = require("../utils"); +import { getVariable, getVariableRange } from "../utils.js"; const rule = { scope: "file", @@ -69,4 +69,4 @@ class Gros { ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnusedMethodParameter.js b/lib/rules/UnusedMethodParameter.js index c3b62447..d186e94a 100644 --- a/lib/rules/UnusedMethodParameter.js +++ b/lib/rules/UnusedMethodParameter.js @@ -1,6 +1,6 @@ // Unused method parameter -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -18,4 +18,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/UnusedVariable.js b/lib/rules/UnusedVariable.js index 9c9e3a03..f5a290c4 100644 --- a/lib/rules/UnusedVariable.js +++ b/lib/rules/UnusedVariable.js @@ -1,6 +1,6 @@ // Unused variable -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -17,4 +17,4 @@ const rule = { }, }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/VariableName.js b/lib/rules/VariableName.js index cf2784a9..ab6cdefe 100644 --- a/lib/rules/VariableName.js +++ b/lib/rules/VariableName.js @@ -1,5 +1,5 @@ // Variable name invalid -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -33,4 +33,4 @@ def RANDOM_ID = 0 ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/rules/VariableTypeRequired.js b/lib/rules/VariableTypeRequired.js index 12781dac..b07d998e 100644 --- a/lib/rules/VariableTypeRequired.js +++ b/lib/rules/VariableTypeRequired.js @@ -1,5 +1,5 @@ // Variable type required -const { getVariableRange } = require("../utils"); +import { getVariableRange } from "../utils.js"; const rule = { variables: [ @@ -33,4 +33,4 @@ def returnCode = 0 ], }; -module.exports = { rule }; +export { rule }; diff --git a/lib/utils.js b/lib/utils.js index ef9c9405..b2ff8cda 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,11 +1,14 @@ // Shared functions -"use strict"; -const debug = require("debug")("npm-groovy-lint"); -const trace = require("debug")("npm-groovy-lint-trace"); -const decodeHtml = require("decode-html"); -const fse = require("fs-extra"); -const os = require("os"); +import Debug from "debug"; +const debug = Debug("npm-groovy-lint"); +const trace = Debug("npm-groovy-lint-trace"); +import fs from "fs-extra"; +import * as os from "os"; +import * as path from "path"; +import { fileURLToPath } from "url"; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +import find from "find-package-json"; const validErrorCombinations = { error: ["error", "warning", "info"], @@ -154,7 +157,7 @@ function evaluateVariables(variableDefs, msg) { const regexRes = msg.match(varDef.regex); if (regexRes && regexRes.length > 1) { const regexPos = varDef.regexPos || 1; - let value = decodeHtml(regexRes[regexPos]); + let value = decodeHTMLEntities(regexRes[regexPos]); value = escapeValue(value); const varValue = varDef.type && varDef.type === "number" @@ -221,12 +224,10 @@ function getLastStringRange(errLine, str, errItem) { }; } -/* function getLastVariableRange(errLine, evaluatedVars, variable, errItem) { const varValue = getVariable(evaluatedVars, variable); return getLastStringRange(errLine, varValue, errItem); } -*/ // Returns all strings which are not inside braces function getOutOfBracesStrings(str, exclude = []) { @@ -257,7 +258,7 @@ function getOutOfBracesStrings(str, exclude = []) { async function getSourceLines(source, fileNm) { let fileContent = source || - (await fse.readFile(fileNm).catch((err) => { + (await fs.readFile(fileNm).catch((err) => { throw new Error(`Unable to read source lines: ${err}`); // Ensure that we have a stack trace. })); return normalizeNewLines(fileContent.toString()).split(os.EOL); @@ -324,7 +325,7 @@ function getStringRangeMultiline(allLines, str, errItem, levelKey) { function getVariable(evaluatedVars, name, optns = { mandatory: true, decodeHtml: false, line: "" }) { const matchingVars = evaluatedVars.filter((evaluatedVar) => evaluatedVar.name === name); if (matchingVars && matchingVars.length > 0) { - return optns.decodeHtml ? decodeHtml(matchingVars[0].value) : matchingVars[0].value; + return optns.decodeHtml ? decodeHTMLEntities(matchingVars[0].value) : matchingVars[0].value; } else if (optns.mandatory) { throw new Error("GroovyLint fix: missing mandatory variable " + name + " in " + JSON.stringify(evaluatedVars)) + "for line :\n" + optns.line; } else { @@ -420,8 +421,7 @@ function getNpmGroovyLintVersion() { let v = process.env.npm_package_version; if (!v) { try { - const FindPackageJson = require("find-package-json"); - const finder = FindPackageJson(__dirname); + const finder = find(__dirname); v = finder.next().value.version; } catch { v = "error"; @@ -430,18 +430,42 @@ function getNpmGroovyLintVersion() { return v; } -module.exports = { +const entities = { + amp: "&", + apos: "'", + lt: "<", + gt: ">", + quot: '"', + nbsp: "\xa0", +}; +const entityPattern = /&([a-z]+);/gi; + +function decodeHTMLEntities(text) { + // A single replace pass with a static RegExp is faster than a loop + return text.replace(entityPattern, function (match, entity) { + entity = entity.toLowerCase(); + if (Object.prototype.hasOwnProperty.call(entities, entity)) { + return entities[entity]; + } + // return original string if there is no matching entity (no replace) + return match; + }); +} + +export { addImport, addSpaceAfterChar, addSpaceAroundChar, containsOtherThan, containsExceptInsideString, + decodeHTMLEntities, evaluateRange, evaluateRangeFromLine, evaluateVariables, findRangeBetweenStrings, getIndentLength, getLastStringRange, + getLastVariableRange, getNpmGroovyLintVersion, getOutOfBracesStrings, getSourceLines, diff --git a/package-lock.json b/package-lock.json index 81742b4e..abe9d9e6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,11 +11,10 @@ "dependencies": { "ansi-colors": "^4.1.1", "axios": "^1.6.2", - "chalk": "^4.1.2", + "chalk": "^5.3.0", "cli-progress": "^3.12.0", "commondir": "^1.0.1", "debug": "^4.1.1", - "decode-html": "^2.0.0", "find-java-home": "^2.0.0", "find-package-json": "^1.2.0", "fs-extra": "^11.0.0", @@ -25,7 +24,7 @@ "js-yaml": "^4.1.0", "node-sarif-builder": "^3.0.0", "optionator": "^0.9.0", - "strip-json-comments": "^3.0.1", + "strip-json-comments": "^5.0.0", "uuid": "^10.0.0" }, "bin": { @@ -46,7 +45,7 @@ "nyc": "^17.0.0", "prettier": "^3.0.0", "rimraf": "^6.0.0", - "which": "^2.0.2" + "which": "^4.0.0" }, "engines": { "node": ">=20.0.0" @@ -550,6 +549,19 @@ "url": "/~https://github.com/sponsors/sindresorhus" } }, + "node_modules/@eslint/eslintrc/node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "/~https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@eslint/js": { "version": "9.9.1", "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.9.1.tgz", @@ -1195,15 +1207,12 @@ "license": "CC-BY-4.0" }, "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", + "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", + "license": "MIT", "engines": { - "node": ">=10" + "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "funding": { "url": "/~https://github.com/chalk/chalk?sponsor=1" @@ -1352,6 +1361,27 @@ "node": ">= 8" } }, + "node_modules/cross-spawn/node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/cross-spawn/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/debug": { "version": "4.3.6", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz", @@ -1378,11 +1408,6 @@ "node": ">=0.10.0" } }, - "node_modules/decode-html": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/decode-html/-/decode-html-2.0.0.tgz", - "integrity": "sha512-lVJ+EBozhAXA2nSQG+xAgcD0P5K3uejnIIvM09uoQfS8AALkQ+HhHcEUvKovXi0EIpIZWjm0y8X7ULjaJpgY9w==" - }, "node_modules/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", @@ -1558,6 +1583,23 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/eslint/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "/~https://github.com/chalk/chalk?sponsor=1" + } + }, "node_modules/eslint/node_modules/eslint-scope": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.0.2.tgz", @@ -2139,6 +2181,7 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, "engines": { "node": ">=8" } @@ -2340,9 +2383,14 @@ } }, "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.1.tgz", + "integrity": "sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=16" + } }, "node_modules/istanbul-lib-coverage": { "version": "3.2.2", @@ -2674,6 +2722,23 @@ "url": "/~https://github.com/sponsors/sindresorhus" } }, + "node_modules/log-symbols/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "/~https://github.com/chalk/chalk?sponsor=1" + } + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -2964,6 +3029,19 @@ "dev": true, "license": "MIT" }, + "node_modules/mocha/node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "/~https://github.com/sponsors/sindresorhus" + } + }, "node_modules/mocha/node_modules/supports-color": { "version": "8.1.1", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", @@ -3982,6 +4060,13 @@ "url": "/~https://github.com/sponsors/isaacs" } }, + "node_modules/spawn-wrap/node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, "node_modules/spawn-wrap/node_modules/rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", @@ -3999,6 +4084,22 @@ "url": "/~https://github.com/sponsors/isaacs" } }, + "node_modules/spawn-wrap/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -4065,11 +4166,12 @@ } }, "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.1.tgz", + "integrity": "sha512-0fk9zBqO67Nq5M/m45qHCJxylV/DhBlIOVExqgOMiCCrzrhU6tCibRXNqE3jwJLftzE9SNuZtYbpzcO+i9FiKw==", + "license": "MIT", "engines": { - "node": ">=8" + "node": ">=14.16" }, "funding": { "url": "/~https://github.com/sponsors/sindresorhus" @@ -4079,6 +4181,7 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -4298,17 +4401,19 @@ } }, "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-4.0.0.tgz", + "integrity": "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==", + "dev": true, + "license": "ISC", "dependencies": { - "isexe": "^2.0.0" + "isexe": "^3.1.1" }, "bin": { - "node-which": "bin/node-which" + "node-which": "bin/which.js" }, "engines": { - "node": ">= 8" + "node": "^16.13.0 || >=18.0.0" } }, "node_modules/which-module": { diff --git a/package.json b/package.json index 72670255..038f03a2 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,8 @@ "name": "npm-groovy-lint", "version": "14.6.0", "description": "Lint, format and auto-fix your Groovy / Jenkinsfile / Gradle files", - "main": "index.js", + "exports": "./index.js", + "type": "module", "scripts": { "lint:fix": "eslint **/*.js --fix && prettier --write \"./lib/**/*.{js,jsx}\" --tab-width 4 --print-width 150", "server:run-from-source": "npm run server:kill && groovy -cp \"lib/java/*\" groovy/src/main/com/nvuillam/CodeNarcServer.groovy --server", @@ -48,11 +49,10 @@ "dependencies": { "ansi-colors": "^4.1.1", "axios": "^1.6.2", - "chalk": "^4.1.2", + "chalk": "^5.3.0", "cli-progress": "^3.12.0", "commondir": "^1.0.1", "debug": "^4.1.1", - "decode-html": "^2.0.0", "find-java-home": "^2.0.0", "find-package-json": "^1.2.0", "fs-extra": "^11.0.0", @@ -62,7 +62,7 @@ "js-yaml": "^4.1.0", "node-sarif-builder": "^3.0.0", "optionator": "^0.9.0", - "strip-json-comments": "^3.0.1", + "strip-json-comments": "^5.0.0", "uuid": "^10.0.0" }, "devDependencies": { @@ -80,7 +80,7 @@ "nyc": "^17.0.0", "prettier": "^3.0.0", "rimraf": "^6.0.0", - "which": "^2.0.2" + "which": "^4.0.0" }, "engines": { "node": ">=20.0.0" diff --git a/scripts/build-config-all.js b/scripts/build-config-all.js index 27e01812..a17085c5 100644 --- a/scripts/build-config-all.js +++ b/scripts/build-config-all.js @@ -1,55 +1,52 @@ - +import fs from 'fs-extra' +import { getNpmGroovyLintRules } from "../lib/groovy-lint-rules.js"; // Build Json containing all CodeNarc rules -"use strict"; - -// Imports -const fse = require('fs-extra'); -const { getNpmGroovyLintRules } = require("../lib/groovy-lint-rules.js"); - -const ruleSetAll = fse.readFileSync('lib/example/RuleSet-All.groovy', 'utf8'); - -const allLines = ruleSetAll.replace(/\r?\n/g, "\r\n").split("\r\n"); - -function buildAllRules(allLines) { - const configurationProperties = {}; - let currentCategory = null; - - for (const line of allLines) { - // Got a new category - if (line.includes('.xml')) { - //line ex : "// rulesets/basic.xml" - const splits = line.split('/'); - currentCategory = splits[splits.length - 1].replace('.xml', '').trim(); - continue; - } - // Check if the line is a rule ( contains only alphanumeric characters) - if (currentCategory && line.trim() !== '' && line.trim().match("^[a-zA-Z0-9]*$")) { - const ruleName = line.trim(); - const propName = `${currentCategory}.${ruleName}`; - let description = ruleName.replace(/([A-Z])/g, ' $1').trim(); - description = description.charAt(0).toUpperCase() + description.slice(1).toLowerCase() - const property = {}; - configurationProperties[propName] = property; +(async () => { + // Imports + const ruleSetAll = fs.readFileSync('lib/example/RuleSet-All.groovy', 'utf8'); + const allLines = ruleSetAll.replace(/\r?\n/g, "\r\n").split("\r\n"); + + function buildAllRules(allLines) { + const configurationProperties = {}; + let currentCategory = null; + + for (const line of allLines) { + // Got a new category + if (line.includes('.xml')) { + //line ex : "// rulesets/basic.xml" + const splits = line.split('/'); + currentCategory = splits[splits.length - 1].replace('.xml', '').trim(); + continue; + } + // Check if the line is a rule ( contains only alphanumeric characters) + if (currentCategory && line.trim() !== '' && line.trim().match("^[a-zA-Z0-9]*$")) { + const ruleName = line.trim(); + const propName = `${currentCategory}.${ruleName}`; + let description = ruleName.replace(/([A-Z])/g, ' $1').trim(); + description = description.charAt(0).toUpperCase() + description.slice(1).toLowerCase() + const property = {}; + configurationProperties[propName] = property; + } } + return configurationProperties; } - return configurationProperties; -} -const allRulesConfig = buildAllRules(allLines); + const allRulesConfig = buildAllRules(allLines); -const fullConfigIndented = JSON.stringify({ "rules": allRulesConfig }, null, 4); + const fullConfigIndented = JSON.stringify({ "rules": allRulesConfig }, null, 4); -fse.writeFileSync('./lib/.groovylintrc-all.json', fullConfigIndented); + fs.writeFileSync('./lib/.groovylintrc-all.json', fullConfigIndented); -console.log('Generated lib/.groovylintrc-all.json fullConfig'); + console.log('Generated lib/.groovylintrc-all.json fullConfig'); -const npmDefinedRules = getNpmGroovyLintRules(); -const fixableRules = []; -for (const rule of Object.keys(npmDefinedRules)) { - if (npmDefinedRules[rule].fix) { - fixableRules.push('- ' + rule); + const npmDefinedRules = await getNpmGroovyLintRules(); + const fixableRules = []; + for (const rule of Object.keys(npmDefinedRules)) { + if (npmDefinedRules[rule].fix) { + fixableRules.push('- ' + rule); + } } -} -fixableRules.sort(); -const mdLog = fixableRules.join('\n'); -console.log('Fixable rules :\n' + mdLog); + fixableRules.sort(); + const mdLog = fixableRules.join('\n'); + console.log('Fixable rules :\n' + mdLog); +})() \ No newline at end of file diff --git a/scripts/build-server.js b/scripts/build-server.js index 82376c89..cf7556d4 100644 --- a/scripts/build-server.js +++ b/scripts/build-server.js @@ -1,13 +1,12 @@ // Build Server creating a deterministic jar file. -"use strict"; // Imports -const fs = require('fs-extra'); -const childProcess = require("child_process"); -const handlebars = require('handlebars'); -const admZip = require('adm-zip'); -const path = require('path'); -const glob = require('glob'); +import fs from 'fs-extra'; +import * as childProcess from "child_process"; +import Handlebars from 'handlebars'; +import AdmZip from 'adm-zip'; +import * as path from 'path'; +import * as glob from 'glob'; const srcDir = 'groovy/src/main'; const metaDir = 'META-INF'; @@ -28,7 +27,7 @@ const classDir = `${tmpDir}/${classPath}`; function jarFileTimes() { console.info('Getting jar file times...'); let file = `${libDir}${jarFile}`; - let zip = new admZip(file); + let zip = new AdmZip(file); let zipEntries = zip.getEntries(); let details = new Map(); @@ -90,7 +89,7 @@ function buildManifest() { } // Update the manifest file if it has changed. - const template = handlebars.compile(manifestTemplate); + const template = Handlebars.compile(manifestTemplate); const contents = template({classPath: wrapped}); const srcManifestFile = `${srcDir}/${manifestFile}`; @@ -138,7 +137,7 @@ function buildJar(jarFileTimes) { fs.copyFileSync(`${libDir}${logConfig}`, `${tmpDir}/${logConfig}`); // Create the jar file. - var jar = new admZip(); + var jar = new AdmZip(); files.forEach((file) => { let origTime = jarFileTimes.get(file); let tmpFile = `${tmpDir}/${file}`; diff --git a/scripts/deploy-in-vscode.js b/scripts/deploy-in-vscode.js index 933df62b..c5d9fdd6 100644 --- a/scripts/deploy-in-vscode.js +++ b/scripts/deploy-in-vscode.js @@ -2,10 +2,9 @@ // Copy source files into vscode npm installation (avoid generate betas to test updates) // npm-groovy-lint & vscode-groovy-lint must be in the same folder, else you have to override VSCODE_GROOVY_LINT_PATH env variable -"use strict"; // Imports -const { existsSync, emptyDirSync, mkdirSync, copySync } = require('fs-extra'); +import { existsSync, emptyDirSync, mkdirSync, copySync } from 'fs-extra'; console.log('---- START DEPLOY IN VSCODE INSTALLED npm-groovy-lint PACKAGE ----'); diff --git a/test/errors.test.js b/test/errors.test.js index e15ad6df..ebbbed63 100644 --- a/test/errors.test.js +++ b/test/errors.test.js @@ -1,14 +1,12 @@ #! /usr/bin/env node -"use strict"; -const NpmGroovyLint = require("../lib/groovy-lint.js"); -let assert = require("assert"); -const fse = require("fs-extra"); - -const { SAMPLE_FILE_SMALL_PATH } = require("./helpers/common"); +import NpmGroovyLint from "../lib/groovy-lint.js"; +import assert from 'assert'; +import fs from 'fs-extra' +import { SAMPLE_FILE_SMALL_PATH } from "./helpers/common.js"; describe("Errors", function() { it("(API:source) should trigger a parse options error", async function() { - const prevFileContent = fse.readFileSync("./lib/example/SampleFile.groovy").toString(); + const prevFileContent = fs.readFileSync("./lib/example/SampleFile.groovy").toString(); const npmGroovyLintConfig = { source: prevFileContent, someUnknownParam: "lelamanul" @@ -20,7 +18,7 @@ describe("Errors", function() { }); it("(API:source) should trigger a loglevel failon consistency error", async function() { - const prevFileContent = fse.readFileSync("./lib/example/SampleFile.groovy").toString(); + const prevFileContent = fs.readFileSync("./lib/example/SampleFile.groovy").toString(); const npmGroovyLintConfig = { source: prevFileContent, failon: "warning", @@ -62,7 +60,7 @@ describe("Errors", function() { }); it("(API:source) should trigger a fix function error", async function() { - const prevFileContent = fse.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(); + const prevFileContent = fs.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(); const npmGroovyLintConfig = { source: prevFileContent, fix: true, diff --git a/test/helpers/common.js b/test/helpers/common.js index bacf8cdb..657eca93 100644 --- a/test/helpers/common.js +++ b/test/helpers/common.js @@ -1,8 +1,8 @@ #! /usr/bin/env node -let assert = require("assert"); -const os = require("os"); -const fse = require("fs-extra"); -const jsdiff = require("diff"); +import assert from 'assert'; +import * as os from "os"; +import fs from 'fs-extra' +import * as jsdiff from "diff"; const NPM_GROOVY_LINT = "npm-groovy-lint "; const EXAMPLE_DIRECTORY = "./lib/example/"; @@ -44,8 +44,8 @@ async function copyFilesInTmpDir() { ? "./tmptest" : os.tmpdir(); // Windows / other const tmpDir = rootTmpDir + "/" + ("tmpGroovyLintTest_" + Math.random()).replace(".", ""); - await fse.ensureDir(tmpDir, { mode: "0777" }); - await fse.copy("./lib/example", tmpDir); + await fs.ensureDir(tmpDir, { mode: "0777" }); + await fs.copy("./lib/example", tmpDir); console.info("GroovyLint: Copied ./lib/example into " + tmpDir); return tmpDir; } @@ -76,7 +76,7 @@ function assertLintedFiles(output, expectedCount) { ); } -module.exports = { +export { NPM_GROOVY_LINT, EXAMPLE_DIRECTORY, SAMPLE_FILE_BIG, diff --git a/test/helpers/init.js b/test/helpers/init.js index 3f6c6e7d..3ce38eac 100644 --- a/test/helpers/init.js +++ b/test/helpers/init.js @@ -1,14 +1,13 @@ #! /usr/bin/env node -"use strict"; -//const NpmGroovyLint = require("../../groovy-lint.js"); +import Debug from 'debug'; console.log("npm run test initialized"); // Activate debug log if we are in debug mode -const debug = typeof v8debug === "object" || /--debug|--inspect|--inspect-brk/.test(process.execArgv.join(" ")); -if (debug) { - require("debug").enable("npm-groovy-lint"); - require("debug").enable("java-caller"); +const debugActive = typeof v8debug === "object" || /--debug|--inspect|--inspect-brk/.test(process.execArgv.join(" ")); +if (debugActive) { + Debug.enable("npm-groovy-lint"); + Debug.enable("java-caller"); } // Reinitialize java-caller cache globalThis.NPM_JAVA_CALLER_IS_INITIALIZED = false; diff --git a/test/lint-api.test.js b/test/lint-api.test.js index 9de9f6aa..5e76d043 100644 --- a/test/lint-api.test.js +++ b/test/lint-api.test.js @@ -1,10 +1,9 @@ #! /usr/bin/env node -"use strict"; -const NpmGroovyLint = require("../lib/groovy-lint.js"); -let assert = require("assert"); -const fse = require("fs-extra"); -const path = require("path"); -const { +import NpmGroovyLint from "../lib/groovy-lint.js" +import assert from 'assert'; +import fs from 'fs-extra' +import * as path from "path"; +import { beforeEachTestCase, checkCodeNarcCallsCounter, assertLintedFiles, @@ -16,7 +15,7 @@ const { SAMPLE_RULESET_1_PATH, SAMPLE_RULESET_2_PATH, EXAMPLE_DIRECTORY -} = require("./helpers/common"); +} from "./helpers/common.js"; describe("Lint with API", () => { beforeEach(beforeEachTestCase); @@ -97,8 +96,8 @@ describe("Lint with API", () => { ).run(); assert(linter.status === 0, `Linter status is 0 (${linter.status} returned)`); - assert(fse.existsSync(reportFileName), `CodeNarc HTML report generated at ${reportFileName}`); - fse.removeSync(reportFileName); + assert(fs.existsSync(reportFileName), `CodeNarc HTML report generated at ${reportFileName}`); + fs.removeSync(reportFileName); checkCodeNarcCallsCounter(1); }); @@ -110,8 +109,8 @@ describe("Lint with API", () => { ).run(); assert(linter.status === 0, `Linter status is 0 (${linter.status} returned)`); - assert(fse.existsSync(reportFileName), `CodeNarc XML report generated at ${path.resolve(reportFileName)}`); - fse.removeSync(reportFileName); + assert(fs.existsSync(reportFileName), `CodeNarc XML report generated at ${path.resolve(reportFileName)}`); + fs.removeSync(reportFileName); checkCodeNarcCallsCounter(1); }); @@ -131,8 +130,8 @@ describe("Lint with API", () => { ).run(); assert(linter.status === 0, `Linter status is 0 (${linter.status} returned)`); - assert(fse.existsSync(reportFileName), `XML HTML report generated at ${path.resolve(reportFileName)}`); - fse.removeSync(reportFileName); + assert(fs.existsSync(reportFileName), `XML HTML report generated at ${path.resolve(reportFileName)}`); + fs.removeSync(reportFileName); checkCodeNarcCallsCounter(1); }); @@ -165,7 +164,7 @@ describe("Lint with API", () => { it("(API:source) should run with source only (no parsing)", async function() { const npmGroovyLintConfig = { - source: fse.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(), + source: fs.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(), sourcefilepath: SAMPLE_FILE_SMALL_PATH, insight: false, output: "txt", @@ -179,7 +178,7 @@ describe("Lint with API", () => { it("(API:source) should run with CodeNarc ruleset file", async function() { const npmGroovyLintConfig = { - source: fse.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(), + source: fs.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(), sourcefilepath: SAMPLE_FILE_SMALL_PATH, rulesets: `${SAMPLE_RULESET_1_PATH},${SAMPLE_RULESET_2_PATH}`, output: "txt", @@ -195,7 +194,7 @@ describe("Lint with API", () => { it("(API:source) should run with source only (parse success)", async function() { const npmGroovyLintConfig = { - source: fse.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(), + source: fs.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(), sourcefilepath: SAMPLE_FILE_SMALL_PATH, output: "txt", insight: false, @@ -210,7 +209,7 @@ describe("Lint with API", () => { it("(API:source) should run with source only (file with spaces)", async function() { const npmGroovyLintConfig = { - source: fse.readFileSync(SAMPLE_FILE_WITH_SPACES_PATH).toString(), + source: fs.readFileSync(SAMPLE_FILE_WITH_SPACES_PATH).toString(), sourcefilepath: SAMPLE_FILE_WITH_SPACES_PATH, output: "txt", insight: false, @@ -225,7 +224,7 @@ describe("Lint with API", () => { it("(API:source) should run with source only (parse error)", async function() { const npmGroovyLintConfig = { - source: fse.readFileSync(SAMPLE_FILE_PARSE_ERROR_PATH).toString(), + source: fs.readFileSync(SAMPLE_FILE_PARSE_ERROR_PATH).toString(), sourcefilepath: SAMPLE_FILE_PARSE_ERROR_PATH, output: "txt", insight: false, @@ -242,7 +241,7 @@ describe("Lint with API", () => { it("(API:source) should run without CodeNarc Server", async function() { const npmGroovyLintConfig = { - source: fse.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(), + source: fs.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(), sourcefilepath: SAMPLE_FILE_SMALL_PATH, noserver: true, output: "none", diff --git a/test/lint-build-fix.test.js b/test/lint-build-fix.test.js index 72cc2dee..012d6be3 100644 --- a/test/lint-build-fix.test.js +++ b/test/lint-build-fix.test.js @@ -1,18 +1,17 @@ #! /usr/bin/env node -"use strict"; -let assert = require("assert"); -const util = require("util"); -const fse = require("fs-extra"); -const rimraf = require("rimraf"); -const childProcess = require("child_process"); +import assert from 'assert'; +import * as util from 'util'; +import fs from 'fs-extra' +import * as rimraf from "rimraf"; +import * as childProcess from "child_process"; const exec = util.promisify(childProcess.exec); -const { copyFilesInTmpDir, SAMPLE_FILE_SMALL, SAMPLE_FILE_SMALL_FIX, NPM_GROOVY_LINT } = require("./helpers/common"); +import { copyFilesInTmpDir, SAMPLE_FILE_SMALL, SAMPLE_FILE_SMALL_FIX, NPM_GROOVY_LINT } from "./helpers/common.js"; describe("Lint & fix with EXE", function() { it("(EXE:file) should lint and fix a file in one shot", async function() { const tmpDir = await copyFilesInTmpDir(); try { - const prevFileContent = fse.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL).toString(); + const prevFileContent = fs.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL).toString(); const params = [ "--output", '"npm-groovy-fix-log.json"', "--path", '"' + tmpDir + '"', @@ -28,14 +27,14 @@ describe("Lint & fix with EXE", function() { } assert(stdout, "stdout is set"); - assert(fse.existsSync("npm-groovy-fix-log.json"), "Output json file has been produced"); + assert(fs.existsSync("npm-groovy-fix-log.json"), "Output json file has been produced"); - const newFileContent = fse.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL).toString().replace(/\r\n/g,'\n'); + const newFileContent = fs.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL).toString().replace(/\r\n/g,'\n'); assert(prevFileContent !== newFileContent, "Groovy file has been updated"); - const expectedFileContent = fse.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL_FIX).toString().replace(/\r\n/g,'\n'); + const expectedFileContent = fs.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL_FIX).toString().replace(/\r\n/g,'\n'); assert.strictEqual(newFileContent, expectedFileContent, "Formatted file is corresponding to expected result"); } finally { - fse.removeSync("npm-groovy-fix-log.json"); + fs.removeSync("npm-groovy-fix-log.json"); rimraf.sync(tmpDir); } }).timeout(120000); diff --git a/test/lint-build-format.test.js b/test/lint-build-format.test.js index d982d6e5..0d9d7c52 100644 --- a/test/lint-build-format.test.js +++ b/test/lint-build-format.test.js @@ -1,12 +1,11 @@ #! /usr/bin/env node -"use strict"; -let assert = require("assert"); -const util = require("util"); -const fse = require("fs-extra"); -const rimraf = require("rimraf"); -const childProcess = require("child_process"); +import assert from 'assert'; +import * as util from 'util'; +import fs from 'fs-extra' +import * as rimraf from "rimraf"; +import * as childProcess from "child_process"; const exec = util.promisify(childProcess.exec); -const { beforeEachTestCase, copyFilesInTmpDir, SAMPLE_FILE_SMALL, SAMPLE_FILE_SMALL_FORMAT, NPM_GROOVY_LINT } = require("./helpers/common"); +import { beforeEachTestCase, copyFilesInTmpDir, SAMPLE_FILE_SMALL, SAMPLE_FILE_SMALL_FORMAT, NPM_GROOVY_LINT } from "./helpers/common.js"; describe("Lint & format with EXE", function() { beforeEach(beforeEachTestCase); @@ -14,7 +13,7 @@ describe("Lint & format with EXE", function() { it("(EXE:file) should lint and format a file in one shot", async function() { const tmpDir = await copyFilesInTmpDir(); try { - const prevFileContent = fse.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL).toString(); + const prevFileContent = fs.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL).toString(); const params = [ "--output", '"npm-groovy-fix-log.json"', @@ -34,14 +33,14 @@ describe("Lint & format with EXE", function() { } assert(stdout, "stdout is set"); - assert(fse.existsSync("npm-groovy-fix-log.json"), "Output json file has been produced"); + assert(fs.existsSync("npm-groovy-fix-log.json"), "Output json file has been produced"); - const newFileContent = fse.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL).toString().replace(/\r\n/g,'\n'); + const newFileContent = fs.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL).toString().replace(/\r\n/g,'\n'); assert(prevFileContent !== newFileContent, "Groovy file has been updated"); - const expectedFileContent = fse.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL_FORMAT).toString().replace(/\r\n/g,'\n'); + const expectedFileContent = fs.readFileSync(tmpDir + "/" + SAMPLE_FILE_SMALL_FORMAT).toString().replace(/\r\n/g,'\n'); assert.strictEqual(newFileContent, expectedFileContent, "Formatted file is corresponding to expected result"); } finally { - fse.removeSync("npm-groovy-fix-log.json"); + fs.removeSync("npm-groovy-fix-log.json"); rimraf.sync(tmpDir); } }).timeout(120000); diff --git a/test/lint-build.test.js b/test/lint-build.test.js index 1cdb9f36..69e6139a 100644 --- a/test/lint-build.test.js +++ b/test/lint-build.test.js @@ -1,14 +1,13 @@ #! /usr/bin/env node -"use strict"; -const util = require("util"); -let assert = require("assert"); -const fse = require("fs-extra"); -const path = require("path"); -const childProcess = require("child_process"); +import * as util from 'util'; +import assert from 'assert'; +import fs from 'fs-extra' +import * as path from "path"; +import * as childProcess from "child_process"; const exec = util.promisify(childProcess.exec); const spawn = childProcess.spawnSync; -const { assertLintedFiles, SAMPLE_FILE_SMALL, NPM_GROOVY_LINT, SAMPLE_FILE_BIG } = require("./helpers/common"); +import { assertLintedFiles, SAMPLE_FILE_SMALL, NPM_GROOVY_LINT, SAMPLE_FILE_BIG }from "./helpers/common.js"; describe("Lint with executable", () => { it("(EXE:file) should generate text console output", async function() { @@ -146,8 +145,8 @@ describe("Lint with executable", () => { `-report="html:${reportFileName}"` ]; await exec(NPM_GROOVY_LINT + params.join(" ")); - assert(fse.existsSync(reportFileName), "html CodeNarc report has been generated at " + reportFileName); - fse.removeSync(reportFileName); + assert(fs.existsSync(reportFileName), "html CodeNarc report has been generated at " + reportFileName); + fs.removeSync(reportFileName); }); it("(EXE:file) should generate codenarc XML file report", async function() { @@ -160,8 +159,8 @@ describe("Lint with executable", () => { `-report="xml:${reportFileName}"` ]; await exec(NPM_GROOVY_LINT + params.join(" ")); - assert(fse.existsSync(reportFileName), "xml CodeNarc report has been generated at " + reportFileName); - fse.removeSync(reportFileName); + assert(fs.existsSync(reportFileName), "xml CodeNarc report has been generated at " + reportFileName); + fs.removeSync(reportFileName); }); it("(EXE:file) should run on a Jenkinsfile", async function() { diff --git a/test/lint-comments.test.js b/test/lint-comments.test.js index 406802e0..5234acf2 100644 --- a/test/lint-comments.test.js +++ b/test/lint-comments.test.js @@ -1,8 +1,7 @@ #! /usr/bin / env node -"use strict"; -const NpmGroovyLint = require("../lib/groovy-lint.js"); -let assert = require("assert"); -const { beforeEachTestCase, checkCodeNarcCallsCounter } = require("./helpers/common"); +import NpmGroovyLint from "../lib/groovy-lint.js" +import assert from 'assert'; +import { beforeEachTestCase, checkCodeNarcCallsCounter } from "./helpers/common.js"; describe("Check disabled rules", function() { beforeEach(beforeEachTestCase); diff --git a/test/lint-fix.rules.test.js b/test/lint-fix.rules.test.js index 9fadd9a9..dad450ae 100644 --- a/test/lint-fix.rules.test.js +++ b/test/lint-fix.rules.test.js @@ -1,17 +1,15 @@ #! /usr/bin/env node -"use strict"; -const NpmGroovyLint = require("../lib/groovy-lint.js"); -const { getNpmGroovyLintRules } = require("../lib/groovy-lint-rules.js"); -const { normalizeNewLines } = require("../lib/utils.js"); -let assert = require("assert"); +import NpmGroovyLint from "../lib/groovy-lint.js" +import { getNpmGroovyLintRules } from "../lib/groovy-lint-rules.js"; +import { normalizeNewLines } from "../lib/utils.js"; +import assert from 'assert'; -const { beforeEachTestCase, checkCodeNarcCallsCounter, getDiff } = require("./helpers/common"); -const npmGroovyLintRules = getNpmGroovyLintRules({ loadTests: true }); +import { beforeEachTestCase, checkCodeNarcCallsCounter, getDiff } from "./helpers/common.js"; // Read rules file and test all fixes -describe("Check rules auto-fixes", () => { +describe("Check rules auto-fixes", async () => { beforeEach(beforeEachTestCase); - + const npmGroovyLintRules = await getNpmGroovyLintRules({ loadTests: true }); // Iterate all rules for (const ruleName of Object.keys(npmGroovyLintRules)) { let pos = 1; diff --git a/test/lint-fix.test.js b/test/lint-fix.test.js index e0418183..b0879ec4 100644 --- a/test/lint-fix.test.js +++ b/test/lint-fix.test.js @@ -1,23 +1,22 @@ #! /usr/bin/env node -"use strict"; -const NpmGroovyLint = require("../lib/groovy-lint.js"); -let assert = require("assert"); -const fse = require("fs-extra"); -const rimraf = require("rimraf"); -const { +import NpmGroovyLint from "../lib/groovy-lint.js" +import assert from 'assert'; +import fs from 'fs-extra' +import * as rimraf from "rimraf"; +import { beforeEachTestCase, copyFilesInTmpDir, checkCodeNarcCallsCounter, SAMPLE_FILE_BIG_PATH, SAMPLE_FILE_SMALL_PATH -} = require("./helpers/common"); +} from "./helpers/common.js"; -describe("Lint & fix with API", function() { +describe("Lint & fix with API", function () { beforeEach(beforeEachTestCase); - it("(API:source) should lint then fix only a list of errors", async function() { + it("(API:source) should lint then fix only a list of errors", async function () { const sampleFilePath = SAMPLE_FILE_BIG_PATH; - const prevFileContent = fse.readFileSync(sampleFilePath).toString(); + const prevFileContent = fs.readFileSync(sampleFilePath).toString(); const npmGroovyLintConfig = { source: prevFileContent, sourcefilepath: sampleFilePath, @@ -39,10 +38,10 @@ describe("Lint & fix with API", function() { checkCodeNarcCallsCounter(2); }); - it("(API:source) should lint and fix (one shot)", async function() { + it("(API:source) should lint and fix (one shot)", async function () { const sampleFilePath = SAMPLE_FILE_BIG_PATH; const expectedFixedErrs = 1076; - const prevFileContent = fse.readFileSync(sampleFilePath).toString(); + const prevFileContent = fs.readFileSync(sampleFilePath).toString(); const npmGroovyLintConfig = { source: prevFileContent, sourcefilepath: sampleFilePath, @@ -63,10 +62,10 @@ describe("Lint & fix with API", function() { checkCodeNarcCallsCounter(3); }).timeout(200000); - it("(API:source) should lint and fix (no lintagainafterfix)", async function() { + it("(API:source) should lint and fix (no lintagainafterfix)", async function () { const sampleFilePath = SAMPLE_FILE_BIG_PATH; const expectedFixedErrs = 1076; - const prevFileContent = fse.readFileSync(sampleFilePath).toString(); + const prevFileContent = fs.readFileSync(sampleFilePath).toString(); const npmGroovyLintConfig = { source: prevFileContent, sourcefilepath: sampleFilePath, @@ -88,10 +87,10 @@ describe("Lint & fix with API", function() { checkCodeNarcCallsCounter(2); }).timeout(200000); - it("(API:source) should lint and fix (no lintagainafterfix) 2", async function() { + it("(API:source) should lint and fix (no lintagainafterfix) 2", async function () { const sampleFilePath = SAMPLE_FILE_SMALL_PATH; const expectedFixedErrs = 3; - const prevFileContent = fse.readFileSync(sampleFilePath).toString(); + const prevFileContent = fs.readFileSync(sampleFilePath).toString(); const npmGroovyLintConfig = { source: prevFileContent, sourcefilepath: sampleFilePath, @@ -113,10 +112,10 @@ describe("Lint & fix with API", function() { checkCodeNarcCallsCounter(1); }).timeout(200000); - it("(API:file) should lint and fix a Jenkinsfile in one shot", async function() { + it("(API:file) should lint and fix a Jenkinsfile in one shot", async function () { const tmpDir = await copyFilesInTmpDir(); try { - const prevFileContent = fse.readFileSync(tmpDir + "/Jenkinsfile").toString(); + const prevFileContent = fs.readFileSync(tmpDir + "/Jenkinsfile").toString(); const linter = await new NpmGroovyLint( [ process.execPath, @@ -138,16 +137,16 @@ describe("Lint & fix with API", function() { assert(linter.status === 1, `Linter status is 1 (${linter.status} returned)`); assert(linter.lintResult.summary.totalFixedNumber > 0, "Error have been fixed"); assert(linter.lintResult.files[Object.keys(linter.lintResult.files)[0]].updatedSource !== prevFileContent, "File content has been updated"); - assert(fse.existsSync("npm-groovy-fix-log.json"), "Output json file has been produced"); + assert(fs.existsSync("npm-groovy-fix-log.json"), "Output json file has been produced"); assert(!linter.outputString.includes("NaN"), "Results does not contain NaN"); checkCodeNarcCallsCounter(2); } finally { - fse.removeSync("npm-groovy-fix-log.json"); + fs.removeSync("npm-groovy-fix-log.json"); rimraf.sync(tmpDir); } }).timeout(120000); - it("(API:file) should fix only some errors", async function() { + it("(API:file) should fix only some errors", async function () { const fixRules = [ // Line rules or not changing line rules @@ -190,16 +189,16 @@ describe("Lint & fix with API", function() { assert(linter.status === 0); assert(linter.lintResult.summary.totalFixedNumber > 0, "Errors have been fixed"); - assert(fse.existsSync("npm-groovy-fix-log-should-fix-only-some-errors.txt"), "Output txt file produced"); + assert(fs.existsSync("npm-groovy-fix-log-should-fix-only-some-errors.txt"), "Output txt file produced"); assert(!linter.outputString.includes("NaN"), "Results does not contain NaN"); checkCodeNarcCallsCounter(1); } finally { - fse.removeSync("npm-groovy-fix-log-should-fix-only-some-errors.txt"); + fs.removeSync("npm-groovy-fix-log-should-fix-only-some-errors.txt"); rimraf.sync(tmpDir); } }).timeout(120000); - it("(API:file) should fix groovy files", async function() { + it("(API:file) should fix groovy files", async function () { const tmpDir = await copyFilesInTmpDir(); try { const linter = await new NpmGroovyLint( @@ -220,11 +219,11 @@ describe("Lint & fix with API", function() { assert(linter.status === 1, `Linter status is 1 (${linter.status} returned)`); assert(linter.lintResult.summary.totalFixedNumber > 0, "Errors have been fixed"); - assert(fse.existsSync("npm-groovy-fix-log-should-fix-groovy-files.txt"), "Output txt file produced"); + assert(fs.existsSync("npm-groovy-fix-log-should-fix-groovy-files.txt"), "Output txt file produced"); assert(!linter.outputString.includes("NaN"), "Results does not contain NaN"); checkCodeNarcCallsCounter(2); } finally { - fse.removeSync("npm-groovy-fix-log-should-fix-groovy-files.txt"); + fs.removeSync("npm-groovy-fix-log-should-fix-groovy-files.txt"); rimraf.sync(tmpDir); } }).timeout(120000); diff --git a/test/lint-format.test.js b/test/lint-format.test.js index 488304a8..4ce3fb2c 100644 --- a/test/lint-format.test.js +++ b/test/lint-format.test.js @@ -1,11 +1,10 @@ #! /usr/bin/env node -"use strict"; -const NpmGroovyLint = require("../lib/groovy-lint.js"); -let assert = require("assert"); -const fse = require("fs-extra"); -const { normalizeNewLines } = require("../lib/utils.js"); -const rimraf = require("rimraf"); -const { +import NpmGroovyLint from "../lib/groovy-lint.js" +import assert from 'assert'; +import fs from 'fs-extra' +import { normalizeNewLines } from "../lib/utils.js"; +import * as rimraf from "rimraf"; +import { beforeEachTestCase, checkCodeNarcCallsCounter, getDiff, @@ -13,14 +12,14 @@ const { SAMPLE_FILE_BIG, SAMPLE_FILE_BIG_PATH, SAMPLE_FILE_SMALL_PATH -} = require("./helpers/common"); +} from "./helpers/common.js"; -describe("Format with API", function() { +describe("Format with API", function () { beforeEach(beforeEachTestCase); - it("(API:source) should format code", async function() { + it("(API:source) should format code", async function () { const expectedFixedErrs = 1096; - const prevFileContent = fse.readFileSync(SAMPLE_FILE_BIG_PATH).toString(); + const prevFileContent = fs.readFileSync(SAMPLE_FILE_BIG_PATH).toString(); const npmGroovyLintConfig = { source: prevFileContent, format: true, @@ -43,9 +42,9 @@ describe("Format with API", function() { checkCodeNarcCallsCounter(2); }).timeout(100000); - it("(API:source) should format code with custom config", async function() { + it("(API:source) should format code with custom config", async function () { const expectedFixedErrs = 37; - const prevFileContent = fse.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(); + const prevFileContent = fs.readFileSync(SAMPLE_FILE_SMALL_PATH).toString(); const npmGroovyLintConfig = { source: prevFileContent, sourcefilepath: SAMPLE_FILE_SMALL_PATH, @@ -72,11 +71,11 @@ describe("Format with API", function() { checkCodeNarcCallsCounter(1); }).timeout(100000); - it("(API:file) should format code", async function() { + it("(API:file) should format code", async function () { const expectedFixedErrs = 1096; const tmpDir = await copyFilesInTmpDir(); try { - const prevFileContent = fse.readFileSync(SAMPLE_FILE_BIG_PATH).toString(); + const prevFileContent = fs.readFileSync(SAMPLE_FILE_BIG_PATH).toString(); const npmGroovyLintConfig = { path: tmpDir, files: `**/${SAMPLE_FILE_BIG}`, @@ -93,7 +92,7 @@ describe("Format with API", function() { linter.lintResult.summary.totalFixedNumber >= expectedFixedErrs, `${expectedFixedErrs} errors have been fixed (${linter.lintResult.summary.totalFixedNumber} returned)` ); - const newFileContent = fse.readFileSync(tmpDir + "/" + SAMPLE_FILE_BIG).toString(); + const newFileContent = fs.readFileSync(tmpDir + "/" + SAMPLE_FILE_BIG).toString(); assert(newFileContent !== prevFileContent, "File has been updated"); const fixedNbInLogs = (linter.outputString.match(/fixed/g) || []).length; assert(fixedNbInLogs >= expectedFixedErrs, `Result log contains ${expectedFixedErrs} fixed errors (${fixedNbInLogs} returned)`); @@ -105,10 +104,10 @@ describe("Format with API", function() { }).timeout(100000); for (const [key, val] of getSamplesMap()) { - it("(API:source) " + key + " --format", async function() { + it("(API:source) " + key + " --format", async function () { await checkRule(key, val, "format"); }).timeout(30000); - it("(API:source) " + key + " --fix", async function() { + it("(API:source) " + key + " --fix", async function () { await checkRule(key, val, "fix"); }).timeout(30000); } diff --git a/test/lint-range.rules.test.js b/test/lint-range.rules.test.js index 06dd0ae7..729666cc 100644 --- a/test/lint-range.rules.test.js +++ b/test/lint-range.rules.test.js @@ -1,17 +1,15 @@ #! /usr/bin/env node -"use strict"; -const NpmGroovyLint = require("../lib/groovy-lint.js"); -const { getNpmGroovyLintRules } = require("../lib/groovy-lint-rules.js"); -const { normalizeNewLines } = require("../lib/utils.js"); -let assert = require("assert"); +import NpmGroovyLint from "../lib/groovy-lint.js" +import { getNpmGroovyLintRules } from "../lib/groovy-lint-rules.js"; +import { normalizeNewLines } from "../lib/utils.js"; +import assert from 'assert'; -const { beforeEachTestCase, checkCodeNarcCallsCounter } = require("./helpers/common"); -const npmGroovyLintRules = getNpmGroovyLintRules({ loadTests: true }); +import { beforeEachTestCase, checkCodeNarcCallsCounter } from "./helpers/common.js"; // Read rules file and test all fixes -describe("Check range detection", () => { +describe("Check range detection", async () => { beforeEach(beforeEachTestCase); - + const npmGroovyLintRules = await getNpmGroovyLintRules({ loadTests: true }); // Iterate all rules for (const ruleName of Object.keys(npmGroovyLintRules)) { let pos = 1; diff --git a/test/miscellaneous.test.js b/test/miscellaneous.test.js index 79e930f3..49160a29 100644 --- a/test/miscellaneous.test.js +++ b/test/miscellaneous.test.js @@ -1,15 +1,17 @@ #! /usr/bin/env node -"use strict"; -const NpmGroovyLint = require("../lib/groovy-lint.js"); -let assert = require("assert"); -const childProcess = require("child_process"); -const fse = require("fs-extra"); -const os = require("os"); -const path = require("path"); -const util = require("util") -const which = require("which"); +import NpmGroovyLint from "../lib/groovy-lint.js" +import assert from 'assert'; +import * as childProcess from "child_process"; +import fs from 'fs-extra' +import * as os from "os"; +import * as path from "path"; +import find from "find-package-json"; +import * as util from 'util' +import * as which from 'which' const exec = util.promisify(childProcess.exec); -const { beforeEachTestCase, checkCodeNarcCallsCounter, SAMPLE_FILE_BIG, SAMPLE_FILE_SMALL, SAMPLE_FILE_SMALL_PATH } = require("./helpers/common"); +import { beforeEachTestCase, checkCodeNarcCallsCounter, SAMPLE_FILE_BIG, SAMPLE_FILE_SMALL, SAMPLE_FILE_SMALL_PATH } from "./helpers/common.js"; +import { fileURLToPath } from 'url'; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); describe("Miscellaneous", function() { it("(API:source) returns config file using path", async function() { @@ -36,8 +38,8 @@ describe("Miscellaneous", function() { it("(API:source) load config using specific file name", async function() { const customConfigFilePath = process.platform.includes("linux") ? "~/.groovylintrc-custom.json" : os.tmpdir() + "\\.groovylintrc-custom.json"; - await fse.ensureDir("~/", { mode: "0777" }); - await fse.copy("./lib/example/.groovylintrc-custom.json", customConfigFilePath); + await fs.ensureDir("~/", { mode: "0777" }); + await fs.copy("./lib/example/.groovylintrc-custom.json", customConfigFilePath); const npmGroovyLintConfig = { config: customConfigFilePath, path: "./lib/example/", @@ -47,7 +49,7 @@ describe("Miscellaneous", function() { verbose: true }; const linter = await new NpmGroovyLint(npmGroovyLintConfig, {}).run(); - await fse.remove(customConfigFilePath); + await fs.remove(customConfigFilePath); const rules = linter.options.rules || {}; assert(rules["CompileStatic"] == "off", "CompileStatic is off"); assert(rules["CouldBeElvis"] == "off", "CouldBeElvis is off"); @@ -284,8 +286,7 @@ describe("Miscellaneous", function() { process.env.npm_package_version = ""; // NV: Do not use npm_package_version to have more code coverage :) const linter = await new NpmGroovyLint([process.execPath, "", "-v"], {}).run(); assert(linter.status === 0, `Linter status is 0 (${linter.status} returned)`); - const FindPackageJson = require("find-package-json"); - const finder = FindPackageJson(__dirname); + const finder = find(__dirname); const v = finder.next().value.version; assert(linter.outputString.includes(`npm-groovy-lint version ${v}`), `Provides version ${v}\nReturned outputString:\n${linter.outputString}`); assert(linter.outputString.includes(`CodeNarc version`), `Provides CodeNarc version\nReturned outputString:\n${linter.outputString}`); @@ -304,10 +305,10 @@ describe("Miscellaneous", function() { beforeEachTestCase(); // Call manually as beforeEach only works from the CLI. const logFile = "npm-groovy-lint.log"; - let logFileExist = fse.existsSync(logFile); + let logFileExist = fs.existsSync(logFile); if (logFileExist) { // Remove old log file. - await fse.remove(logFile); + await fs.remove(logFile); } const npmGroovyLintConfig = { @@ -322,7 +323,7 @@ describe("Miscellaneous", function() { assert(linter.status === 1, `Linter status is 0 (${linter.status} returned)`); checkCodeNarcCallsCounter(1); - logFileExist = fse.existsSync(logFile) + logFileExist = fs.existsSync(logFile) assert(!logFileExist, "npm-groovy-lint.log has been created"); // Enable log file. @@ -332,7 +333,7 @@ describe("Miscellaneous", function() { assert(linter.status === 1, `Linter status is 1 (${linter.status} returned)`); checkCodeNarcCallsCounter(2); - logFileExist = fse.existsSync(logFile); + logFileExist = fs.existsSync(logFile); assert(logFileExist, "npm-groovy-lint.log has not been created"); }); }); diff --git a/test/server.test.js b/test/server.test.js index 2ee94e11..f2ae4af2 100644 --- a/test/server.test.js +++ b/test/server.test.js @@ -1,9 +1,8 @@ #! /usr/bin/env node -"use strict"; -const NpmGroovyLint = require("../lib/groovy-lint.js"); -let assert = require("assert"); -const which = require("which"); -const { beforeEachTestCase, checkCodeNarcCallsCounter, SAMPLE_FILE_BIG } = require("./helpers/common"); +import NpmGroovyLint from "../lib/groovy-lint.js" +import assert from 'assert'; +import * as which from 'which' +import { beforeEachTestCase, checkCodeNarcCallsCounter, SAMPLE_FILE_BIG } from "./helpers/common.js"; describe.skip("Server", function() { it("(API:Server) should kill running server", async function() {