Skip to content

Commit

Permalink
Convert to ES Module (#412)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
nvuillam and renovate[bot] authored Aug 25, 2024
1 parent c86deb0 commit 1a804b8
Show file tree
Hide file tree
Showing 103 changed files with 638 additions and 535 deletions.
1 change: 1 addition & 0 deletions .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"anymatch",
"appender",
"Appender",
"apos",
"archy",
"argparse",
"arity",
Expand Down
10 changes: 6 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
10 changes: 6 additions & 4 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
42 changes: 20 additions & 22 deletions lib/codenarc-caller.js
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -445,5 +445,3 @@ class CodeNarcCaller {
}
}
}

module.exports = CodeNarcCaller;
27 changes: 14 additions & 13 deletions lib/codenarc-factory.js
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -215,6 +215,7 @@ async function parseCodeNarcResult(options, codeNarcBaseDir, codeNarcJsonResult,
},
};
}
const npmGroovyLintRules = await getNpmGroovyLintRules();
const result = { summary: {} };

// Parse main result
Expand Down Expand Up @@ -518,4 +519,4 @@ function directoryExists(resolvedPath) {
}
}

module.exports = { prepareCodeNarcCall, parseCodeNarcResult };
export { prepareCodeNarcCall, parseCodeNarcResult };
30 changes: 16 additions & 14 deletions lib/config.js
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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) {
Expand All @@ -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) {
Expand All @@ -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);
Expand Down Expand Up @@ -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}`;
Expand All @@ -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
Expand Down Expand Up @@ -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, "");
}

Expand All @@ -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 };
3 changes: 1 addition & 2 deletions lib/filter.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// Filter errors
"use strict";

// Parse source to list parts where errors must be ignored
function collectDisabledBlocks(allLines) {
Expand Down Expand Up @@ -91,4 +90,4 @@ function cleanFromCommentMarks(str) {
return str.replace("/*", "").replace("//", "").replace("*/", "").trim();
}

module.exports = { collectDisabledBlocks, isFilteredError };
export { collectDisabledBlocks, isFilteredError };
26 changes: 12 additions & 14 deletions lib/groovy-lint-fix.js
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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(",");
}
Expand All @@ -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(
{
Expand Down Expand Up @@ -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);
}
}),
);
Expand Down Expand Up @@ -351,5 +351,3 @@ class NpmGroovyLintFix {
});
}
}

module.exports = NpmGroovyLintFix;
22 changes: 11 additions & 11 deletions lib/groovy-lint-rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 !
Expand Down Expand Up @@ -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;
}
Expand All @@ -187,8 +189,6 @@ function getNpmGroovyLintRules(optns = { loadTests: false }) {
return npmGroovyLintRules;
}

function getFormattingRulesToAlwaysRun() {
export function getFormattingRulesToAlwaysRun() {
return formatRulesToAlwaysRun;
}

module.exports = { getNpmGroovyLintRules, getFormattingRulesToAlwaysRun };
33 changes: 16 additions & 17 deletions lib/groovy-lint.js
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -530,4 +529,4 @@ class NpmGroovyLint {
}
}

module.exports = NpmGroovyLint;
export default NpmGroovyLint;
Loading

0 comments on commit 1a804b8

Please sign in to comment.