@zohodesk/codestandard-validator 0.0.4-exp-16 → 0.0.4-exp-18

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.
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const {
4
- exec,
5
- execSync
4
+ exec
6
5
  } = require('child_process');
7
6
  const fs = require('fs');
8
7
  const path = require('path');
@@ -88,22 +87,6 @@ function filterDeltedFileFromStagedFiles(files) {
88
87
  return false;
89
88
  });
90
89
  }
91
- async function lintFiles(filePath) {
92
- switch (path.extname(filePath)) {
93
- case '.js' || '.ts' || '.tsx' || '.jsx':
94
- {
95
- return await findEslintErrors(filePath);
96
- }
97
- case '.css' || '.scss':
98
- {
99
- return await findStyleLintErrors(filePath);
100
- }
101
- default:
102
- {
103
- return [];
104
- }
105
- }
106
- }
107
90
 
108
91
  /**
109
92
  * @function findEslintErrors - method Lint given file based on given configuration
@@ -111,7 +94,7 @@ async function lintFiles(filePath) {
111
94
  * @returns {Array<string>} - array of command line report as a string
112
95
  */
113
96
 
114
- function findEslintErrors(file) {
97
+ async function findEslintErrors(file) {
115
98
  let nodeModulesPathOfProject = `${getNodeModulesPath()}`;
116
99
  let eslintExecutablePath = getEslintExecutablePath();
117
100
  let eslintConfigurationFilePath = `${nodeModulesPathOfProject}/.eslintrc.js`;
@@ -138,35 +121,6 @@ function findEslintErrors(file) {
138
121
  Logger.log(Logger.INFO_TYPE, 'node_modules not found');
139
122
  }
140
123
  }
141
-
142
- /**
143
- *
144
- * @param {*} params
145
- */
146
- function findStyleLintErrors(filePath) {
147
- const configFilePath = path.resolve(getNodeModulesPath(), '.stylelintrc.json');
148
- const absolutePath = path.join(getRootDirectory(), filePath);
149
- try {
150
- return new Promise((resolve, reject) => {
151
- exec(`npx stylelint ${absolutePath} --config ${configFilePath}`, {
152
- cwd: getNodeModulesPath()
153
- }, (error, stderr, stdout) => {
154
- if (stderr) {
155
- resolve(stderr.trim().split('\n'));
156
- } else if (error) {
157
- Logger.log(Logger.FAILURE_TYPE, error);
158
- reject("Error executing eslint command");
159
- } else {
160
- resolve([]);
161
- }
162
- });
163
- });
164
- } catch (error) {
165
- Logger.log(Logger.FAILURE_TYPE, `Issue is lint css files`);
166
- return [];
167
- }
168
- }
169
-
170
124
  /**
171
125
  * @function {calculateGitDiffForFile} - method calculate diff of file
172
126
  * @param {*} branch_name - branch name
@@ -203,10 +157,10 @@ function isOnlyWarningsPresentInFile(eslintErrorsPresent) {
203
157
  let severityOfEachErrorInFile = [];
204
158
  eslintErrorsPresent.map(error => {
205
159
  let partsInString = error.split(" ");
206
- let severityOfError = partsInString.find(word => word === 'error' || word === 'warning' || word === '✖');
160
+ let severityOfError = partsInString.find(word => word === 'error' || word === 'warning');
207
161
  severityOfEachErrorInFile.push(severityOfError);
208
162
  });
209
- return !(severityOfEachErrorInFile.includes('✖') || severityOfEachErrorInFile.includes('error'));
163
+ return !severityOfEachErrorInFile.includes('error');
210
164
  }
211
165
 
212
166
  /**
@@ -239,33 +193,29 @@ async function preCommitHook() {
239
193
  try {
240
194
  staged_files = await getStagedFiles();
241
195
  if (!staged_files.length == 0) {
242
- const {
243
- JsFiles: staged_filesJS,
244
- CssFiles
245
- } = filterFiles(staged_files, eslintConfigFiles, true);
196
+ staged_files = filterFiles(staged_files, eslintConfigFiles, true);
246
197
 
247
- // staged_filesJS = filterFiles(staged_filesJS,exemptionFiles) //this is the code for giving exemption to a file during pre commit
248
- // if(staged_filesJS.length === 0){
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){
249
200
  // Logger.log(Logger.SUCCESS_TYPE,`Commit Successful`)
250
201
  // process.exit(0)
251
202
  // }
252
203
  areFilesStaged = true;
253
- var stagedFiles = [...staged_filesJS, ...CssFiles];
254
- for (let file in stagedFiles) {
255
- let currentFileName = stagedFiles[file];
204
+ for (let file in staged_files) {
205
+ let currentFileName = staged_files[file];
256
206
  let changedLinesArray = [];
257
207
  let eslintErrorsInChangedLines = [];
258
208
  let isOnlyEslintWarningsPresentInFile = false;
259
- if (getSupportedLanguage().includes(path.extname(stagedFiles[file]))) {
209
+ if (getSupportedLanguage().includes(path.extname(staged_files[file]))) {
260
210
  try {
261
- var errorsInFile = await lintFiles(stagedFiles[file]);
262
- // eslintErrorsInFile = impactBasedPrecommit == false ? filterWarningInFile(errorsInFile) : errorsInFile
263
- if (stagedFiles[file] && typeof stagedFiles[file] == 'string') {
264
- if (!errorsInFile.length == 0) {
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) {
265
215
  //Calculating changed lines in a file and storing them in respective arrays
266
216
  if (impactBasedPrecommit) {
267
217
  //git diff is computed and stored in an array
268
- let git_diff = await calculateGitDiffForFile(current_branch, stagedFiles[file]);
218
+ let git_diff = await calculateGitDiffForFile(current_branch, staged_files[file]);
269
219
  changedLinesArray = git_diff.filter(line => line.startsWith('@@'));
270
220
  let changedLinesStartArray = [];
271
221
  let changedLinesEndArray = [];
@@ -279,15 +229,15 @@ async function preCommitHook() {
279
229
  changedLinesEndArray.push(changesStartLine + parseInt(changesEndLine) - 1);
280
230
  }
281
231
  }
282
- for (let error = 1; error < errorsInFile.length - 2; error++) {
283
- //errorsInFile[error].trim() - 69:26 error => Do not hardcode content. Use I18N key instead no-hardcoding/no-hardcoding,
284
- //errorsInFile[error].trim().split(' ')[0] => 69:26
285
- //errorsInFile[error].trim().split(' ')[0].split(':')[0] => 69
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
286
236
 
287
- let eslintErrorLineNumber = errorsInFile[error].trim().split(' ')[0].split(':')[0];
237
+ let eslintErrorLineNumber = eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0];
288
238
  for (let lineNumber in changedLinesStartArray) {
289
239
  if (eslintErrorLineNumber >= changedLinesStartArray[lineNumber] && eslintErrorLineNumber <= changedLinesEndArray[lineNumber]) {
290
- eslintErrorsInChangedLines.push(errorsInFile[error]);
240
+ eslintErrorsInChangedLines.push(eslintErrorsInFile[error]);
291
241
  }
292
242
  }
293
243
  }
@@ -308,10 +258,10 @@ async function preCommitHook() {
308
258
  }
309
259
  }
310
260
  } else {
311
- if (errorsInFile.length > 0) {
261
+ if (eslintErrorsInFile.length > 0) {
312
262
  let startIndex = 1;
313
- let endIndex = errorsInFile.length - 2;
314
- let listOsEslintErrors = errorsInFile.slice(startIndex, endIndex);
263
+ let endIndex = eslintErrorsInFile.length - 2;
264
+ let listOsEslintErrors = eslintErrorsInFile.slice(startIndex, endIndex);
315
265
  isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(listOsEslintErrors);
316
266
  Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
317
267
  for (let eslintError of listOsEslintErrors) {
@@ -3,9 +3,7 @@
3
3
  const {
4
4
  Logger
5
5
  } = require('../Logger/Logger');
6
- const {
7
- existsSync
8
- } = require("fs");
6
+
9
7
  /**
10
8
  * @function filterFiles - removes certain files from set of source files
11
9
  * @param {Array} arrayOfFilesToBeFiltered - array of files which must be filtered
@@ -14,29 +12,6 @@ const {
14
12
  * @returns {Array} - containing the resultant set of files after filtering
15
13
  */
16
14
  function filterFiles(arrayOfFilesToBeFiltered, filesToBeRemoved, isConfigFileNeedToBeRemoved = false) {
17
- /**
18
- * @function filterFilesByExtension - filter javascript files. omit feature files
19
- * @param {Array<String>} lintFiles - linter files as Array
20
- * @returns {Array<String>}
21
- * */
22
- function filterFilesByExtension(lintFiles) {
23
- return lintFiles.reduce((files, currentFile) => {
24
- if (currentFile.includes('.feature') && existsSync(currentFile)) {
25
- files.featureFiles.push(currentFile);
26
- }
27
- if (currentFile.includes('.js') || currentFile.includes('.ts') || currentFile.includes('.tsx') || currentFile.includes('.jsx') && existsSync(currentFile)) {
28
- files.JsFiles.push(currentFile);
29
- }
30
- if (currentFile.includes('.css') && existsSync(currentFile)) {
31
- files.CssFiles.push(currentFile);
32
- }
33
- return files;
34
- }, {
35
- featureFiles: [],
36
- JsFiles: [],
37
- CssFiles: []
38
- });
39
- }
40
15
  if (filesToBeRemoved.length !== 0) {
41
16
  if (isConfigFileNeedToBeRemoved) {
42
17
  arrayOfFilesToBeFiltered.filter(file => {
@@ -56,7 +31,7 @@ function filterFiles(arrayOfFilesToBeFiltered, filesToBeRemoved, isConfigFileNee
56
31
  return false;
57
32
  }
58
33
  });
59
- return filterFilesByExtension(filteredArrayofFilesWithoutConfigFile);
34
+ return filteredArrayofFilesWithoutConfigFile;
60
35
  } else if (filesToBeRemoved.length === 0) {
61
36
  return arrayOfFilesToBeFiltered;
62
37
  }
@@ -59,8 +59,6 @@ function getSupportedLanguage() {
59
59
  _language.push('.jsx');
60
60
  _language.push('.ts');
61
61
  _language.push('.tsx');
62
- _language.push('.css');
63
- _language.push('.scss');
64
62
  return _language;
65
63
  }
66
64
  function getRunningEnv() {
@@ -6,12 +6,19 @@ const {
6
6
  const {
7
7
  printUninstalledPlugins
8
8
  } = require('./printUninstalledPlugins');
9
+ const {
10
+ installPlugins
11
+ } = require('./installPlugins');
9
12
  function arePluginsInstalled() {
10
13
  let {
11
14
  uninstalledPlugins,
12
15
  noPluginMessage
13
16
  } = checkIfPluginsAreInstalled();
14
- printUninstalledPlugins(uninstalledPlugins, noPluginMessage);
17
+ let areAllPluginsInstalled = uninstalledPlugins.length === 0 ? true : false;
18
+ if (!areAllPluginsInstalled) {
19
+ installPlugins(uninstalledPlugins);
20
+ }
21
+ // printUninstalledPlugins(uninstalledPlugins,noPluginMessage)
15
22
  }
16
23
  module.exports = {
17
24
  arePluginsInstalled
@@ -128,6 +128,15 @@ function checkIfPluginsAreInstalled() {
128
128
  }
129
129
  }
130
130
 
131
+ /**
132
+ * @function returnExactPluginVersion - to return the exact plugin version after removing caret or tilde symbol if present
133
+ * @param {string} pluginVersion
134
+ * @returns {string} - which represents exactPluginVersion
135
+ */
136
+ function returnExactPluginVersion(pluginVersion) {
137
+ return pluginVersion.replace(/[\^~]/, '');
138
+ }
139
+
131
140
  /**
132
141
  * @function checkPluginsPresentInNodemodules - to check if the plugin is present in the node_modules of the project
133
142
  * @param {string} rulePluginName
@@ -159,7 +168,9 @@ function checkPluginsPresentInNodemodules(rulePluginName) {
159
168
  function checkPluginHasProperVersion(rulePluginName, installationPath, remotePluginVersion) {
160
169
  const pluginPathArray = installationPath.toString().split(rulePluginName);
161
170
  const rulePluginPackageJSONPath = path.join(pluginPathArray[0], rulePluginName, 'package.json');
162
- return remotePluginVersion == require(rulePluginPackageJSONPath).version ? true : false;
171
+ const remotePluginExactVersion = returnExactPluginVersion(remotePluginVersion);
172
+ const packageJsonPluginExactVersion = returnExactPluginVersion(require(rulePluginPackageJSONPath).version);
173
+ return remotePluginExactVersion == packageJsonPluginExactVersion ? true : false;
163
174
  }
164
175
  module.exports = {
165
176
  checkIfPluginsAreInstalled
@@ -3,6 +3,9 @@
3
3
  const {
4
4
  execSync
5
5
  } = require('child_process');
6
+ const {
7
+ writeFileSync
8
+ } = require('fs');
6
9
  const {
7
10
  checkIfPluginsAreInstalled
8
11
  } = require('./checkIfPluginsAreInstalled');
@@ -26,7 +29,8 @@ const {
26
29
  function installPlugins(pluginsToBeInstalled) {
27
30
  // let {uninstalledPlugins : pluginsToBeInstalled} = checkIfPluginsAreInstalled()
28
31
  if (pluginsToBeInstalled.length > 0) {
29
- let installCommand = `npm install --save ${pluginsToBeInstalled.join(' ')}`;
32
+ let packageJsonBeforePluginsInstallation = getPackageJsonContentBeforeInstallingPlugins();
33
+ let installCommand = `npm install --save-dev ${pluginsToBeInstalled.join(' ')}`;
30
34
  Logger.log(Logger.INFO_TYPE, 'Installing plugins ....');
31
35
  Logger.log(Logger.INFO_TYPE, `Install command being executed: ${installCommand}`);
32
36
  let arePluginsInstalledSuccessfully = executeSynchronizedCommands(execSync, [installCommand, {
@@ -35,18 +39,44 @@ function installPlugins(pluginsToBeInstalled) {
35
39
  }], '', 'Some issue occured while installing plugins', false, true);
36
40
  if (arePluginsInstalledSuccessfully) {
37
41
  Logger.log(Logger.SUCCESS_TYPE, 'Plugins installation successful');
38
- createVersionControlFile(pluginsToBeInstalled);
39
- return true;
42
+ let isPackageJsonRestored = restorePackageJsonContent(packageJsonBeforePluginsInstallation);
43
+ if (isPackageJsonRestored) {
44
+ createVersionControlFile(pluginsToBeInstalled);
45
+ // return true
46
+ } else {
47
+ Logger.log(Logger.FAILURE_TYPE, 'Unable to restore package.json content');
48
+ // return false
49
+ }
40
50
  } else {
41
51
  Logger.log(Logger.FAILURE_TYPE, "Unable to install plugins.Kindly retry the command");
42
- return false;
52
+ // return false
43
53
  }
44
54
  } else {
45
55
  Logger.log(Logger.INFO_TYPE, 'Plugins are already installed');
46
- return true;
56
+ // return true
47
57
  }
48
58
  }
49
59
 
60
+ /**
61
+ * @function getPackageJsonContentBeforeInstallingPlugins - to get the content of package.json before installing plugins
62
+ * @returns {Object} - package.json content before installing plugins
63
+ */
64
+ function getPackageJsonContentBeforeInstallingPlugins() {
65
+ let packageJsonFilePath = `${getNodeModulesPath()}/package.json`;
66
+ let packageJsonContentBeforePluginsInstallation = require(packageJsonFilePath);
67
+ return packageJsonContentBeforePluginsInstallation;
68
+ }
69
+
70
+ /**
71
+ * @function restorePackageJsonContent - restore the same content as it was before installing plugins
72
+ * @returns {Boolean} - indicating the success or failure of restoring package.json content
73
+ */
74
+ function restorePackageJsonContent(packageJsonContentBeforePluginsInstallation) {
75
+ let packageJsonFilePath = `${getNodeModulesPath()}/package.json`;
76
+ let isPackageJsonRestored = executeSynchronizedCommands(writeFileSync, [packageJsonFilePath, JSON.stringify(packageJsonContentBeforePluginsInstallation, null, 2)], 'Package.json content restored successfully', 'Unable to restore package.json content', false, true);
77
+ return isPackageJsonRestored;
78
+ }
79
+
50
80
  // function appendInstalledPluginsToPackageJson(pluginsToBeAppendedInPackageJson){
51
81
  // let packageJsonFilePath = `${nodeModulesPathOfProject}/package.json`
52
82
  // let packageJsonContent = require(packageJsonFilePath)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zohodesk/codestandard-validator",
3
- "version": "0.0.4-exp-16",
3
+ "version": "0.0.4-exp-18",
4
4
  "description": "library to enforce code standard using eslint",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -1,35 +0,0 @@
1
- "use strict";
2
-
3
- const {
4
- Worker
5
- } = require('worker_threads');
6
- async function installPluginsByWorker(plugins) {
7
- try {
8
- const results = await Promise.all(plugins.map(pkg => runWorker({
9
- packageName: pkg.packageName,
10
- version: pkg.version
11
- })));
12
- console.log('Package are installed By from workers:', results.join('\n'));
13
- } catch (error) {
14
- console.error('Error:', error);
15
- }
16
- }
17
- function runWorker(data) {
18
- return new Promise((resolve, reject) => {
19
- const worker = new Worker(`${__dirname}/worker.js`, {
20
- workerData: data
21
- });
22
- worker.on('message', result => {
23
- resolve(result);
24
- });
25
- worker.on('error', error => {
26
- reject(error);
27
- });
28
- worker.on('exit', code => {
29
- if (code !== 0) {
30
- reject(new Error(`Worker stopped with exit code ${code}`));
31
- }
32
- });
33
- });
34
- }
35
- module.exports = installPluginsByWorker;
@@ -1,33 +0,0 @@
1
- "use strict";
2
-
3
- const {
4
- workerData,
5
- parentPort
6
- } = require('worker_threads');
7
- const {
8
- spawnSync
9
- } = require('child_process');
10
- const {
11
- getNodeModulesPath
12
- } = require('../../General/getNodeModulesPath');
13
- function performanceInstalllation({
14
- packageName,
15
- version
16
- }) {
17
- const start = performance.now();
18
- try {
19
- require.resolve(packageName);
20
- } catch (err) {
21
- spawnSync('npm', ['install', `${packageName}@${version}`, '--no-save'], {
22
- stdio: 'inherit',
23
- cwd: getNodeModulesPath()
24
- });
25
- }
26
- const end = performance.now();
27
- return `Package ${packageName}@${version} installed successfully and installed in ${end - start} ms`;
28
- }
29
- const result = performanceInstalllation({
30
- packageName: workerData.packageName,
31
- version: workerData.version
32
- });
33
- parentPort.postMessage(result);