Skip to content

Commit

Permalink
Use os.EOL
Browse files Browse the repository at this point in the history
  • Loading branch information
nvuillam committed Jul 9, 2020
1 parent dd8b987 commit 0b11ec3
Show file tree
Hide file tree
Showing 13 changed files with 50 additions and 26 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## [5.4.2] 2020-07-09

- Use os.EOL [(#65)](https://github.com/nvuillam/npm-groovy-lint/pull/65) solving [(#63)](https://github.com/nvuillam/npm-groovy-lint/issues/63) --fix for indentation adds CRLF line-endings to all files it touches

## [5.4.1] 2020-07-01

- CodeNarcServer listens to localhost only [(#59)](https://github.com/nvuillam/npm-groovy-lint/pull/59) solving [(#56)](https://github.com/nvuillam/npm-groovy-lint/issues/56)
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -325,17 +325,21 @@ This package uses :
## RELEASE NOTES
## [5.4.1] 2020-07-01
### [5.4.2] 2020-07-09
- Use os.EOL [(#65)](https://github.com/nvuillam/npm-groovy-lint/pull/65) solving [(#63)](https://github.com/nvuillam/npm-groovy-lint/issues/63) --fix for indentation adds CRLF line-endings to all files it touches
### [5.4.1] 2020-07-01
- CodeNarcServer listens to localhost only [(#59)](https://github.com/nvuillam/npm-groovy-lint/pull/59) solving [(#56)](https://github.com/nvuillam/npm-groovy-lint/issues/56)
- Replace @analytics/segment with @amplitude/node for anonymous stats
## [5.3.0] 2020-06-29
### [5.3.0] 2020-06-29
- New option **--failon** , replacing `--failonerror`,`--failonwarning` and `--failoninfo`. It can take error, warning or info values (default: none). Previous options remain working but are deprecated and will be removed in a future major version
- Update help for `--fixrules` option
## [5.1.0] 2020-06-04
### [5.1.0] 2020-06-04
- Install Java 8 using node-jre in case java version found is higher than Java 11 (CodeNarc compatibility is Java 8 to 11)
Expand Down
4 changes: 2 additions & 2 deletions lib/codenarc-factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const xml2js = require("xml2js");
const { getConfigFileName } = require("./config.js");
const { collectDisabledBlocks, isFilteredError } = require("./filter.js");
const { getNpmGroovyLintRules } = require("./groovy-lint-rules.js");
const { evaluateRange, evaluateVariables, getSourceLines } = require("./utils.js");
const { evaluateRange, evaluateVariables, getSourceLines, normalizeNewLines } = require("./utils.js");

////////////////////////////
// Build codenarc options //
Expand Down Expand Up @@ -46,7 +46,7 @@ async function prepareCodeNarcCall(options) {
cnFiles = "**/" + tmpFileNm;
}

await fse.writeFile(result.tmpGroovyFileName, options.source.replace(/\r?\n/g, "\r\n"));
await fse.writeFile(result.tmpGroovyFileName, normalizeNewLines(options.source));
debug(`CREATE GROOVY temp file ${result.tmpGroovyFileName} with input source, as CodeNarc requires physical files`);
}

Expand Down
3 changes: 2 additions & 1 deletion lib/groovy-lint-fix.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
const fse = require("fs-extra");
const cliProgress = require("cli-progress");
const debug = require("debug")("npm-groovy-lint");
const os = require("os");
const { getNpmGroovyLintRules, getFormattingRulesToAlwaysRun } = require("./groovy-lint-rules.js");
const { evaluateVariables, getSourceLines } = require("./utils.js");

Expand Down Expand Up @@ -208,7 +209,7 @@ class NpmGroovyLintFix {
);
fixedInFileNb = fixedInFileNb + fixedNb;
}
const newSources = allLines.join("\r\n");
const newSources = allLines.join(os.EOL);
this.updatedLintResult.files[fileNm].updatedSource = newSources;
// Write new file content if it has been updated
if (this.options.save && fixedInFileNb > 0) {
Expand Down
3 changes: 2 additions & 1 deletion lib/groovy-lint.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

// Imports
const debug = require("debug")("npm-groovy-lint");
const os = require("os");
const performance = require("perf_hooks").performance;

const NpmGroovyLintFix = require("./groovy-lint-fix");
Expand Down Expand Up @@ -183,7 +184,7 @@ class NpmGroovyLint {
versions.push("Embeds:");
versions.push(`- CodeNarc version ${NPM_GROOVY_LINT_CONSTANTS["CodeNarcVersion"]}`);
versions.push(`- Groovy version ${NPM_GROOVY_LINT_CONSTANTS["GroovyVersion"]} (superlite)`);
const versionsOut = versions.join("\n");
const versionsOut = versions.join(os.EOL);
console.info(versionsOut);
this.outputString = versionsOut;
return false;
Expand Down
2 changes: 2 additions & 0 deletions lib/rules/BlankLineBeforePackage.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const rule = {
const lineNumber = getVariable(variables, "lineNb", { mandatory: true });
if (allLines[lineNumber].trim() === "") {
allLines.splice(lineNumber, 1);
} else if (allLines[lineNumber + 1].trim() === "") {
allLines.splice(lineNumber + 1, 1);
}
return allLines;
}
Expand Down
8 changes: 4 additions & 4 deletions lib/rules/DuplicateImport.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ import javax.swing.JFileChooser
import java.util.regex.Matcher
import f.g.h.I
class SaMere {
class Wesh {
Matcher inputZ
}
class SaMere2 {
class Gros {
JFileChooser inputX
}
`,
Expand All @@ -51,11 +51,11 @@ import a.b.c.D
import f.g.h.I
class SaMere {
class Wesh {
Matcher inputZ
}
class SaMere2 {
class Gros {
JFileChooser inputX
}
`
Expand Down
3 changes: 2 additions & 1 deletion lib/rules/FileEndsWithoutNewline.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// File ends without new line
const os = require("os");

const rule = {
scope: "file",
Expand All @@ -7,7 +8,7 @@ const rule = {
label: "Add new line at the end of file",
type: "function",
func: allLines => {
return (allLines.join("\r\n") + "\r\n").split("\r\n");
return (allLines.join(os.EOL) + os.EOL).split(os.EOL);
}
},
tests: [
Expand Down
9 changes: 5 additions & 4 deletions lib/rules/UnusedImport.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,22 +39,23 @@ import javax.swing.notkept.filechooser.FileFilter
import javax.swing.JFileChooser
import org.apache.commons.lang3.notkept.SystemUtils
class SaMere {
class Wesh {
Matcher inputZ
}
class SaMere2 {
class Gros {
JFileChooser inputX
}
`,
sourceAfter: `
import java.util.regex.Matcher
import javax.swing.JFileChooser
class SaMere {
class Wesh {
Matcher inputZ
}
class SaMere2 {
class Gros {
JFileChooser inputX
}
`
Expand Down
2 changes: 1 addition & 1 deletion lib/test/helpers/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async function copyFilesInTmpDir() {
// Get diff between 2 strings
function getDiff(expected, afterUpdate, beforeUpdate) {
const diff = jsdiff.diffChars(expected, afterUpdate);
const effectiveDiffs = diff.filter(item => (item.added || item.removed) && ![`\r`, `\r\n`].includes(item.value));
const effectiveDiffs = diff.filter(item => item.added || item.removed);
if (effectiveDiffs.length > 0) {
console.error("BeforeFix: \n" + beforeUpdate);
console.error("AfterFix: \n" + afterUpdate);
Expand Down
5 changes: 3 additions & 2 deletions lib/test/lint-fix.rules.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"use strict";
const NpmGroovyLint = require("../groovy-lint.js");
const { getNpmGroovyLintRules } = require("../groovy-lint-rules.js");
const { normalizeNewLines } = require("../utils.js");
let assert = require("assert");

const { beforeEachTestCase, checkCodeNarcCallsCounter, getDiff } = require("./helpers/common");
Expand Down Expand Up @@ -40,7 +41,7 @@ describe("Check rules auto-fixes", () => {
async function checkRuleFix(ruleName, testRule) {
let fixRules = ruleName;
// Call linter & fixer
const source = testRule.sourceBefore.replace(/\r?\n/g, "\r\n");
const source = normalizeNewLines(testRule.sourceBefore);
const npmGroovyLintConfig = {
source: source,
rulesets: fixRules,
Expand All @@ -64,7 +65,7 @@ async function checkRuleFix(ruleName, testRule) {
assert(err == null, "No crash during NpmGroovyLint run");
assert(linter.status === 0, `Linter status is 0 (${linter.status} returned)`);
const updatedSource = linter.lintResult.files[0].updatedSource;
const effectiveDiffs = getDiff(testRule.sourceAfter, updatedSource, source);
const effectiveDiffs = getDiff(normalizeNewLines(testRule.sourceAfter), updatedSource, source);
assert(effectiveDiffs.length === 0, `Fix result is not the one expected.\n Diff: \n${JSON.stringify(effectiveDiffs, null, 2)}`);
checkCodeNarcCallsCounter(testRule.codeNarcCallsNumber || 1);
}
5 changes: 3 additions & 2 deletions lib/test/lint-format.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const NpmGroovyLint = require("../groovy-lint.js");
let assert = require("assert");
const fse = require("fs-extra");
const { normalizeNewLines } = require("../utils.js");
const rimraf = require("rimraf");
const {
beforeEachTestCase,
Expand Down Expand Up @@ -110,7 +111,7 @@ describe("Format with API", function() {
});

async function checkRule(key, check) {
const source = check.before;
const source = normalizeNewLines(check.before);
const moreOptions = check.moreOptions ? check.moreOptions : {};
const npmGroovyLintConfig = Object.assign(
{
Expand All @@ -130,7 +131,7 @@ async function checkRule(key, check) {
`${check.totalFixed} Errors have been fixed (${linter.lintResult.summary.totalFixedNumber} returned)`
);
const result = linter.lintResult.files[0].updatedSource;
const expectedResult = check.after;
const expectedResult = normalizeNewLines(check.after);
const effectiveDiff = getDiff(expectedResult, result, source);
assert(linter.status === 0, `Linter status is 0 (${linter.status} returned)`);
assert(effectiveDiff.length === 0, "Code has been formatted correctly");
Expand Down
18 changes: 13 additions & 5 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
const debug = require("debug")("npm-groovy-lint");
const decodeHtml = require("decode-html");
const fse = require("fs-extra");
const os = require("os");

function addImport(allLineLs, classToImport) {
// Check if import is already there
Expand Down Expand Up @@ -214,10 +215,7 @@ function getOutOfBracesStrings(str, exclude = []) {
// Split source lines to analyse
async function getSourceLines(source, fileNm) {
let fileContent = source || (await fse.readFile(fileNm));
return fileContent
.toString()
.replace(/\r?\n/g, "\r\n")
.split("\r\n");
return normalizeNewLines(fileContent.toString()).split(os.EOL);
}

// Get range of the first occurrence of a substring or regex in a string
Expand Down Expand Up @@ -327,6 +325,15 @@ function moveOpeningBracket(allLines, variables) {
return allLines;
}

function normalizeNewLines(str) {
let normalizedString = str + "";
normalizedString = str.replace(/\r/g, "");
normalizedString = normalizedString.replace(/\n/g, os.EOL);
return normalizedString;
}

// Utils of utils :)

// Check if a substring is between quotes in a string
function notBetweenQuotesOrComment(str, substr) {
const singleQuotesMatch = str.match(/'(.*?)'/) || [];
Expand Down Expand Up @@ -382,5 +389,6 @@ module.exports = {
getVariable,
getVariableRange,
isValidCodeLine,
moveOpeningBracket
moveOpeningBracket,
normalizeNewLines
};

0 comments on commit 0b11ec3

Please sign in to comment.