@zohodesk/codestandard-validator 0.0.2-exp-6 → 0.0.2-exp-8

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.
@@ -12,7 +12,8 @@ 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
@@ -23,6 +24,14 @@ const {
23
24
  const {
24
25
  getBranchName
25
26
  } = require('../../utils/GitActions/gitActions');
27
+ const {
28
+ getConfigurationPrecommit,
29
+ getSupportedLanguage
30
+ } = require('../../utils/General/getGeneralInfo');
31
+ const {
32
+ impactBasedPrecommit,
33
+ shouldWarningsAbortCommit
34
+ } = getConfigurationPrecommit();
26
35
 
27
36
  /**
28
37
  * @function isMergeCommit - This method check whether it is merge or not
@@ -122,6 +131,21 @@ function areAllPluginsInstalled() {
122
131
  return unInstalledPlugins.length === 0 ? true : false;
123
132
  }
124
133
 
134
+ /**
135
+ * @function {isOnlyWarningsPresentInFile} - method that checks if only eslint warnings are present in a file
136
+ * @returns {Boolean} - returns boolean based on only warnings present or not in file
137
+ */
138
+ function isOnlyWarningsPresentInFile(eslintErrorsPresentInFile) {
139
+ let severityOfEachErrorInFile = [];
140
+ let startIndex = 1;
141
+ let endIndex = eslintErrorsPresentInFile.length - 2;
142
+ eslintErrorsPresentInFile.slice(startIndex, endIndex).map(error => {
143
+ let partsInString = error.split(" ");
144
+ severityOfEachErrorInFile.push(partsInString[1]);
145
+ });
146
+ return severityOfEachErrorInFile.includes('error');
147
+ }
148
+
125
149
  /**
126
150
  * @function {preCommitHook} - method execute pre commit hook
127
151
  * @returns {void}
@@ -141,6 +165,7 @@ async function preCommitHook() {
141
165
  let exemptionFiles = [];
142
166
  let current_branch = '';
143
167
  let hasEslintErrorsInChangedLines = false;
168
+ let hasEslintErrorsInFiles = false;
144
169
  let areFilesStaged = false;
145
170
  try {
146
171
  current_branch = await getBranchName();
@@ -162,46 +187,66 @@ async function preCommitHook() {
162
187
  let currentFileName = staged_files[file];
163
188
  let changedLinesArray = [];
164
189
  let eslintErrorsInChangedLines = [];
165
- if (path.extname(staged_files[file]) === '.js') {
190
+ let isOnlyEslintWarningsPresentInFile = false;
191
+ if (getSupportedLanguage().includes(path.extname(staged_files[file]))) {
166
192
  try {
167
- let eslintErrorsInFile = await findEslintErrors(staged_files[file]);
193
+ var eslintErrorsInFile = await findEslintErrors(staged_files[file]);
194
+ // eslintErrorsInFile = impactBasedPrecommit == false ? filterWarningInFile(eslintErrorsInFile) : eslintErrorsInFile
195
+ isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(eslintErrorsInFile);
168
196
  if (staged_files[file] && typeof staged_files[file] == 'string') {
169
197
  if (!eslintErrorsInFile.length == 0) {
170
- //git diff is computed and stored in an array
171
- let git_diff = await calculateGitDiffForFile(current_branch, staged_files[file]);
172
- changedLinesArray = git_diff.filter(line => line.startsWith('@@'));
173
- let changedLinesStartArray = [];
174
- let changedLinesEndArray = [];
175
-
176
198
  //Calculating changed lines in a file and storing them in respective arrays
177
- for (let number of changedLinesArray) {
178
- let changesStartLine = parseInt(number.split(' ')[2].split(',')[0]);
179
- changedLinesStartArray.push(changesStartLine);
180
- let changesEndLine = number.split(' ')[2].split(',')[1];
181
- if (changesEndLine === undefined) {
182
- changedLinesEndArray.push(changesStartLine);
183
- } else {
184
- changedLinesEndArray.push(changesStartLine + parseInt(changesEndLine) - 1);
199
+ if (impactBasedPrecommit) {
200
+ //git diff is computed and stored in an array
201
+ let git_diff = await calculateGitDiffForFile(current_branch, staged_files[file]);
202
+ changedLinesArray = git_diff.filter(line => line.startsWith('@@'));
203
+ let changedLinesStartArray = [];
204
+ let changedLinesEndArray = [];
205
+ for (let number of changedLinesArray) {
206
+ let changesStartLine = parseInt(number.split(' ')[2].split(',')[0]);
207
+ changedLinesStartArray.push(changesStartLine);
208
+ let changesEndLine = number.split(' ')[2].split(',')[1];
209
+ if (changesEndLine === undefined) {
210
+ changedLinesEndArray.push(changesStartLine);
211
+ } else {
212
+ changedLinesEndArray.push(changesStartLine + parseInt(changesEndLine) - 1);
213
+ }
185
214
  }
186
- }
187
- for (let error = 1; error < eslintErrorsInFile.length - 2; error++) {
188
- //eslintErrorsInFile[error].trim() - 69:26 error => Do not hardcode content. Use I18N key instead no-hardcoding/no-hardcoding,
189
- //eslintErrorsInFile[error].trim().split(' ')[0] => 69:26
190
- //eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0] => 69
215
+ for (let error = 1; error < eslintErrorsInFile.length - 2; error++) {
216
+ //eslintErrorsInFile[error].trim() - 69:26 error => Do not hardcode content. Use I18N key instead no-hardcoding/no-hardcoding,
217
+ //eslintErrorsInFile[error].trim().split(' ')[0] => 69:26
218
+ //eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0] => 69
191
219
 
192
- let eslintErrorLineNumber = eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0];
193
- for (let lineNumber in changedLinesStartArray) {
194
- if (eslintErrorLineNumber >= changedLinesStartArray[lineNumber] && eslintErrorLineNumber <= changedLinesEndArray[lineNumber]) {
195
- eslintErrorsInChangedLines.push(eslintErrorsInFile[error]);
220
+ let eslintErrorLineNumber = eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0];
221
+ for (let lineNumber in changedLinesStartArray) {
222
+ if (eslintErrorLineNumber >= changedLinesStartArray[lineNumber] && eslintErrorLineNumber <= changedLinesEndArray[lineNumber]) {
223
+ eslintErrorsInChangedLines.push(eslintErrorsInFile[error]);
224
+ }
196
225
  }
197
226
  }
198
- }
199
- if (eslintErrorsInChangedLines.length > 0) {
200
- Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
201
- for (let eslintError of eslintErrorsInChangedLines) {
202
- Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
227
+ if (eslintErrorsInChangedLines.length > 0) {
228
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
229
+ for (let eslintError of eslintErrorsInChangedLines) {
230
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
231
+ }
232
+ if (shouldWarningsAbortCommit) {
233
+ hasEslintErrorsInChangedLines = true;
234
+ } else if (!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile) {
235
+ hasEslintErrorsInChangedLines = false;
236
+ }
237
+ }
238
+ } else {
239
+ if (eslintErrorsInFile.length > 0) {
240
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
241
+ for (let eslintError of eslintErrorsInFile) {
242
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
243
+ }
244
+ if (shouldWarningsAbortCommit) {
245
+ hasEslintErrorsInFiles = true;
246
+ } else if (!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile) {
247
+ hasEslintErrorsInFiles = false;
248
+ }
203
249
  }
204
- hasEslintErrorsInChangedLines = true;
205
250
  }
206
251
  }
207
252
  }
@@ -217,10 +262,13 @@ async function preCommitHook() {
217
262
  } catch {
218
263
  Logger.log(Logger.INFO_TYPE, 'Error executing pre commit hook');
219
264
  }
220
- if (hasEslintErrorsInChangedLines) {
265
+ if (hasEslintErrorsInChangedLines && areFilesStaged) {
266
+ Logger.log(Logger.FAILURE_TYPE, `There are eslint errors present. So commit is aborted`);
267
+ process.exit(1);
268
+ } else if (hasEslintErrorsInFiles && areFilesStaged) {
221
269
  Logger.log(Logger.FAILURE_TYPE, `There are eslint errors present. So commit is aborted`);
222
270
  process.exit(1);
223
- } else if (!hasEslintErrorsInChangedLines && areFilesStaged) {
271
+ } else if (!hasEslintErrorsInFiles && !hasEslintErrorsInChangedLines && areFilesStaged) {
224
272
  Logger.log(Logger.SUCCESS_TYPE, `Commit Successful`);
225
273
  process.exit(0);
226
274
  }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+
3
+ const path = require("path");
4
+
5
+ /**
6
+ * Configuration object for linting and reporting.
7
+ * @property {string} ruleConfigurationPath - The path to the ESLint configuration file.
8
+ * @property {boolean} impactBased - Indicates if the linting is impact-based.
9
+ * @property {string} lintReportPath - The path to the lint report JSON file.
10
+ * @property {string} metricServerHost - The URL of the SonarQube server.
11
+ * @property {string} exemptionInstanceHost - This is Exemption running host URL
12
+ * @property {string} metric_token - The token for authentication with the SonarQube server.
13
+ * @property {string} gitEndPoint - API EndPoint for Git Actions
14
+ * @property {string} tsConfigurationPath - The path of the ts configuration Path
15
+ * @property {number} projectId - project id of repository
16
+ * @property {boolean} impactBasedPrecommit - Indicates if the linting is impact-based in pre commit
17
+ * @property {string} token - Encrypted Authentication Token
18
+ * @property {string} compareBranch - Branch to compare diff
19
+ */
20
+
21
+ module.exports = {
22
+ ruleConfigurationPath: path.resolve(process.cwd(), ".eslintrc.js"),
23
+ impactBased: true,
24
+ lintReportPath: path.resolve(process.cwd(), "lint-report", "lintReport.json"),
25
+ metricServerHost: "https://client-linters.zohodesk.csez.zohocorpin.com",
26
+ exemptionInstanceHost: "",
27
+ metric_token: "zxh_9737850jh2l53ml17223929ihii73072j54j2260",
28
+ branchDiffPath: path.resolve(process.cwd(), "diffBranch.json"),
29
+ gitEndPoint: "https://zgit.csez.zohocorpin.com",
30
+ tsConfigurationPath: path.resolve(process.cwd(), 'tsconfig.json'),
31
+ projectId: `project-id`,
32
+ impactBasedPrecommit: true,
33
+ shouldWarningsAbortCommit: false,
34
+ token: "w-OkG3f5OOM1Rkly8phZ",
35
+ compareBranch: 'release'
36
+ };
@@ -36,6 +36,15 @@ function filterFiles(arrayOfFilesToBeFiltered, filesToBeRemoved, isConfigFileNee
36
36
  return arrayOfFilesToBeFiltered;
37
37
  }
38
38
  }
39
+
40
+ /**
41
+ * @function filterWarningInFile - filter warning in files
42
+ * @returns {Array<string>}
43
+ */
44
+ function filterWarningInFile(array) {
45
+ // handle error in file
46
+ }
39
47
  module.exports = {
40
- filterFiles
48
+ filterFiles,
49
+ filterWarningInFile
41
50
  };
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
 
3
3
  const os = require('os');
4
+ const path = require('path');
5
+ const fs = require("fs");
4
6
 
5
7
  /**
6
8
  * @function getTimeStampInfo - to fetch various timestamp details
@@ -25,7 +27,40 @@ function getTimeStampInfo() {
25
27
  function getEnv() {
26
28
  return os.type();
27
29
  }
30
+
31
+ /**
32
+ * @function getConfigPath - get a path of lint configuration path
33
+ * @returns {string}
34
+ */
35
+ function getConfigPath() {
36
+ const configPath = path.resolve(process.cwd(), 'lint.config.js');
37
+ const defaultConfigPath = path.resolve(__dirname, '..', '..', 'setup', 'sample.config.js');
38
+ return fs.exitSync(configPath) ? configPath : defaultConfigPath;
39
+ }
40
+
41
+ /**
42
+ * @function getConfiguration - get configuration object of lint configuration
43
+ * @returns
44
+ */
45
+ function getConfigurationPrecommit() {
46
+ return require(getConfigPath());
47
+ }
48
+
49
+ /**
50
+ * @function getSupportedLanguage - get support language
51
+ * @returns {Array<string>}
52
+ */
53
+ function getSupportedLanguage() {
54
+ const _language = [];
55
+ _language.push('.js');
56
+ _language.push('.jsx');
57
+ _language.push('.ts');
58
+ _language.push('.tsx');
59
+ return _language;
60
+ }
28
61
  module.exports = {
62
+ getSupportedLanguage,
29
63
  getTimeStampInfo,
30
- getEnv
64
+ getEnv,
65
+ getConfigurationPrecommit
31
66
  };
@@ -4,17 +4,21 @@
4
4
  const {
5
5
  execSync
6
6
  } = require('child_process');
7
+ const {
8
+ readdirSync
9
+ } = require('fs');
10
+ const path = require('path');
7
11
  const initializeHusky = require('./initializeHusky');
8
12
  const configurePrecommitHook = require('./configurePrecommitHook');
13
+ const {
14
+ getNodeModulesPath
15
+ } = require('../General/getNodeModulesPath');
9
16
  const {
10
17
  executeSynchronizedCommands
11
18
  } = require('../General/executeSyncCommands');
12
19
  const {
13
20
  Logger
14
21
  } = require('../Logger/Logger');
15
- const {
16
- getRootDirectory
17
- } = require('../General/RootDirectoryUtils/getRootDirectory');
18
22
  let isCustomPrecommitConfigurationSuccessful = false;
19
23
 
20
24
  /**
@@ -49,25 +53,16 @@ function setupHusky() {
49
53
  * @returns {boolean} - indicating if husky package installed successfully or not
50
54
  */
51
55
  function installHuskyPackage() {
52
- // checking globally so removed
53
- // const nodeModulesPathOfProject = path.join(getNodeModulesPath(),'node_modules')
54
- // let pluginsInNodeModules = executeSynchronizedCommands(readdirSync,[nodeModulesPathOfProject],'','Unable to get directories in node_modules when checking if husky is installed',true,false)
56
+ const nodeModulesPathOfProject = path.join(getNodeModulesPath(), 'node_modules');
57
+ let pluginsInNodeModules = executeSynchronizedCommands(readdirSync, [nodeModulesPathOfProject], '', 'Unable to get directories in node_modules when checking if husky is installed', true, false);
55
58
  let husky = {
56
59
  packageName: 'husky',
57
- version: '7.0.4'
60
+ version: '^7.0.4'
58
61
  };
59
-
60
- // let isHuskyInstalled = pluginsInNodeModules.includes(husky.packageName) ? true : false
61
- try {
62
- const huskyVersion = execSync("husky -v", {
63
- cwd: getRootDirectory()
64
- }).toString();
65
- if (!(huskyVersion.trim() == husky.version)) {
66
- throw new Error("error");
67
- }
68
- } catch {
62
+ let isHuskyInstalled = pluginsInNodeModules.includes(husky.packageName) ? true : false;
63
+ if (!isHuskyInstalled) {
69
64
  Logger.log(Logger.INFO_TYPE, 'Installing husky package ....');
70
- let installCommand = `npm install ${husky.packageName}@${husky.version} --save-dev --save-exact -g`;
65
+ let installCommand = `npm install ${husky.packageName}@${husky.version} --save-dev`;
71
66
  let isHuskyPackageInstalled = executeSynchronizedCommands(execSync, [installCommand, {
72
67
  stdio: 'inherit'
73
68
  }], 'Husky package Installed Successfully', 'Unable to install husky package', false, true);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zohodesk/codestandard-validator",
3
- "version": "0.0.2-exp-6",
3
+ "version": "0.0.2-exp-8",
4
4
  "description": "library to enforce code standard using eslint",
5
5
  "main": "index.js",
6
6
  "scripts": {