@zohodesk/codestandard-validator 1.0.0-exp-2 → 1.0.0-exp-4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,10 +41,10 @@ async function preCommitHook() {
41
41
  const branch = await safeGetBranch();
42
42
  const shouldAbort = await runLintWorkflow(JsFiles, branch);
43
43
  if (shouldAbort) {
44
- Logger.log(Logger.FAILURE_TYPE, "There are linter errors/warnings. Commit aborted.");
44
+ Logger.log(Logger.FAILURE_TYPE, "There are linter errors/warnings. Commit aborted 🙁.");
45
45
  process.exit(1);
46
46
  }
47
- Logger.log(Logger.SUCCESS_TYPE, "Commit Successful");
47
+ Logger.log(Logger.SUCCESS_TYPE, `Code is good to go 🙂`);
48
48
  process.exit(0);
49
49
  }
50
50
  preCommitHook();
@@ -4,8 +4,22 @@ const {
4
4
  Logger
5
5
  } = require("../../utils/Logger/Logger");
6
6
  const {
7
- calculateGitDiffForFile
8
- } = require("./lint");
7
+ exec
8
+ } = require('child_process');
9
+ const {
10
+ promisify
11
+ } = require('util');
12
+ const execAsync = promisify(exec);
13
+ async function calculateGitDiffForFile(branch, file) {
14
+ try {
15
+ const {
16
+ stdout
17
+ } = await execAsync(`git diff -U0 ${branch.trim()} ${file}`);
18
+ return stdout;
19
+ } catch (err) {
20
+ throw err;
21
+ }
22
+ }
9
23
  function parseDiffHunks(diff) {
10
24
  return diff.filter(line => line.startsWith("@@")).map(hunk => {
11
25
  const [start, count = 1] = hunk.split(" ")[2].slice(1).split(",").map(Number);
@@ -20,10 +34,6 @@ async function filterErrorsByChangedLines(errors, branch, file) {
20
34
  return changedRanges.some(([s, e]) => line >= s && line <= e);
21
35
  });
22
36
  }
23
- async function createBranchDiff(diff) {
24
- // const diff = await calculateGitDiffForFile(branch, file);
25
- // const changeset = extractDiffHunks(diff)
26
- }
27
37
  function filterFileLevelErrors(errors) {
28
38
  return errors.slice(1, -2); // strip ESLint summary lines
29
39
  }
@@ -35,5 +45,6 @@ module.exports = {
35
45
  filterErrorsByChangedLines,
36
46
  filterFileLevelErrors,
37
47
  logErrors,
38
- parseDiffHunks
48
+ parseDiffHunks,
49
+ calculateGitDiffForFile
39
50
  };
@@ -21,9 +21,7 @@ const {
21
21
  getSupportedLanguage
22
22
  } = require('../../utils/General/getGeneralInfo');
23
23
  const {
24
- filterFileLevelErrors,
25
- filterErrorsByChangedLines,
26
- logErrors
24
+ calculateGitDiffForFile
27
25
  } = require('./errorhelpers');
28
26
  const {
29
27
  Execution,
@@ -36,6 +34,12 @@ const {
36
34
  const {
37
35
  extractDiffHunks
38
36
  } = require('./utils');
37
+ const {
38
+ Logger
39
+ } = require('../../utils/Logger/Logger');
40
+ const {
41
+ default: fetchProjectIssuesViaCurl
42
+ } = require('../../utils/General/SonarQubeUtil');
39
43
  const execAsync = promisify(exec);
40
44
  async function lintFiles(filePath) {
41
45
  const ext = path.extname(filePath);
@@ -79,21 +83,10 @@ function findStyleLintErrors(filePath) {
79
83
  return [];
80
84
  });
81
85
  }
82
- async function calculateGitDiffForFile(branch, file) {
83
- try {
84
- const {
85
- stdout
86
- } = await execAsync(`git diff -U0 ${branch.trim()} ${file}`);
87
- return stdout;
88
- } catch (err) {
89
- throw err;
90
- }
91
- }
92
86
  async function runLintWorkflow(files, branch) {
93
87
  const branchDiff = {
94
88
  diffs: []
95
89
  };
96
- let shouldAbort = false;
97
90
  var branchName = getBranchName();
98
91
  for (const file of files) {
99
92
  if (!getSupportedLanguage().includes(path.extname(file))) continue;
@@ -104,30 +97,31 @@ async function runLintWorkflow(files, branch) {
104
97
  diff: changeset
105
98
  };
106
99
  branchDiff.diffs.push(diff);
107
- // const filteredErrors = impactBasedPrecommit
108
- // ? await filterErrorsByChangedLines(errors, branch, file)
109
- // : filterFileLevelErrors(errors);
110
-
111
- // if (filteredErrors.length > 0) {
112
- // logErrors(file, filteredErrors);
113
- // shouldAbort ||= shouldWarningsAbortCommit || !isOnlyWarnings(filteredErrors);
114
- // }
115
100
  }
116
101
  const diffPath = path.resolve(getNodeModulesPath(), 'diffBranch.json');
117
- fs.writeFileSync(diffPath, JSON.stringify(diffPath));
102
+ fs.writeFileSync(diffPath, JSON.stringify(branchDiff));
118
103
  const cliobj = {
119
104
  env: 'ci',
120
- cmdExecuted: 'dev-ci'
105
+ cmdExecuted: 'precommit'
121
106
  };
122
107
  const execute = new Execution(EsLint, SonarQube, cliobj);
123
- await execute.executeLintHandler();
124
- await execute.executeMetricHandler();
108
+ await execute.executeLintHandler().finally(async () => {
109
+ await execute.executeMetricHandler();
110
+ /**
111
+ * global.analytics.totalIssues = global.analytics.totalIssues + 1;
112
+ global.analytics.status = "FAILURE";
113
+ global.analytics.message = 'Issues are detected, please review and resolve the errors'
114
+ */
115
+ const {
116
+ issues,
117
+ hasIssue,
118
+ totalIssues
119
+ } = fetchProjectIssuesViaCurl("projectName");
120
+ });
121
+ Logger.log(Logger.INFO_TYPE, global.analytics);
125
122
  return global.analytics.status == 'FAILURE' ? true : false;
126
123
  }
127
124
  module.exports = {
128
125
  runLintWorkflow,
129
- lintFiles,
130
- findEslintErrors,
131
- findStyleLintErrors,
132
- calculateGitDiffForFile
126
+ lintFiles
133
127
  };
@@ -0,0 +1,369 @@
1
+ "use strict";
2
+
3
+ const {
4
+ exec
5
+ } = require('child_process');
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const {
9
+ getEslintExecutablePath
10
+ } = require('../../utils/ConfigFileUtils/getEslintExecutablePath');
11
+ const {
12
+ getNodeModulesPath
13
+ } = require('../../utils/General/getNodeModulesPath');
14
+ const {
15
+ filterFiles
16
+ } = require('../../utils/FileAndFolderOperations/filterFiles');
17
+ const {
18
+ Logger
19
+ } = require('../../utils/Logger/Logger');
20
+ const {
21
+ checkIfPluginsAreInstalled
22
+ } = require('../../utils/PluginsInstallation/checkIfPluginsAreInstalled');
23
+ const {
24
+ getBranchName
25
+ } = require('../../utils/GitActions/gitActions');
26
+ const {
27
+ getConfigurationPrecommit,
28
+ getSupportedLanguage
29
+ } = require('../../utils/General/getGeneralInfo');
30
+ const {
31
+ getRootDirectory
32
+ } = require('../../utils/General/RootDirectoryUtils/getRootDirectory');
33
+ const {
34
+ impactBasedPrecommit,
35
+ shouldWarningsAbortCommit
36
+ } = getConfigurationPrecommit();
37
+
38
+ /**
39
+ * @function isMergeCommit - This method check whether it is merge or not
40
+ * @returns {Boolean} - return boolean based on latest merge changes
41
+ */
42
+ async function isMergeCommit() {
43
+ return new Promise((resolve, reject) => {
44
+ exec('git rev-parse -q --verify MERGE_HEAD', (error, stderr, stdout) => {
45
+ if (error) {
46
+ reject(error.toString().trim());
47
+ } else if (stderr) {
48
+ resolve(stderr.trim());
49
+ } else if (stdout) {
50
+ resolve(stdout.trim());
51
+ }
52
+ });
53
+ });
54
+ }
55
+
56
+ /**
57
+ * @function {getStagedFiles} - methods return staged files
58
+ * @returns {Array<string>} - array of files
59
+ */
60
+
61
+ async function getStagedFiles() {
62
+ return new Promise((resolve, reject) => {
63
+ exec("git diff --staged --name-only", (error, stderr, stdout) => {
64
+ if (error) {
65
+ if (error != null) reject("Couldn't fetch staged files");
66
+ } else if (stderr) {
67
+ resolve(filterDeltedFileFromStagedFiles(stderr.trim().split('\n')));
68
+ } else if (stdout.trim() === '') {
69
+ resolve(stdout.trim());
70
+ }
71
+ });
72
+ });
73
+ }
74
+
75
+ /**
76
+ * @function {filterDeltedFileFromStagedFiles} - filter deleted staged files
77
+ * @param {Array<string>} files - staged files
78
+ * @returns
79
+ */
80
+ function filterDeltedFileFromStagedFiles(files) {
81
+ return files.filter(file => {
82
+ const absolutePath = path.resolve(getRootDirectory(), file);
83
+ if (fs.existsSync(absolutePath)) {
84
+ return true;
85
+ }
86
+ return false;
87
+ });
88
+ }
89
+ async function lintFiles(filePath) {
90
+ switch (String(path.extname(filePath))) {
91
+ case '.js':
92
+ case '.ts':
93
+ case '.tsx':
94
+ case '.jsx':
95
+ case '.properties':
96
+ {
97
+ return await findEslintErrors(filePath);
98
+ }
99
+ case '.css':
100
+ case '.scss':
101
+ {
102
+ return await findStyleLintErrors(filePath);
103
+ }
104
+ default:
105
+ {
106
+ return [];
107
+ }
108
+ }
109
+ }
110
+
111
+ /**
112
+ * @function findEslintErrors - method Lint given file based on given configuration
113
+ * @param {*} file - path of file to lint
114
+ * @returns {Array<string>} - array of command line report as a string
115
+ */
116
+
117
+ function findEslintErrors(file) {
118
+ let nodeModulesPathOfProject = `${getNodeModulesPath()}`;
119
+ let eslintExecutablePath = getEslintExecutablePath();
120
+ let eslintConfigurationFilePath = `${nodeModulesPathOfProject}/.eslintrc.js`;
121
+ let isEslintExecutablePresent = fs.existsSync(eslintExecutablePath) ? true : false;
122
+ let isNodeModulesPresent = fs.existsSync(nodeModulesPathOfProject);
123
+ if (isNodeModulesPresent) {
124
+ if (isEslintExecutablePresent) {
125
+ return new Promise((resolve, reject) => {
126
+ exec(`npx --ignore-existing "${eslintExecutablePath}" --config "${eslintConfigurationFilePath}" --no-inline-config --resolve-plugins-relative-to="${nodeModulesPathOfProject}/node_modules" ${file}`, (error, stderr, stdout) => {
127
+ if (stderr) {
128
+ resolve(stderr.trim().split('\n'));
129
+ } else if (error) {
130
+ Logger.log(Logger.FAILURE_TYPE, error);
131
+ reject("Error executing eslint command");
132
+ } else {
133
+ resolve([]);
134
+ }
135
+ });
136
+ });
137
+ } else {
138
+ Logger.log(Logger.INFO_TYPE, 'Eslint executable not found. make sure eslint plugin is installed');
139
+ }
140
+ } else {
141
+ Logger.log(Logger.INFO_TYPE, 'node_modules not found');
142
+ }
143
+ }
144
+
145
+ /**
146
+ *
147
+ * @param {*} params
148
+ */
149
+ function findStyleLintErrors(filePath) {
150
+ const configFilePath = path.resolve(getNodeModulesPath(), '.stylelintrc.js');
151
+ const absolutePath = path.join(getRootDirectory(), filePath);
152
+ try {
153
+ return new Promise((resolve, reject) => {
154
+ exec(`npx stylelint ${absolutePath} --config ${configFilePath}`, {
155
+ cwd: getNodeModulesPath()
156
+ }, (error, stderr, stdout) => {
157
+ if (stdout) {
158
+ resolve(stdout.trim().split('\n'));
159
+ }
160
+ // if(stderr){
161
+ // resolve(stderr.trim().split('\n'))
162
+ // }
163
+ else if (error) {
164
+ Logger.log(Logger.FAILURE_TYPE, error);
165
+ reject("Error executing stylelint command");
166
+ } else {
167
+ resolve([]);
168
+ }
169
+ });
170
+ });
171
+ } catch (error) {
172
+ Logger.log(Logger.FAILURE_TYPE, `Issue is lint css files`);
173
+ return [];
174
+ }
175
+ }
176
+
177
+ /**
178
+ * @function {calculateGitDiffForFile} - method calculate diff of file
179
+ * @param {*} branch_name - branch name
180
+ * @param {*} file - path of file
181
+ * @returns {Promise<Array<string>>} - array of command line report as a string
182
+ */
183
+ async function calculateGitDiffForFile(branch_name, file) {
184
+ let gitDiffCommand = `git diff -U0 ${branch_name.trim()} ${file}`;
185
+ return new Promise((resolve, reject) => {
186
+ exec(gitDiffCommand, (error, stderr) => {
187
+ if (stderr) {
188
+ resolve(stderr.trim().split('\n'));
189
+ } else if (error) {
190
+ reject(error);
191
+ }
192
+ });
193
+ });
194
+ }
195
+ /**
196
+ * @function {areAllPluginsInstalled} - method whether plugin is installed or not
197
+ * @returns {Boolean} - return boolean based on plugin installed or not
198
+ */
199
+
200
+ function areAllPluginsInstalled() {
201
+ let unInstalledPlugins = checkIfPluginsAreInstalled().uninstalledPlugins;
202
+ return unInstalledPlugins.length === 0 ? true : false;
203
+ }
204
+
205
+ /**
206
+ * @function {isOnlyWarningsPresentInFile} - method that checks if only eslint warnings are present in a file
207
+ * @returns {Boolean} - returns boolean based on only warnings present or not in file
208
+ */
209
+ function isOnlyWarningsPresentInFile(eslintErrorsPresent) {
210
+ let severityOfEachErrorInFile = [];
211
+ eslintErrorsPresent.map(error => {
212
+ let partsInString = error.split(" ");
213
+ let severityOfError = partsInString.find(word => word === 'error' || word === 'warning' || word === '✖');
214
+ severityOfEachErrorInFile.push(severityOfError);
215
+ });
216
+ return !(severityOfEachErrorInFile.includes('✖') || severityOfEachErrorInFile.includes('error'));
217
+ }
218
+
219
+ /**
220
+ * @function {preCommitHook} - method execute pre commit hook
221
+ * @returns {void}
222
+ */
223
+
224
+ async function preCommitHook_default() {
225
+ Logger.log(Logger.INFO_TYPE, 'Executing pre commit hook...');
226
+ Logger.log(Logger.INFO_TYPE, `working dir : ${process.cwd()}`);
227
+ try {
228
+ let isMerge = await isMergeCommit();
229
+ Logger.log(Logger.INFO_TYPE, 'Looks like you have merged. So skipping pre commit check');
230
+ process.exit(0);
231
+ } catch (error) {
232
+ if (areAllPluginsInstalled()) {
233
+ let staged_files = [];
234
+ let eslintConfigFiles = ['.eslintrc.js'];
235
+ let exemptionFiles = [];
236
+ let current_branch = '';
237
+ let hasEslintErrorsInChangedLines = false;
238
+ let hasEslintErrorsInFiles = false;
239
+ let areFilesStaged = false;
240
+ let shouldAbortCommit = false;
241
+ try {
242
+ current_branch = await getBranchName();
243
+ } catch {
244
+ Logger.log(Logger.INFO_TYPE, "Error fetching current branch");
245
+ }
246
+ try {
247
+ staged_files = await getStagedFiles();
248
+ if (!staged_files.length == 0) {
249
+ const {
250
+ JsFiles: staged_filesJS,
251
+ CssFiles
252
+ } = filterFiles(staged_files, eslintConfigFiles, true);
253
+
254
+ // staged_filesJS = filterFiles(staged_filesJS,exemptionFiles) //this is the code for giving exemption to a file during pre commit
255
+ // if(staged_filesJS.length === 0){
256
+ // Logger.log(Logger.SUCCESS_TYPE,`Commit Successful`)
257
+ // process.exit(0)
258
+ // }
259
+
260
+ // CssFiles not Enabled For while
261
+ areFilesStaged = true;
262
+ var stagedFiles = [...staged_filesJS];
263
+ for (let file in stagedFiles) {
264
+ let currentFileName = stagedFiles[file];
265
+ let changedLinesArray = [];
266
+ let eslintErrorsInChangedLines = [];
267
+ let isOnlyEslintWarningsPresentInFile = false;
268
+ if (getSupportedLanguage().includes(path.extname(stagedFiles[file]))) {
269
+ try {
270
+ var errorsInFile = await lintFiles(stagedFiles[file]);
271
+ // eslintErrorsInFile = impactBasedPrecommit == false ? filterWarningInFile(errorsInFile) : errorsInFile
272
+ if (stagedFiles[file] && typeof stagedFiles[file] == 'string') {
273
+ if (!errorsInFile.length == 0) {
274
+ //Calculating changed lines in a file and storing them in respective arrays
275
+ if (impactBasedPrecommit) {
276
+ //git diff is computed and stored in an array
277
+ let git_diff = await calculateGitDiffForFile(current_branch, stagedFiles[file]);
278
+ changedLinesArray = git_diff.filter(line => line.startsWith('@@'));
279
+ let changedLinesStartArray = [];
280
+ let changedLinesEndArray = [];
281
+ for (let number of changedLinesArray) {
282
+ let changesStartLine = parseInt(number.split(' ')[2].split(',')[0]);
283
+ changedLinesStartArray.push(changesStartLine);
284
+ let changesEndLine = number.split(' ')[2].split(',')[1];
285
+ if (changesEndLine === undefined) {
286
+ changedLinesEndArray.push(changesStartLine);
287
+ } else {
288
+ changedLinesEndArray.push(changesStartLine + parseInt(changesEndLine) - 1);
289
+ }
290
+ }
291
+ for (let error = 1; error < errorsInFile.length - 2; error++) {
292
+ //errorsInFile[error].trim() - 69:26 error => Do not hardcode content. Use I18N key instead no-hardcoding/no-hardcoding,
293
+ //errorsInFile[error].trim().split(' ')[0] => 69:26
294
+ //errorsInFile[error].trim().split(' ')[0].split(':')[0] => 69
295
+
296
+ let eslintErrorLineNumber = errorsInFile[error].trim().split(' ')[0].split(':')[0];
297
+ for (let lineNumber in changedLinesStartArray) {
298
+ if (eslintErrorLineNumber >= changedLinesStartArray[lineNumber] && eslintErrorLineNumber <= changedLinesEndArray[lineNumber]) {
299
+ eslintErrorsInChangedLines.push(errorsInFile[error]);
300
+ }
301
+ }
302
+ }
303
+ if (eslintErrorsInChangedLines.length > 0) {
304
+ isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(eslintErrorsInChangedLines);
305
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
306
+ for (let eslintError of eslintErrorsInChangedLines) {
307
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
308
+ }
309
+ if (shouldWarningsAbortCommit) {
310
+ hasEslintErrorsInChangedLines = true;
311
+ shouldAbortCommit = true;
312
+ } else if (!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile) {
313
+ hasEslintErrorsInChangedLines = false;
314
+ } else if (!shouldWarningsAbortCommit && !isOnlyEslintWarningsPresentInFile) {
315
+ hasEslintErrorsInChangedLines = true;
316
+ shouldAbortCommit = true;
317
+ }
318
+ }
319
+ } else {
320
+ if (errorsInFile.length > 0) {
321
+ let startIndex = 1;
322
+ let endIndex = errorsInFile.length - 2;
323
+ let listOsEslintErrors = errorsInFile.slice(startIndex, endIndex);
324
+ isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(listOsEslintErrors);
325
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
326
+ for (let eslintError of listOsEslintErrors) {
327
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
328
+ }
329
+ if (shouldWarningsAbortCommit) {
330
+ hasEslintErrorsInFiles = true;
331
+ shouldAbortCommit = true;
332
+ } else if (!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile) {
333
+ hasEslintErrorsInFiles = false;
334
+ } else if (!shouldWarningsAbortCommit && !isOnlyEslintWarningsPresentInFile) {
335
+ hasEslintErrorsInFiles = true;
336
+ shouldAbortCommit = true;
337
+ }
338
+ }
339
+ }
340
+ }
341
+ }
342
+ } catch (err) {
343
+ Logger.log(Logger.FAILURE_TYPE, err);
344
+ Logger.log(Logger.FAILURE_TYPE, "Error in executing lint command");
345
+ }
346
+ }
347
+ }
348
+ } else if (staged_files.length === 0) {
349
+ Logger.log(Logger.INFO_TYPE, 'No files have been staged. Stage your files before committing');
350
+ }
351
+ } catch {
352
+ Logger.log(Logger.INFO_TYPE, 'Error executing pre commit hook');
353
+ }
354
+ if (shouldAbortCommit) {
355
+ Logger.log(Logger.FAILURE_TYPE, `There are linter errors/warnings present. So commit is aborted.`);
356
+ process.exit(1);
357
+ } else if (shouldAbortCommit === false && staged_files.length !== 0) {
358
+ Logger.log(Logger.SUCCESS_TYPE, `Commit Successful`);
359
+ process.exit(0);
360
+ }
361
+ } else {
362
+ Logger.log(Logger.FAILURE_TYPE, 'Commit failed since some lint plugins are not installed');
363
+ Logger.log(Logger.INFO_TYPE, `Kindly execute the command \x1b[37mnpx ZDPrecommit setupPlugins \x1b[33mfrom the location where package.json is present to install the plugins`);
364
+ Logger.log(Logger.INFO_TYPE, 'Execute the command and kindly try committing again.');
365
+ process.exit(1);
366
+ }
367
+ }
368
+ }
369
+ preCommitHook_default();