Skip to content

Commit

Permalink
eslint fix
Browse files Browse the repository at this point in the history
  • Loading branch information
nvuillam committed Aug 23, 2024
1 parent beea1ce commit f12674e
Show file tree
Hide file tree
Showing 82 changed files with 623 additions and 643 deletions.
69 changes: 36 additions & 33 deletions lib/codenarc-caller.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ class CodeNarcCaller {
minimumJavaVersion: 17,
maximumJavaVersion: 17,
rootPath: __dirname,
jar: "java/CodeNarcServer.jar"
jar: "java/CodeNarcServer.jar",
},
codeNarcJava: {
minimumJavaVersion: 17,
maximumJavaVersion: 17,
rootPath: __dirname,
jar: "java/CodeNarcServer.jar"
}
jar: "java/CodeNarcServer.jar",
},
};

constructor(codenarcArgs1, serverStatus1, args1, options1, execOpts1) {
Expand Down Expand Up @@ -69,9 +69,9 @@ class CodeNarcCaller {
codeNarcExcludes: this.execOpts.codeNarcExcludes,
parse: this.options.parse !== false && this.execOpts.onlyCodeNarc === false,
fileList: this.execOpts.groovyFileName ? [this.execOpts.groovyFileName] : this.execOpts.inputFileList,
requestKey: this.execOpts.requestKey || null
requestKey: this.execOpts.requestKey || null,
},
timeout: 600000
timeout: 600000,
};
trace(`CALL CodeNarcServer with ${JSON.stringify(axiosConfig, null, 2)}`);
let response;
Expand All @@ -98,8 +98,8 @@ class CodeNarcCaller {
error: {
msg: `exception: ${e.response.data.exceptionType} message: ${e.response.data.errorMessage}`,
stack: e.stack,
responseData: e.response.data.errorDtl
}
responseData: e.response.data.errorDtl,
},
};
} else if (e.code === "ECONNRESET") {
// The server was shutdown just retry.
Expand All @@ -111,13 +111,16 @@ class CodeNarcCaller {
// respObj.status = 'cancelledByDuplicateRequest'
// respObj.statusCode = 444
return {
status: 9
status: 9,
};
} else {
console.error(
c.red(
"CodeNarcServer unexpected error:\n" + JSON.stringify(e, null, 2) + "\n" + JSON.stringify(e.response?.data?.errorDtl, null, 2)
)
"CodeNarcServer unexpected error:\n" +
JSON.stringify(e, null, 2) +
"\n" +
JSON.stringify(e.response?.data?.errorDtl, null, 2),
),
);
}
this.serverStatus = "error";
Expand All @@ -126,8 +129,8 @@ class CodeNarcCaller {
error: {
msg: e.message,
stack: e.stack,
responseData: e.response?.data?.errorDtl
}
responseData: e.response?.data?.errorDtl,
},
};
}

Expand All @@ -139,7 +142,7 @@ class CodeNarcCaller {
parseErrors: response.data.parseErrors,
codeNarcStdOut: response.data.stdout,
codeNarcStdErr: undefined,
status: 0
status: 0,
};
}

Expand All @@ -148,7 +151,7 @@ class CodeNarcCaller {
return {
codeNarcStdOut: undefined,
codeNarcStdErr: undefined,
status: 9
status: 9,
};
}

Expand All @@ -165,9 +168,9 @@ class CodeNarcCaller {
msgDtl: {
parseErrors: response.data.parseErrors,
stdout: response.data.stdout,
stderr: response.data.errorDtl
}
}
stderr: response.data.errorDtl,
},
},
};
}

Expand All @@ -183,7 +186,7 @@ class CodeNarcCaller {
if (this.execOpts.groovyFileName) {
scriptArgs.unshift("--file", this.execOpts.groovyFileName);
} else if (this.execOpts.inputFileList) {
this.execOpts.inputFileList.forEach(file => {
this.execOpts.inputFileList.forEach((file) => {
scriptArgs.unshift("--file", file);
});
}
Expand All @@ -194,9 +197,9 @@ class CodeNarcCaller {
{
format: "[{bar}] Running CodeNarc for {duration_formatted}",
hideCursor: true,
clearOnComplete: true
clearOnComplete: true,
},
cliProgress.Presets.shades_classic
cliProgress.Presets.shades_classic,
);
this.bar.start(10, 1);
this.barTimer = setInterval(() => {
Expand Down Expand Up @@ -232,8 +235,8 @@ 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 => {
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";
Expand All @@ -246,8 +249,8 @@ class CodeNarcCaller {
codeNarcStdErr: javaResult.stderr,
status: 2,
error: {
msg: `Fatal error while calling CodeNarc\n${reason}\n${javaResult.stderr}`
}
msg: `Fatal error while calling CodeNarc\n${reason}\n${javaResult.stderr}`,
},
};
}
}
Expand All @@ -259,7 +262,7 @@ class CodeNarcCaller {
parseErrors: response.parseErrors,
codeNarcStdOut: javaResult.stdout,
codeNarcStdErr: javaResult.stderr,
status: 0
status: 0,
};
}

Expand Down Expand Up @@ -295,16 +298,16 @@ class CodeNarcCaller {
const start = performance.now();
let notified = false;
let interval;
await new Promise(resolve => {
await new Promise((resolve) => {
interval = setInterval(() => {
debug(
`pinging CodeNarcServer at ${serverPingUri} notified: ${notified}, serverStatus: ${
this.serverStatus
}, since: ${performance.now() - start}, maxAttemptTimeMs: ${maxAttemptTimeMs}`
}, since: ${performance.now() - start}, maxAttemptTimeMs: ${maxAttemptTimeMs}`,
);
axios
.get(serverPingUri)
.then(response => {
.then((response) => {
if (response.status === 200) {
// Server is correctly started, as he replied to the ping request
this.serverStatus = "running";
Expand All @@ -322,7 +325,7 @@ class CodeNarcCaller {
resolve();
}
})
.catch(e => {
.catch((e) => {
debug(`Ping code: ${e.code} message: ${e.message}`);
let since = performance.now() - start;
if (notified === false && this.serverStatus === "unknown" && since > maxAttemptTimeMs) {
Expand Down Expand Up @@ -399,15 +402,15 @@ class CodeNarcCaller {
const serverPingUri = this.getCodeNarcServerUri() + "/ping";

let interval;
await new Promise(resolve => {
await new Promise((resolve) => {
interval = setInterval(() => {
debug(`pinging CodeNarcServer at ${serverPingUri} serverStatus: ${this.serverStatus}`);
axios
.get(serverPingUri)
.then(response => {
.then((response) => {
debug(`ping response: ${response.status}`);
})
.catch(e => {
.catch((e) => {
debug(`Ping code: ${e.code} message: ${e.message}`);
clearInterval(interval);
resolve();
Expand Down Expand Up @@ -438,7 +441,7 @@ class CodeNarcCaller {
try {
return JSON.parse(response);
} catch (e) {
return { err: `Unable to parse ${response}` };
return { err: `Unable to parse ${response}: ${e.message}` };
}
}
}
Expand Down
64 changes: 27 additions & 37 deletions lib/codenarc-factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ async function prepareCodeNarcCall(options) {
cnFiles = ["**/" + tmpFileNm];
}

await fs.writeFile(result.tmpGroovyFileName, normalizeNewLines(options.source)).catch(err => {
await fs.writeFile(result.tmpGroovyFileName, normalizeNewLines(options.source)).catch((err) => {
throw new Error(`Unable to write temp file: ${err}`); // Ensure we have a stack trace.
});

Expand Down Expand Up @@ -89,17 +89,17 @@ async function prepareCodeNarcCall(options) {
const filePatterns =
options.ext && options.ext.length > 0
? // Convert extensions with or without leading slash into an ant pattern.
options.ext.map(ext => ext.replace(/^\.?/u, "*."))
options.ext.map((ext) => ext.replace(/^\.?/u, "*."))
: defaultFilesPattern;
const sourceFiles = [];
const includes = [];
positionalArgs.filter(Boolean).forEach(pathname => {
positionalArgs.filter(Boolean).forEach((pathname) => {
const absolutePath = path.resolve(".", pathname);
const relativePath = path.relative(codeNarcBaseDir, absolutePath);
if (directoryExists(absolutePath)) {
// Directory: convert into ant patterns.
const patternBase = antPath(relativePath) + "**/";
includes.push(...filePatterns.map(filePattern => patternBase + filePattern));
includes.push(...filePatterns.map((filePattern) => patternBase + filePattern));
} else if (fs.existsSync(absolutePath)) {
// File: add to file / patterns list.
const file = antPath(relativePath);
Expand Down Expand Up @@ -127,7 +127,7 @@ async function prepareCodeNarcCall(options) {
result.codeNarcIncludes = cnFiles;
} else {
// If files not sent, use defaultFilesPattern, guessed from options.rulesets value
const filePatterns = defaultFilesPattern.map(filePattern => `**/${filePattern}`);
const filePatterns = defaultFilesPattern.map((filePattern) => `**/${filePattern}`);
result.codenarcArgs.push(`-includes=${filePatterns.join(",")}`);
result.codeNarcIncludes = filePatterns;
}
Expand All @@ -149,23 +149,13 @@ async function prepareCodeNarcCall(options) {
result.outputType = result.output.endsWith(".txt")
? "txt"
: result.output.endsWith(".json")
? "json"
: result.output.endsWith(".sarif")
? "sarif"
: result.output;
? "json"
: result.output.endsWith(".sarif")
? "sarif"
: result.output;
result.codenarcArgs.push(`-report=json:stdout`);
} else if (["html", "xml"].includes(result.output.split(".").pop())) {
result.outputType = result.output
.split(".")
.pop()
.endsWith("html")
? "html"
: result.output
.split(".")
.pop()
.endsWith("xml")
? "xml"
: "";
result.outputType = result.output.split(".").pop().endsWith("html") ? "html" : result.output.split(".").pop().endsWith("xml") ? "xml" : "";
const ext = result.output.split(".").pop();
result.codenarcArgs.push(`-report=${ext}:${result.output}`);

Expand All @@ -178,7 +168,7 @@ async function prepareCodeNarcCall(options) {
const errMsg = `Output not managed: ${result.output}. (For now, only output formats are txt and json in console, and html and xml as files)`;
console.error(errMsg);
result.error = {
msg: errMsg
msg: errMsg,
};
}
return result;
Expand All @@ -197,10 +187,10 @@ function antPath(path) {
// Calculate longest base dir by analyzing the list of files
async function getCodeNarcBaseDirFromFiles(positionalArgs) {
// All arguments are not files
if (!positionalArgs.every(fileOrDirOrPattern => fs.existsSync(fileOrDirOrPattern) || directoryExists(fileOrDirOrPattern))) {
if (!positionalArgs.every((fileOrDirOrPattern) => fs.existsSync(fileOrDirOrPattern) || directoryExists(fileOrDirOrPattern))) {
return process.cwd();
}
const folders = positionalArgs.map(fileOrDir => {
const folders = positionalArgs.map((fileOrDir) => {
// Dir
if (directoryExists(fileOrDir)) {
return path.resolve(fileOrDir);
Expand All @@ -221,8 +211,8 @@ async function parseCodeNarcResult(options, codeNarcBaseDir, codeNarcJsonResult,
return {
status: 2,
error: {
msg: errMsg
}
msg: errMsg,
},
};
}
const result = { summary: {} };
Expand Down Expand Up @@ -264,13 +254,13 @@ async function parseCodeNarcResult(options, codeNarcBaseDir, codeNarcJsonResult,
line: parseError.cause && parseError.cause.line ? parseError.cause.line : 0,
rule: "NglParseError",
severity: "error",
msg: msg
msg: msg,
};
// Add range if provided
if (parseError.cause && parseError.cause.startColumn) {
errItemParse.range = {
start: { line: parseError.cause.startLine, character: parseError.cause.startColumn },
end: { line: parseError.cause.endLine, character: parseError.cause.endColumn }
end: { line: parseError.cause.endLine, character: parseError.cause.endColumn },
};
}

Expand Down Expand Up @@ -310,7 +300,7 @@ async function parseCodeNarcResult(options, codeNarcBaseDir, codeNarcJsonResult,
rule: violation.ruleName,
severity:
violation.priority === 1 ? "error" : violation.priority === 2 ? "warning" : violation.priority === 3 ? "info" : "unknown",
msg: violation.message ? violation.message : ""
msg: violation.message ? violation.message : "",
};
errItem.msg = tmpGroovyFileNameReplace ? errItem.msg.replace(tmpGroovyFileNameReplace, "") : errItem.msg;

Expand Down Expand Up @@ -371,7 +361,7 @@ async function parseCodeNarcResult(options, codeNarcBaseDir, codeNarcJsonResult,
// Add description from CodeNarc
rules[ruleName] = { description: ruleDef.description };
// Try to build codenarc url (ex: https://codenarc.github.io/CodeNarc/codenarc-rules-basic.html#bitwiseoperatorinconditional-rule )
const matchRules = grooylintrcAllRules.filter(ruleNameX => ruleNameX.split(".")[1] === ruleName);
const matchRules = grooylintrcAllRules.filter((ruleNameX) => ruleNameX.split(".")[1] === ruleName);
if (matchRules && matchRules[0]) {
const ruleCategory = matchRules[0].split(".")[0];
const ruleDocUrl = `${CODENARC_WWW_BASE}/codenarc-rules-${ruleCategory}.html#${ruleName.toLowerCase()}-rule`;
Expand All @@ -389,7 +379,7 @@ async function buildRuleSets(options) {
// If RuleSet files has already been created, or is groovy file, return it
if (options.rulesets && (options.rulesets.endsWith(".groovy") || options.rulesets.endsWith(".xml"))) {
const rulesetSplits = options.rulesets.split(",");
const normalizedRulesets = rulesetSplits.map(rulesetFile => {
const normalizedRulesets = rulesetSplits.map((rulesetFile) => {
const fullFile = path.resolve(rulesetFile);
// Encode file name so CodeNarc understands it
if (fs.existsSync(fullFile)) {
Expand All @@ -416,8 +406,8 @@ async function buildRuleSets(options) {
!options.rulesets.includes("/") &&
!options.rulesets.includes("\\")
) {
let ruleList = options.rulesets.split(/(,(?!"))/gm).filter(elt => elt !== ",");
ruleSetsDef = ruleList.map(ruleFromArgument => {
let ruleList = options.rulesets.split(/(,(?!"))/gm).filter((elt) => elt !== ",");
ruleSetsDef = ruleList.map((ruleFromArgument) => {
let ruleName;
let ruleOptions = {};
if (ruleFromArgument.includes("{")) {
Expand All @@ -434,8 +424,8 @@ async function buildRuleSets(options) {
typeof ruleFromConfig === "object"
? Object.assign(ruleFromConfig, ruleOptions)
: Object.keys(ruleOptions).length > 0
? ruleOptions
: ruleFromConfig;
? ruleOptions
: ruleFromConfig;
const ruleDef = buildCodeNarcRule(ruleName, mergedRuleConfig);
// If rule has been sent as argument, enable it by default
if (ruleDef.enabled === false) {
Expand All @@ -449,15 +439,15 @@ async function buildRuleSets(options) {
for (const ruleName of Object.keys(options.rules)) {
let ruleDef = options.rules[ruleName];
// If rule has been overridden in argument, set it on top of config file properties
const ruleFromRuleSetsArgPos = ruleSetsDef.findIndex(ruleDef => ruleDef.ruleName === ruleName);
const ruleFromRuleSetsArgPos = ruleSetsDef.findIndex((ruleDef) => ruleDef.ruleName === ruleName);
if (ruleFromRuleSetsArgPos > -1) {
const ruleFromRuleSetsArg = ruleSetsDef[ruleFromRuleSetsArgPos];
ruleDef =
typeof ruleDef === "object"
? Object.assign(ruleDef, ruleFromRuleSetsArg)
: Object.keys(ruleFromRuleSetsArg).length > 0
? ruleFromRuleSetsArg
: ruleDef;
? ruleFromRuleSetsArg
: ruleDef;
}
// Add in the list of rules to test , except if it is disabled
if (!(ruleDef === "off" || ruleDef.disabled === true || ruleDef.enabled === false)) {
Expand Down
Loading

0 comments on commit f12674e

Please sign in to comment.