@zohodesk/codestandard-validator 0.0.6-exp-18 → 0.0.6-exp-21

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.
@@ -7,12 +7,13 @@ const fs = require('fs');
7
7
  const path = require('path');
8
8
  const {
9
9
  getEslintExecutablePath
10
- } = require('../../utils/EslintConfigFileUtils/getEslintExecutablePath');
10
+ } = require('../../utils/ConfigFileUtils/getEslintExecutablePath');
11
11
  const {
12
12
  getNodeModulesPath
13
13
  } = require('../../utils/General/getNodeModulesPath');
14
14
  const {
15
- filterFiles
15
+ filterFiles,
16
+ filterWarningInFile
16
17
  } = require('../../utils/FileAndFolderOperations/filterFiles');
17
18
  const {
18
19
  Logger
@@ -35,276 +36,176 @@ const {
35
36
  shouldWarningsAbortCommit
36
37
  } = getConfigurationPrecommit();
37
38
 
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() {
39
+ /* ------------------------------------------
40
+ Git Helpers
41
+ ------------------------------------------ */
42
+
43
+ function isMergeCommit() {
43
44
  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
- }
45
+ exec('git rev-parse -q --verify MERGE_HEAD', (err, stderr, stdout) => {
46
+ if (err) return reject(err.toString().trim());
47
+ resolve((stdout || stderr).trim());
52
48
  });
53
49
  });
54
50
  }
55
-
56
- /**
57
- * @function {getStagedFiles} - methods return staged files
58
- * @returns {Array<string>} - array of files
59
- */
60
-
61
- async function getStagedFiles() {
51
+ function getStagedFiles() {
62
52
  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
- }
53
+ exec('git diff --staged --name-only', (err, stderr, stdout) => {
54
+ if (err) return reject("Couldn't fetch staged files");
55
+ const output = stderr || stdout;
56
+ if (!output.trim()) return resolve([]);
57
+ resolve(filterDeletedFiles(output.trim().split('\n')));
71
58
  });
72
59
  });
73
60
  }
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
- });
61
+ function filterDeletedFiles(files) {
62
+ return files.filter(file => fs.existsSync(path.resolve(getRootDirectory(), file)));
88
63
  }
89
64
 
90
- /**
91
- * @function findEslintErrors - method Lint given file based on given configuration
92
- * @param {*} file - path of file to lint
93
- * @returns {Array<string>} - array of command line report as a string
94
- */
65
+ /* ------------------------------------------
66
+ Lint Helpers
67
+ ------------------------------------------ */
95
68
 
96
- async function findEslintErrors(file) {
97
- let nodeModulesPathOfProject = `${getNodeModulesPath()}`;
98
- let eslintExecutablePath = getEslintExecutablePath();
99
- let eslintConfigurationFilePath = `${nodeModulesPathOfProject}/.eslintrc.js`;
100
- let isEslintExecutablePresent = fs.existsSync(eslintExecutablePath) ? true : false;
101
- let isNodeModulesPresent = fs.existsSync(nodeModulesPathOfProject);
102
- if (isNodeModulesPresent) {
103
- if (isEslintExecutablePresent) {
104
- return new Promise((resolve, reject) => {
105
- exec(`npx --ignore-existing "${eslintExecutablePath}" --config "${eslintConfigurationFilePath}" --no-inline-config --resolve-plugins-relative-to="${nodeModulesPathOfProject}/node_modules" ${file}`, (error, stderr, stdout) => {
106
- if (stderr) {
107
- resolve(stderr.trim().split('\n'));
108
- } else if (error) {
109
- Logger.log(Logger.FAILURE_TYPE, error);
110
- reject("Error executing eslint command");
111
- } else {
112
- resolve([]);
113
- }
114
- });
115
- });
116
- } else {
117
- Logger.log(Logger.INFO_TYPE, 'Eslint executable not found. make sure eslint plugin is installed');
118
- }
119
- } else {
120
- Logger.log(Logger.INFO_TYPE, 'node_modules not found');
69
+ function lintFiles(filePath) {
70
+ const ext = path.extname(filePath);
71
+ if (['.js', '.ts', '.tsx', '.jsx'].includes(ext)) {
72
+ return findEslintErrors(filePath);
73
+ }
74
+ if (['.css', '.scss'].includes(ext)) {
75
+ return findStyleLintErrors(filePath);
121
76
  }
77
+ return Promise.resolve([]);
122
78
  }
123
- /**
124
- * @function {calculateGitDiffForFile} - method calculate diff of file
125
- * @param {*} branch_name - branch name
126
- * @param {*} file - path of file
127
- * @returns {Promise<Array<string>>} - array of command line report as a string
128
- */
129
- async function calculateGitDiffForFile(branch_name, file) {
130
- let gitDiffCommand = `git diff -U0 ${branch_name.trim()} ${file}`;
79
+ function findStyleLintErrors(filePath) {
80
+ const config = path.resolve(getNodeModulesPath(), '.stylelintrc.js');
81
+ const absolutePath = path.join(getRootDirectory(), filePath);
131
82
  return new Promise((resolve, reject) => {
132
- exec(gitDiffCommand, (error, stderr) => {
133
- if (stderr) {
134
- resolve(stderr.trim().split('\n'));
135
- } else if (error) {
136
- reject(error);
83
+ exec(`npx stylelint ${absolutePath} --config ${config}`, {
84
+ cwd: getNodeModulesPath()
85
+ }, (err, stderr) => {
86
+ if (stderr) return resolve(stderr.trim().split('\n'));
87
+ if (err) {
88
+ Logger.log(Logger.FAILURE_TYPE, err);
89
+ return reject('Error executing stylelint command');
137
90
  }
91
+ resolve([]);
92
+ });
93
+ }).catch(err => {
94
+ Logger.log(Logger.FAILURE_TYPE, 'Issue linting CSS files');
95
+ return [];
96
+ });
97
+ }
98
+ function findEslintErrors(filePath) {
99
+ const eslintPath = getEslintExecutablePath();
100
+ const nodeModulesPath = getNodeModulesPath();
101
+ const eslintConfig = `${nodeModulesPath}/.eslintrc.js`;
102
+ if (!fs.existsSync(eslintPath)) {
103
+ Logger.log(Logger.INFO_TYPE, 'Eslint executable not found. Ensure eslint plugin is installed.');
104
+ return Promise.resolve([]);
105
+ }
106
+ return new Promise((resolve, reject) => {
107
+ const cmd = `npx --ignore-existing "${eslintPath}" --config "${eslintConfig}" --no-inline-config --resolve-plugins-relative-to="${nodeModulesPath}/node_modules" ${filePath}`;
108
+ exec(cmd, (err, stderr) => {
109
+ if (stderr) return resolve(stderr.trim().split('\n'));
110
+ if (err) {
111
+ Logger.log(Logger.FAILURE_TYPE, err);
112
+ return reject('Error executing eslint command');
113
+ }
114
+ resolve([]);
115
+ });
116
+ });
117
+ }
118
+ function calculateGitDiffForFile(branch, file) {
119
+ return new Promise((resolve, reject) => {
120
+ exec(`git diff -U0 ${branch.trim()} ${file}`, (err, stderr) => {
121
+ if (stderr) return resolve(stderr.trim().split('\n'));
122
+ if (err) return reject(err);
138
123
  });
139
124
  });
140
125
  }
141
- /**
142
- * @function {areAllPluginsInstalled} - method whether plugin is installed or not
143
- * @returns {Boolean} - return boolean based on plugin installed or not
144
- */
126
+
127
+ /* ------------------------------------------
128
+ Utility
129
+ ------------------------------------------ */
145
130
 
146
131
  function areAllPluginsInstalled() {
147
- let unInstalledPlugins = checkIfPluginsAreInstalled().uninstalledPlugins;
148
- console.log("unInstalledPlugins", unInstalledPlugins);
149
- return unInstalledPlugins.length === 0 ? true : false;
132
+ const {
133
+ uninstalledPlugins
134
+ } = checkIfPluginsAreInstalled();
135
+ console.log('unInstalledPlugins', uninstalledPlugins);
136
+ return uninstalledPlugins.length === 0;
150
137
  }
151
-
152
- /**
153
- * @function {isOnlyWarningsPresentInFile} - method that checks if only eslint warnings are present in a file
154
- * @returns {Boolean} - returns boolean based on only warnings present or not in file
155
- */
156
- function isOnlyWarningsPresentInFile(eslintErrorsPresent) {
157
- let severityOfEachErrorInFile = [];
158
- eslintErrorsPresent.map(error => {
159
- let partsInString = error.split(" ");
160
- let severityOfError = partsInString.find(word => word === 'error' || word === 'warning');
161
- severityOfEachErrorInFile.push(severityOfError);
162
- });
163
- return !severityOfEachErrorInFile.includes('error');
138
+ function isOnlyWarningsPresent(errors) {
139
+ const severities = errors.map(e => e.split(' ').find(w => w === 'error' || w === 'warning'));
140
+ return !severities.includes('error');
164
141
  }
165
142
 
166
- /**
167
- * @function {preCommitHook} - method execute pre commit hook
168
- * @returns {void}
169
- */
143
+ /* ------------------------------------------
144
+ Main Execution
145
+ ------------------------------------------ */
170
146
 
171
147
  async function preCommitHook() {
172
148
  Logger.log(Logger.INFO_TYPE, 'Executing pre commit hook...');
173
- Logger.log(Logger.INFO_TYPE, `working dir : ${process.cwd()}`);
149
+ Logger.log(Logger.INFO_TYPE, `Working directory: ${process.cwd()}`);
174
150
  try {
175
- let isMerge = await isMergeCommit();
176
- Logger.log(Logger.INFO_TYPE, 'Looks like you have merged. So skipping pre commit check');
151
+ await isMergeCommit();
152
+ Logger.log(Logger.INFO_TYPE, 'Looks like you have merged. So skipping pre-commit check');
177
153
  process.exit(0);
178
- } catch (error) {
179
- if (areAllPluginsInstalled()) {
180
- let staged_files = [];
181
- let eslintConfigFiles = ['.eslintrc.js'];
182
- let exemptionFiles = [];
183
- let current_branch = '';
184
- let hasEslintErrorsInChangedLines = false;
185
- let hasEslintErrorsInFiles = false;
186
- let areFilesStaged = false;
187
- let shouldAbortCommit = false;
188
- try {
189
- current_branch = await getBranchName();
190
- } catch {
191
- Logger.log(Logger.INFO_TYPE, "Error fetching current branch");
192
- }
154
+ } catch {
155
+ if (!areAllPluginsInstalled()) {
156
+ Logger.log(Logger.FAILURE_TYPE, 'Commit failed due to missing eslint plugins');
157
+ Logger.log(Logger.INFO_TYPE, `Run \x1b[37mnpx ZDPrecommit setupPlugins\x1b[33m in the project root`);
158
+ process.exit(1);
159
+ }
160
+ let files = await getStagedFiles();
161
+ if (files.length === 0) {
162
+ Logger.log(Logger.INFO_TYPE, 'No files staged. Stage files before committing.');
163
+ return;
164
+ }
165
+ const currentBranch = await getBranchName().catch(() => '');
166
+ const filteredFiles = filterFiles(files, ['.eslintrc.js'], true);
167
+ let shouldAbort = false;
168
+ for (const file of filteredFiles) {
169
+ if (!getSupportedLanguage().includes(path.extname(file))) continue;
193
170
  try {
194
- staged_files = await getStagedFiles();
195
- if (!staged_files.length == 0) {
196
- staged_files = filterFiles(staged_files, eslintConfigFiles, true);
197
-
198
- // staged_files = filterFiles(staged_files,exemptionFiles) //this is the code for giving exemption to a file during pre commit
199
- // if(staged_files.length === 0){
200
- // Logger.log(Logger.SUCCESS_TYPE,`Commit Successful`)
201
- // process.exit(0)
202
- // }
203
- areFilesStaged = true;
204
- for (let file in staged_files) {
205
- let currentFileName = staged_files[file];
206
- let changedLinesArray = [];
207
- let eslintErrorsInChangedLines = [];
208
- let isOnlyEslintWarningsPresentInFile = false;
209
- if (getSupportedLanguage().includes(path.extname(staged_files[file]))) {
210
- try {
211
- var eslintErrorsInFile = await findEslintErrors(staged_files[file]);
212
- // eslintErrorsInFile = impactBasedPrecommit == false ? filterWarningInFile(eslintErrorsInFile) : eslintErrorsInFile
213
- if (staged_files[file] && typeof staged_files[file] == 'string') {
214
- if (!eslintErrorsInFile.length == 0) {
215
- //Calculating changed lines in a file and storing them in respective arrays
216
- if (impactBasedPrecommit) {
217
- //git diff is computed and stored in an array
218
- let git_diff = await calculateGitDiffForFile(current_branch, staged_files[file]);
219
- changedLinesArray = git_diff.filter(line => line.startsWith('@@'));
220
- let changedLinesStartArray = [];
221
- let changedLinesEndArray = [];
222
- for (let number of changedLinesArray) {
223
- let changesStartLine = parseInt(number.split(' ')[2].split(',')[0]);
224
- changedLinesStartArray.push(changesStartLine);
225
- let changesEndLine = number.split(' ')[2].split(',')[1];
226
- if (changesEndLine === undefined) {
227
- changedLinesEndArray.push(changesStartLine);
228
- } else {
229
- changedLinesEndArray.push(changesStartLine + parseInt(changesEndLine) - 1);
230
- }
231
- }
232
- for (let error = 1; error < eslintErrorsInFile.length - 2; error++) {
233
- //eslintErrorsInFile[error].trim() - 69:26 error => Do not hardcode content. Use I18N key instead no-hardcoding/no-hardcoding,
234
- //eslintErrorsInFile[error].trim().split(' ')[0] => 69:26
235
- //eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0] => 69
236
-
237
- let eslintErrorLineNumber = eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0];
238
- for (let lineNumber in changedLinesStartArray) {
239
- if (eslintErrorLineNumber >= changedLinesStartArray[lineNumber] && eslintErrorLineNumber <= changedLinesEndArray[lineNumber]) {
240
- eslintErrorsInChangedLines.push(eslintErrorsInFile[error]);
241
- }
242
- }
243
- }
244
- if (eslintErrorsInChangedLines.length > 0) {
245
- isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(eslintErrorsInChangedLines);
246
- Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
247
- for (let eslintError of eslintErrorsInChangedLines) {
248
- Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
249
- }
250
- if (shouldWarningsAbortCommit) {
251
- hasEslintErrorsInChangedLines = true;
252
- shouldAbortCommit = true;
253
- } else if (!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile) {
254
- hasEslintErrorsInChangedLines = false;
255
- } else if (!shouldWarningsAbortCommit && !isOnlyEslintWarningsPresentInFile) {
256
- hasEslintErrorsInChangedLines = true;
257
- shouldAbortCommit = true;
258
- }
259
- }
260
- } else {
261
- if (eslintErrorsInFile.length > 0) {
262
- let startIndex = 1;
263
- let endIndex = eslintErrorsInFile.length - 2;
264
- let listOsEslintErrors = eslintErrorsInFile.slice(startIndex, endIndex);
265
- isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(listOsEslintErrors);
266
- Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
267
- for (let eslintError of listOsEslintErrors) {
268
- Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
269
- }
270
- if (shouldWarningsAbortCommit) {
271
- hasEslintErrorsInFiles = true;
272
- shouldAbortCommit = true;
273
- } else if (!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile) {
274
- hasEslintErrorsInFiles = false;
275
- } else if (!shouldWarningsAbortCommit && !isOnlyEslintWarningsPresentInFile) {
276
- hasEslintErrorsInFiles = true;
277
- shouldAbortCommit = true;
278
- }
279
- }
280
- }
281
- }
282
- }
283
- } catch (err) {
284
- Logger.log(Logger.FAILURE_TYPE, err);
285
- Logger.log(Logger.FAILURE_TYPE, "Error in executing eslint command");
286
- }
171
+ const lintResults = await lintFiles(file);
172
+ if (lintResults.length === 0) continue;
173
+ let relevantErrors = [];
174
+ if (impactBasedPrecommit) {
175
+ const gitDiff = await calculateGitDiffForFile(currentBranch, file);
176
+ const changeHunks = gitDiff.filter(line => line.startsWith('@@'));
177
+ const ranges = changeHunks.map(h => {
178
+ const start = parseInt(h.split(' ')[2].split(',')[0]);
179
+ const len = parseInt(h.split(' ')[2].split(',')[1]) || 1;
180
+ return [start, start + len - 1];
181
+ });
182
+ for (const error of lintResults.slice(1, -2)) {
183
+ const lineNum = parseInt(error.trim().split(' ')[0].split(':')[0]);
184
+ if (ranges.some(([start, end]) => lineNum >= start && lineNum <= end)) {
185
+ relevantErrors.push(error);
287
186
  }
288
187
  }
289
- } else if (staged_files.length === 0) {
290
- Logger.log(Logger.INFO_TYPE, 'No files have been staged. Stage your files before committing');
188
+ } else {
189
+ relevantErrors = lintResults.slice(1, -2);
291
190
  }
292
- } catch {
293
- Logger.log(Logger.INFO_TYPE, 'Error executing pre commit hook');
294
- }
295
- if (shouldAbortCommit) {
296
- Logger.log(Logger.FAILURE_TYPE, `There are eslint errors/warnings present. So commit is aborted.`);
297
- process.exit(1);
298
- } else if (shouldAbortCommit === false && staged_files.length !== 0) {
299
- Logger.log(Logger.SUCCESS_TYPE, `Commit Successful`);
300
- process.exit(0);
191
+ if (relevantErrors.length) {
192
+ const onlyWarnings = isOnlyWarningsPresent(relevantErrors);
193
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${file}\x1b[0m`);
194
+ relevantErrors.forEach(e => Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${e.trimEnd()}\x1b[0m`));
195
+ if (shouldWarningsAbortCommit || !onlyWarnings) {
196
+ shouldAbort = true;
197
+ }
198
+ }
199
+ } catch (err) {
200
+ Logger.log(Logger.FAILURE_TYPE, err);
301
201
  }
302
- } else {
303
- Logger.log(Logger.FAILURE_TYPE, 'Commit failed since some eslint plugins are not installed');
304
- 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`);
305
- Logger.log(Logger.INFO_TYPE, 'Execute the command and kindly try committing again.');
202
+ }
203
+ if (shouldAbort) {
204
+ Logger.log(Logger.FAILURE_TYPE, 'There are eslint errors/warnings. Aborting commit.');
306
205
  process.exit(1);
307
206
  }
207
+ Logger.log(Logger.SUCCESS_TYPE, 'Commit Successful');
208
+ process.exit(0);
308
209
  }
309
210
  }
310
211
  preCommitHook();