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

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');
@@ -29,9 +28,6 @@ const {
29
28
  getConfigurationPrecommit,
30
29
  getSupportedLanguage
31
30
  } = require('../../utils/General/getGeneralInfo');
32
- const {
33
- getRootDirectory
34
- } = require('../../utils/General/RootDirectoryUtils/getRootDirectory');
35
31
  const {
36
32
  impactBasedPrecommit,
37
33
  shouldWarningsAbortCommit
@@ -66,7 +62,7 @@ async function getStagedFiles() {
66
62
  if (error) {
67
63
  if (error != null) reject("Couldn't fetch staged files");
68
64
  } else if (stderr) {
69
- resolve(filterDeltedFileFromStagedFiles(stderr.trim().split('\n')));
65
+ resolve(stderr.trim().split('\n'));
70
66
  } else if (stdout.trim() === '') {
71
67
  resolve(stdout.trim());
72
68
  }
@@ -74,44 +70,13 @@ async function getStagedFiles() {
74
70
  });
75
71
  }
76
72
 
77
- /**
78
- * @function {filterDeltedFileFromStagedFiles} - filter deleted staged files
79
- * @param {Array<string>} files - staged files
80
- * @returns
81
- */
82
- function filterDeltedFileFromStagedFiles(files) {
83
- return files.filter(file => {
84
- const absolutePath = path.resolve(getRootDirectory(), file);
85
- if (fs.existsSync(absolutePath)) {
86
- return true;
87
- }
88
- return false;
89
- });
90
- }
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
-
108
73
  /**
109
74
  * @function findEslintErrors - method Lint given file based on given configuration
110
75
  * @param {*} file - path of file to lint
111
76
  * @returns {Array<string>} - array of command line report as a string
112
77
  */
113
78
 
114
- function findEslintErrors(file) {
79
+ async function findEslintErrors(file) {
115
80
  let nodeModulesPathOfProject = `${getNodeModulesPath()}`;
116
81
  let eslintExecutablePath = getEslintExecutablePath();
117
82
  let eslintConfigurationFilePath = `${nodeModulesPathOfProject}/.eslintrc.js`;
@@ -138,35 +103,6 @@ function findEslintErrors(file) {
138
103
  Logger.log(Logger.INFO_TYPE, 'node_modules not found');
139
104
  }
140
105
  }
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
106
  /**
171
107
  * @function {calculateGitDiffForFile} - method calculate diff of file
172
108
  * @param {*} branch_name - branch name
@@ -203,10 +139,10 @@ function isOnlyWarningsPresentInFile(eslintErrorsPresent) {
203
139
  let severityOfEachErrorInFile = [];
204
140
  eslintErrorsPresent.map(error => {
205
141
  let partsInString = error.split(" ");
206
- let severityOfError = partsInString.find(word => word === 'error' || word === 'warning' || word === '✖');
142
+ let severityOfError = partsInString.find(word => word === 'error' || word === 'warning');
207
143
  severityOfEachErrorInFile.push(severityOfError);
208
144
  });
209
- return !(severityOfEachErrorInFile.includes('✖') || severityOfEachErrorInFile.includes('error'));
145
+ return !severityOfEachErrorInFile.includes('error');
210
146
  }
211
147
 
212
148
  /**
@@ -239,33 +175,29 @@ async function preCommitHook() {
239
175
  try {
240
176
  staged_files = await getStagedFiles();
241
177
  if (!staged_files.length == 0) {
242
- const {
243
- JsFiles: staged_filesJS,
244
- CssFiles
245
- } = filterFiles(staged_files, eslintConfigFiles, true);
178
+ staged_files = filterFiles(staged_files, eslintConfigFiles, true);
246
179
 
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){
180
+ // staged_files = filterFiles(staged_files,exemptionFiles) //this is the code for giving exemption to a file during pre commit
181
+ // if(staged_files.length === 0){
249
182
  // Logger.log(Logger.SUCCESS_TYPE,`Commit Successful`)
250
183
  // process.exit(0)
251
184
  // }
252
185
  areFilesStaged = true;
253
- var stagedFiles = [...staged_filesJS, ...CssFiles];
254
- for (let file in stagedFiles) {
255
- let currentFileName = stagedFiles[file];
186
+ for (let file in staged_files) {
187
+ let currentFileName = staged_files[file];
256
188
  let changedLinesArray = [];
257
189
  let eslintErrorsInChangedLines = [];
258
190
  let isOnlyEslintWarningsPresentInFile = false;
259
- if (getSupportedLanguage().includes(path.extname(stagedFiles[file]))) {
191
+ if (getSupportedLanguage().includes(path.extname(staged_files[file]))) {
260
192
  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) {
193
+ var eslintErrorsInFile = await findEslintErrors(staged_files[file]);
194
+ // eslintErrorsInFile = impactBasedPrecommit == false ? filterWarningInFile(eslintErrorsInFile) : eslintErrorsInFile
195
+ if (staged_files[file] && typeof staged_files[file] == 'string') {
196
+ if (!eslintErrorsInFile.length == 0) {
265
197
  //Calculating changed lines in a file and storing them in respective arrays
266
198
  if (impactBasedPrecommit) {
267
199
  //git diff is computed and stored in an array
268
- let git_diff = await calculateGitDiffForFile(current_branch, stagedFiles[file]);
200
+ let git_diff = await calculateGitDiffForFile(current_branch, staged_files[file]);
269
201
  changedLinesArray = git_diff.filter(line => line.startsWith('@@'));
270
202
  let changedLinesStartArray = [];
271
203
  let changedLinesEndArray = [];
@@ -279,15 +211,15 @@ async function preCommitHook() {
279
211
  changedLinesEndArray.push(changesStartLine + parseInt(changesEndLine) - 1);
280
212
  }
281
213
  }
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
214
+ for (let error = 1; error < eslintErrorsInFile.length - 2; error++) {
215
+ //eslintErrorsInFile[error].trim() - 69:26 error => Do not hardcode content. Use I18N key instead no-hardcoding/no-hardcoding,
216
+ //eslintErrorsInFile[error].trim().split(' ')[0] => 69:26
217
+ //eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0] => 69
286
218
 
287
- let eslintErrorLineNumber = errorsInFile[error].trim().split(' ')[0].split(':')[0];
219
+ let eslintErrorLineNumber = eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0];
288
220
  for (let lineNumber in changedLinesStartArray) {
289
221
  if (eslintErrorLineNumber >= changedLinesStartArray[lineNumber] && eslintErrorLineNumber <= changedLinesEndArray[lineNumber]) {
290
- eslintErrorsInChangedLines.push(errorsInFile[error]);
222
+ eslintErrorsInChangedLines.push(eslintErrorsInFile[error]);
291
223
  }
292
224
  }
293
225
  }
@@ -308,10 +240,10 @@ async function preCommitHook() {
308
240
  }
309
241
  }
310
242
  } else {
311
- if (errorsInFile.length > 0) {
243
+ if (eslintErrorsInFile.length > 0) {
312
244
  let startIndex = 1;
313
- let endIndex = errorsInFile.length - 2;
314
- let listOsEslintErrors = errorsInFile.slice(startIndex, endIndex);
245
+ let endIndex = eslintErrorsInFile.length - 2;
246
+ let listOsEslintErrors = eslintErrorsInFile.slice(startIndex, endIndex);
315
247
  isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(listOsEslintErrors);
316
248
  Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
317
249
  for (let eslintError of listOsEslintErrors) {
@@ -343,9 +275,9 @@ async function preCommitHook() {
343
275
  Logger.log(Logger.INFO_TYPE, 'Error executing pre commit hook');
344
276
  }
345
277
  if (shouldAbortCommit) {
346
- Logger.log(Logger.FAILURE_TYPE, `There are eslint errors/warnings present. So commit is aborted.`);
278
+ Logger.log(Logger.FAILURE_TYPE, `There are eslint errors present. So commit is aborted. If possible try to fix the eslint warnings also.`);
347
279
  process.exit(1);
348
- } else if (shouldAbortCommit === false && staged_files.length !== 0) {
280
+ } else {
349
281
  Logger.log(Logger.SUCCESS_TYPE, `Commit Successful`);
350
282
  process.exit(0);
351
283
  }
package/build/lib/cli.js CHANGED
@@ -15,9 +15,6 @@ const {
15
15
  const {
16
16
  installPlugins
17
17
  } = require("../utils/PluginsInstallation/installPlugins");
18
- const {
19
- checkIfPluginsAreInstalled
20
- } = require("../utils/PluginsInstallation/checkIfPluginsAreInstalled");
21
18
  const [,, action, ...options] = process.argv;
22
19
  async function run() {
23
20
  switch (action) {
@@ -33,10 +30,7 @@ async function run() {
33
30
  }
34
31
  case "setupPlugins":
35
32
  {
36
- const {
37
- uninstalledPlugins
38
- } = checkIfPluginsAreInstalled();
39
- await executeMethodsThatReturnBooleanValue("Some issue occurred in installing plugins", installPlugins, uninstalledPlugins);
33
+ await executeMethodsThatReturnBooleanValue("Some issue occurred in installing plugins", installPlugins, null);
40
34
  break;
41
35
  }
42
36
  case "setupExtension":
@@ -35,7 +35,7 @@ async function postInstall() {
35
35
  isGitInitialized() ? await executeMethodsThatReturnBooleanValue("Some issue occurred in setting up husky.", setupHusky, null) : null;
36
36
  await executeMethodsThatReturnBooleanValue("Make sure zgit.csez.zohocorpin.com is accessible", cloneViaCdt, null);
37
37
  await executeMethodsThatReturnBooleanValue("Some issue occurred in creating eslint config file.", createEslintConfigFile, null);
38
- Logger.log(Logger.SUCCESS_TYPE, "Pre commit setup successfull");
38
+ Logger.log(Logger.SUCCESS_TYPE, "Pre commit setup successful");
39
39
  arePluginsInstalled();
40
40
  } catch (error) {
41
41
  Logger.log(Logger.FAILURE_TYPE, `Kindly retry npm install. & ${error.message}`);
@@ -8,7 +8,7 @@ const path = require("path");
8
8
  * @property {boolean} impactBased - Indicates if the linting is impact-based.
9
9
  * @property {string} lintReportPath - The path to the lint report JSON file.
10
10
  * @property {string} metricServerHost - The URL of the SonarQube server.
11
- * @property {string} meticHandler_api_token - The token for authentication with the SonarQube server.
11
+ * @property {string} exemptionInstanceHost - This is Exemption running host URL
12
12
  * @property {string} metric_token - The token for authentication with the SonarQube server.
13
13
  * @property {string} gitEndPoint - API EndPoint for Git Actions
14
14
  * @property {string} tsConfigurationPath - The path of the ts configuration Path
@@ -24,7 +24,7 @@ module.exports = {
24
24
  impactBased: true,
25
25
  lintReportPath: path.resolve(process.cwd(), "lint-report", "lintReport.json"),
26
26
  metricServerHost: "https://client-linters.zohodesk.csez.zohocorpin.com",
27
- meticHandler_api_token: "oyRcKJZxm2RkXytfAzVtmyRlLIftou5anC==",
27
+ exemptionInstanceHost: "",
28
28
  metric_token: "zxh_9737850jh2l53ml17223929ihii73072j54j2260",
29
29
  branchDiffPath: path.resolve(process.cwd(), "diffBranch.json"),
30
30
  gitEndPoint: "https://zgit.csez.zohocorpin.com",
@@ -16,42 +16,21 @@ const {
16
16
  const {
17
17
  executeSynchronizedCommands
18
18
  } = require('../General/executeSyncCommands');
19
- var {
19
+ const {
20
20
  type,
21
21
  endPoint,
22
22
  branch,
23
23
  cacheDirectory,
24
- commonLinterRepoName,
25
- user
24
+ commonLinterRepoName
26
25
  } = require('../../../jsonUtils/commonLinterRepoDetails');
27
- const {
28
- getConfigurationPrecommit,
29
- getRunningEnv
30
- } = require("../General/getGeneralInfo");
31
- const {
32
- decrypt
33
- } = require("../General/Hash");
34
- const {
35
- Logger
36
- } = require("../Logger/Logger");
37
26
  /**
38
27
  * @function cloneViaCdt - Using the "clint development tool" clones the common linter_configuration repo into precommit library
39
28
  * @returns {boolean} - indicating the success or failure of the cloning process
40
29
  */
41
30
 
42
31
  function cloneViaCdt() {
43
- const {
44
- token
45
- } = getConfigurationPrecommit();
46
32
  removeFolder(getDeleteDirPath());
47
- const userName = user;
48
- var absoluteEndPoint = `https://${endPoint}`;
49
- const runningEnv = getRunningEnv();
50
- if (runningEnv === "CI" || runningEnv === "DEVAUTOMATION") {
51
- Logger.log(Logger.INFO_TYPE, `Running in ${runningEnv}`);
52
- absoluteEndPoint = `https://${userName}:${decrypt(token, 12)}@${endPoint}`;
53
- }
54
- var commandToCloneCommonConfigRepo = `npx cdt clone --clone:type=${type} --clone:url=${absoluteEndPoint} --clone:branch=${branch} --clone:cacheDir=${cacheDirectory} --clone:proj:name=${commonLinterRepoName}`;
33
+ const commandToCloneCommonConfigRepo = `npx cdt clone --clone:type=${type} --clone:url=${endPoint} --clone:branch=${branch} --clone:cacheDir=${cacheDirectory} --clone:proj:name=${commonLinterRepoName}`;
55
34
  let isCommonConfigurationClonedSuccessfully = executeSynchronizedCommands(execSync, [commandToCloneCommonConfigRepo, {
56
35
  cwd: getClonedDirPath()
57
36
  }], `Lint Configuration Cloned Successfully - ${getRepoName() || 'common'}`, 'Could not clone the linters common repo', false, true);
@@ -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
  }
@@ -3,9 +3,6 @@
3
3
  const os = require('os');
4
4
  const path = require('path');
5
5
  const fs = require("fs");
6
- const {
7
- execSync
8
- } = require('child_process');
9
6
 
10
7
  /**
11
8
  * @function getTimeStampInfo - to fetch various timestamp details
@@ -59,20 +56,11 @@ function getSupportedLanguage() {
59
56
  _language.push('.jsx');
60
57
  _language.push('.ts');
61
58
  _language.push('.tsx');
62
- _language.push('.css');
63
- _language.push('.scss');
64
59
  return _language;
65
60
  }
66
- function getRunningEnv() {
67
- const command = "npm config get lint_env";
68
- return execSync(command, {
69
- shell: true
70
- }).toString().trim();
71
- }
72
61
  module.exports = {
73
62
  getSupportedLanguage,
74
63
  getTimeStampInfo,
75
64
  getEnv,
76
- getConfigurationPrecommit,
77
- getRunningEnv
65
+ getConfigurationPrecommit
78
66
  };
@@ -23,7 +23,7 @@ function initializeHusky() {
23
23
  let isNavigationToRootDirectorySuccessful = navigateToRootDirectory(getRootDirectory());
24
24
  if (isNavigationToRootDirectorySuccessful) {
25
25
  try {
26
- execSync('npx husky@7 install');
26
+ execSync('npx husky install');
27
27
  return true;
28
28
  } catch (error) {
29
29
  Logger.log(Logger.FAILURE_TYPE, error.toString());
@@ -1,8 +1,21 @@
1
1
  "use strict";
2
2
 
3
3
  /* eslint-disable no-console */
4
+ const {
5
+ execSync
6
+ } = require('child_process');
7
+ const {
8
+ readdirSync
9
+ } = require('fs');
10
+ const path = require('path');
4
11
  const initializeHusky = require('./initializeHusky');
5
12
  const configurePrecommitHook = require('./configurePrecommitHook');
13
+ const {
14
+ getNodeModulesPath
15
+ } = require('../General/getNodeModulesPath');
16
+ const {
17
+ executeSynchronizedCommands
18
+ } = require('../General/executeSyncCommands');
6
19
  const {
7
20
  Logger
8
21
  } = require('../Logger/Logger');
@@ -13,21 +26,51 @@ let isCustomPrecommitConfigurationSuccessful = false;
13
26
  * @returns {boolean} - indicating whether entire custom precommit hook setup using husky process is success or failure
14
27
  */
15
28
  function setupHusky() {
16
- let isHuskyInitializedSuccessfully = initializeHusky();
17
- if (isHuskyInitializedSuccessfully) {
18
- Logger.log(Logger.SUCCESS_TYPE, 'Husky installation successful');
19
- isCustomPrecommitConfigurationSuccessful = configurePrecommitHook();
20
- if (isCustomPrecommitConfigurationSuccessful) {
21
- Logger.log(Logger.SUCCESS_TYPE, 'Custom pre commit hook setup was successful');
22
- return true;
29
+ let isHuskyPackageInstalled = installHuskyPackage();
30
+ if (isHuskyPackageInstalled) {
31
+ let isHuskyInitializedSuccessfully = initializeHusky();
32
+ if (isHuskyInitializedSuccessfully) {
33
+ Logger.log(Logger.SUCCESS_TYPE, 'Husky installation successful');
34
+ isCustomPrecommitConfigurationSuccessful = configurePrecommitHook();
35
+ if (isCustomPrecommitConfigurationSuccessful) {
36
+ Logger.log(Logger.SUCCESS_TYPE, 'Custom pre commit hook setup was successful');
37
+ return true;
38
+ } else {
39
+ Logger.log(Logger.FAILURE_TYPE, 'Couldn\'t configure custom pre commit hook');
40
+ return false;
41
+ }
23
42
  } else {
24
- Logger.log(Logger.FAILURE_TYPE, 'Couldn\'t configure custom pre commit hook');
25
43
  return false;
26
44
  }
27
45
  } else {
46
+ Logger.log(Logger.FAILURE_TYPE, 'Some issue in installing husky package.');
28
47
  return false;
29
48
  }
30
49
  }
50
+
51
+ /**
52
+ * @function installHuskyPackage - installs husky package if not installed for the project
53
+ * @returns {boolean} - indicating if husky package installed successfully or not
54
+ */
55
+ function installHuskyPackage() {
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);
58
+ let husky = {
59
+ packageName: 'husky',
60
+ version: '^7.0.4'
61
+ };
62
+ let isHuskyInstalled = pluginsInNodeModules.includes(husky.packageName) ? true : false;
63
+ if (!isHuskyInstalled) {
64
+ Logger.log(Logger.INFO_TYPE, 'Installing husky package ....');
65
+ let installCommand = `npm install ${husky.packageName}@${husky.version} --save-dev`;
66
+ let isHuskyPackageInstalled = executeSynchronizedCommands(execSync, [installCommand, {
67
+ stdio: 'inherit'
68
+ }], 'Husky package Installed Successfully', 'Unable to install husky package', false, true);
69
+ return isHuskyPackageInstalled;
70
+ }
71
+ Logger.log(Logger.SUCCESS_TYPE, 'Husky package already installed!');
72
+ return true;
73
+ }
31
74
  module.exports = {
32
75
  setupHusky
33
76
  };
@@ -7,11 +7,8 @@ const {
7
7
  printUninstalledPlugins
8
8
  } = require('./printUninstalledPlugins');
9
9
  function arePluginsInstalled() {
10
- let {
11
- uninstalledPlugins,
12
- noPluginMessage
13
- } = checkIfPluginsAreInstalled();
14
- printUninstalledPlugins(uninstalledPlugins, noPluginMessage);
10
+ let uninstalledPlugins = checkIfPluginsAreInstalled();
11
+ printUninstalledPlugins(uninstalledPlugins);
15
12
  }
16
13
  module.exports = {
17
14
  arePluginsInstalled
@@ -74,50 +74,30 @@ function getAllPlugins() {
74
74
  */
75
75
  function checkIfPluginsAreInstalled() {
76
76
  const pluginsForCurrentRepo = getAllPlugins();
77
- var uninstalledPlugins = [];
78
- var plugin = {
77
+ let uninstalledPlugins = [];
78
+ let plugin = {
79
79
  noPluginMessage: '',
80
80
  uninstalledPlugins: []
81
81
  };
82
- // let pluginsIndevDependencies = {}
83
- // let pluginNamesOfDevDependencyPlugins = []
84
- // let arePluginsPresentIndevDependencies = false
85
- // var arePluginsPresentForCurrentRepo = false
86
-
87
- // if(existsSync(path.join(getNodeModulesPath(),'package.json'))){
88
- // let packageJsonContent = require(path.join(getNodeModulesPath(),'package.json'))
89
- // pluginsIndevDependencies = packageJsonContent.devDependencies
90
-
91
- // if(pluginsIndevDependencies !== undefined){
92
- // arePluginsPresentIndevDependencies = true
93
- // pluginNamesOfDevDependencyPlugins = Object.keys(pluginsIndevDependencies)
94
- // }
95
- // else if(pluginsIndevDependencies === undefined){
96
- // Logger.log(Logger.INFO_TYPE,'No devDependencies present!')
97
- // }
98
- // }
99
- // else{
100
- // arePluginsPresentIndevDependencies = false
101
- // }
102
-
103
- // arePluginsPresentForCurrentRepo = pluginsForCurrentRepo.length !== 0 ? true : false
104
-
105
- uninstalledPlugins = pluginsForCurrentRepo.map(plugin => {
106
- const {
107
- packageName,
108
- version
109
- } = plugin;
110
- const {
111
- isPluginPresent,
112
- pluginPath
113
- } = checkPluginsPresentInNodemodules(packageName);
114
- if (isPluginPresent && checkPluginHasProperVersion(packageName, pluginPath, version)) {
115
- return false;
82
+ let pluginsIndevDependencies = {};
83
+ let pluginNamesOfDevDependencyPlugins = [];
84
+ let arePluginsPresentIndevDependencies = false;
85
+ let arePluginsPresentForCurrentRepo = false;
86
+ if (existsSync(path.join(getNodeModulesPath(), 'package.json'))) {
87
+ let packageJsonContent = require(path.join(getNodeModulesPath(), 'package.json'));
88
+ pluginsIndevDependencies = packageJsonContent.devDependencies;
89
+ if (pluginsIndevDependencies !== undefined) {
90
+ arePluginsPresentIndevDependencies = true;
91
+ pluginNamesOfDevDependencyPlugins = Object.keys(pluginsIndevDependencies);
92
+ } else if (pluginsIndevDependencies === undefined) {
93
+ Logger.log(Logger.INFO_TYPE, 'No devDependencies present!');
116
94
  }
117
- return `${packageName}@${version}`;
118
- }).filter(Boolean);
119
- if (uninstalledPlugins.length > 0) {
120
- // uninstalledPlugins = getUnInstalledPlugins(pluginsForCurrentRepo, pluginNamesOfDevDependencyPlugins, pluginsIndevDependencies);
95
+ } else {
96
+ arePluginsPresentIndevDependencies = false;
97
+ }
98
+ arePluginsPresentForCurrentRepo = pluginsForCurrentRepo.length !== 0 ? true : false;
99
+ if (arePluginsPresentForCurrentRepo || arePluginsPresentIndevDependencies) {
100
+ uninstalledPlugins = getUnInstalledPlugins(pluginsForCurrentRepo, pluginNamesOfDevDependencyPlugins, pluginsIndevDependencies);
121
101
  plugin.noPluginMessage = '';
122
102
  plugin.uninstalledPlugins = uninstalledPlugins;
123
103
  return plugin;
@@ -127,40 +107,6 @@ function checkIfPluginsAreInstalled() {
127
107
  return plugin;
128
108
  }
129
109
  }
130
-
131
- /**
132
- * @function checkPluginsPresentInNodemodules - to check if the plugin is present in the node_modules of the project
133
- * @param {string} rulePluginName
134
- * @returns
135
- */
136
- function checkPluginsPresentInNodemodules(rulePluginName) {
137
- try {
138
- const pluginPath = require.resolve(rulePluginName.toString());
139
- return {
140
- pluginPath: pluginPath,
141
- isPluginPresent: existsSync(pluginPath)
142
- };
143
- } catch (error) {
144
- return {
145
- pluginPath: "",
146
- isPluginPresent: false
147
- };
148
- }
149
- }
150
-
151
- /**
152
- * @function checkPluginHasProperVersion - to check if the plugin has the proper version`
153
- * @param {string} rulePluginName
154
- * @param {string} installationPath
155
- * @param {string} remotePluginVersion
156
- * @returns
157
- */
158
-
159
- function checkPluginHasProperVersion(rulePluginName, installationPath, remotePluginVersion) {
160
- const pluginPathArray = installationPath.toString().split(rulePluginName);
161
- const rulePluginPackageJSONPath = path.join(pluginPathArray[0], rulePluginName, 'package.json');
162
- return remotePluginVersion == require(rulePluginPackageJSONPath).version ? true : false;
163
- }
164
110
  module.exports = {
165
111
  checkIfPluginsAreInstalled
166
112
  };
@@ -12,30 +12,23 @@ const {
12
12
  const {
13
13
  Logger
14
14
  } = require('../Logger/Logger');
15
- const {
16
- createVersionControlFile
17
- } = require('../FileAndFolderOperations/versionControl');
18
- const {
19
- getNodeModulesPath
20
- } = require('../General/getNodeModulesPath');
21
15
 
22
16
  /**
23
17
  * @function installPlugins - installs uninstalled plugins for the project
24
18
  * @returns {boolean} - indicating if plugins to be installed are installed successfully or not
25
19
  */
26
- function installPlugins(pluginsToBeInstalled) {
27
- // let {uninstalledPlugins : pluginsToBeInstalled} = checkIfPluginsAreInstalled()
20
+ function installPlugins() {
21
+ let uninstalledPlugins = checkIfPluginsAreInstalled();
22
+ let pluginsToBeInstalled = uninstalledPlugins.uninstalledPlugins;
28
23
  if (pluginsToBeInstalled.length > 0) {
29
- let installCommand = `npm install --save ${pluginsToBeInstalled.join(' ')}`;
24
+ let installCommand = `npm install --save-dev ${pluginsToBeInstalled.join(' ')}`;
30
25
  Logger.log(Logger.INFO_TYPE, 'Installing plugins ....');
31
26
  Logger.log(Logger.INFO_TYPE, `Install command being executed: ${installCommand}`);
32
27
  let arePluginsInstalledSuccessfully = executeSynchronizedCommands(execSync, [installCommand, {
33
- stdio: 'inherit',
34
- cwd: getNodeModulesPath()
28
+ stdio: 'inherit'
35
29
  }], '', 'Some issue occured while installing plugins', false, true);
36
30
  if (arePluginsInstalledSuccessfully) {
37
31
  Logger.log(Logger.SUCCESS_TYPE, 'Plugins installation successful');
38
- createVersionControlFile(pluginsToBeInstalled);
39
32
  return true;
40
33
  } else {
41
34
  Logger.log(Logger.FAILURE_TYPE, "Unable to install plugins.Kindly retry the command");
@@ -8,17 +8,17 @@ const {
8
8
  * @function printUninstalledPlugins - to notify the user regarding plugins for the repository has been installed or not
9
9
  * @param {Array} uninstalledPlugins - contains list of uninstalled plugins for the project
10
10
  */
11
- function printUninstalledPlugins(uninstalledPlugins, noPluginMessage) {
11
+ function printUninstalledPlugins(uninstalledPlugins) {
12
12
  let commandToInstallPlugins = 'npx ZDPrecommit setupPlugins';
13
- if (uninstalledPlugins.length !== 0) {
13
+ if (uninstalledPlugins.uninstalledPlugins.length !== 0) {
14
14
  Logger.log(Logger.INFO_TYPE, 'The following plugins are not installed:');
15
- uninstalledPlugins.map(plugin => {
15
+ uninstalledPlugins.uninstalledPlugins.map(plugin => {
16
16
  Logger.log(Logger.INFO_TYPE, `"${plugin}"`);
17
17
  });
18
18
  Logger.log(Logger.FAILURE_TYPE, `Kindly execute the command \x1b[37m"${commandToInstallPlugins}\x1b[0m" \x1b[31mfrom the location where package.json of the repo is present to install the plugins`);
19
- } else if (uninstalledPlugins.length === 0 && noPluginMessage.trim() === '') {
19
+ } else if (uninstalledPlugins.uninstalledPlugins.length === 0 && uninstalledPlugins.noPluginMessage.trim() === '') {
20
20
  Logger.log(Logger.INFO_TYPE, 'Plugins are installed already');
21
- } else if (uninstalledPlugins.length === 0 && noPluginMessage.trim() !== '') {
21
+ } else if (uninstalledPlugins.uninstalledPlugins.length === 0 && uninstalledPlugins.noPluginMessage.trim() !== '') {
22
22
  Logger.log(Logger.INFO_TYPE, 'No plugins present for the repository');
23
23
  }
24
24
  }
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-17",
4
4
  "description": "library to enforce code standard using eslint",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -1,25 +0,0 @@
1
- "use strict";
2
-
3
- const path = require('path');
4
- const {
5
- getNodeModulesPath
6
- } = require('../General/getNodeModulesPath');
7
- const {
8
- writeFileSync
9
- } = require('fs');
10
- const {
11
- Logger
12
- } = require('../Logger/Logger');
13
- function createVersionControlFile(uninstalledPlugins) {
14
- Logger.log(Logger.INFO_TYPE, `Rule Plugin Versions are Noted in pluginVersionControl.js`);
15
- const versionfilePath = path.join(getNodeModulesPath(), 'node_modules', '@zohodesk', 'codestandard-validator', 'pluginVersionControl.js');
16
- writeFileSync(versionfilePath, `module.exports.plugins = [${uninstalledPlugins.map(plugin => {
17
- return JSON.stringify({
18
- plugin: `${plugin}`,
19
- time: `${new Date()}`
20
- });
21
- }).join(',')}]`);
22
- }
23
- module.exports = {
24
- createVersionControlFile
25
- };
@@ -1,21 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.encrypt = exports.decrypt = void 0;
7
- const caesarCipher = (str, shift) => {
8
- return str.split("").map(char => {
9
- let code = char.charCodeAt();
10
- if (code >= 65 && code <= 90) {
11
- return String.fromCharCode((code - 65 + shift) % 26 + 65);
12
- } else if (code >= 97 && code <= 122) {
13
- return String.fromCharCode((code - 97 + shift) % 26 + 97);
14
- }
15
- return char;
16
- }).join("");
17
- };
18
- const encrypt = (plaintext, shift) => caesarCipher(plaintext, shift);
19
- exports.encrypt = encrypt;
20
- const decrypt = (ciphertext, shift) => caesarCipher(ciphertext, 26 - shift);
21
- exports.decrypt = decrypt;
@@ -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);