@zohodesk/codestandard-validator 0.0.7 → 1.0.0-exp-1

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.
Files changed (34) hide show
  1. package/.babelrc +1 -1
  2. package/bin/execute.js +1 -1
  3. package/build/hooks/Precommit/commit.js +41 -0
  4. package/build/hooks/Precommit/errorhelpers.js +39 -0
  5. package/build/hooks/Precommit/guard.js +50 -0
  6. package/build/hooks/Precommit/lint.js +96 -179
  7. package/build/hooks/Precommit/pre-commit.js +88 -29
  8. package/build/hooks/Precommit/utils.js +56 -0
  9. package/build/hooks/hook.js +40 -0
  10. package/build/lib/cli.js +2 -2
  11. package/build/lib/postinstall.js +3 -3
  12. package/build/utils/CloneCommonLinterRepo/cloneViaCdt.js +39 -26
  13. package/build/utils/ConfigFileUtils/createConfigFile.js +63 -0
  14. package/build/utils/ConfigFileUtils/getLintConfiguration.js +2 -2
  15. package/build/utils/FileAndFolderOperations/filterFiles.js +27 -2
  16. package/build/utils/General/getGeneralInfo.js +64 -3
  17. package/build/utils/General/getNodeModulesPath.js +4 -1
  18. package/build/utils/General/writeProjectDetailsToJson.js +5 -1
  19. package/build/utils/PluginsInstallation/arePluginsInstalled.js +2 -6
  20. package/build/utils/PluginsInstallation/checkIfPluginsAreInstalled.js +32 -59
  21. package/build/utils/PluginsInstallation/installPlugins.js +12 -65
  22. package/build/utils/PrecommitUsingGitSetup/update-git-precommithook.js +42 -35
  23. package/changeLog.md +7 -1
  24. package/index.js +1 -1
  25. package/jsonUtils/commonLinterRepoDetails.js +1 -1
  26. package/package.json +4 -2
  27. package/build/hooks/PrePush/pre-push.js +0 -247
  28. package/build/hooks/Precommit/filterUtils.js +0 -42
  29. package/build/utils/ConfigFileUtils/createConfigFiles.js +0 -68
  30. package/build/utils/EslintConfigFileUtils/createEslintConfigFile.js +0 -54
  31. package/build/utils/EslintConfigFileUtils/getEslintExecutablePath.js +0 -24
  32. package/build/utils/EslintConfigFileUtils/getLintConfiguration.js +0 -52
  33. package/build/utils/PluginsInstallation/Worker/installPluginsByWoker.js +0 -38
  34. package/build/utils/PluginsInstallation/Worker/worker.js +0 -33
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+
3
+ const {
4
+ exec
5
+ } = require("child_process");
6
+ const {
7
+ promisify
8
+ } = require("util");
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const {
12
+ getRootDirectory
13
+ } = require("../../utils/General/RootDirectoryUtils/getRootDirectory");
14
+ const {
15
+ checkIfPluginsAreInstalled
16
+ } = require("../../utils/PluginsInstallation/checkIfPluginsAreInstalled");
17
+ const execAsync = promisify(exec);
18
+ async function isMergeCommit() {
19
+ try {
20
+ const {
21
+ stdout
22
+ } = await execAsync("git rev-parse -q --verify MERGE_HEAD");
23
+ return Boolean(stdout.trim());
24
+ } catch {
25
+ return false;
26
+ }
27
+ }
28
+ async function getStagedFiles() {
29
+ try {
30
+ const {
31
+ stdout
32
+ } = await execAsync("git diff --staged --name-only");
33
+ const files = stdout.trim().split("\n").filter(Boolean);
34
+ return files.filter(file => fs.existsSync(path.resolve(getRootDirectory(), file)));
35
+ } catch {
36
+ throw new Error("Couldn't fetch staged files");
37
+ }
38
+ }
39
+ function areAllPluginsInstalled() {
40
+ return checkIfPluginsAreInstalled().uninstalledPlugins.length === 0;
41
+ }
42
+ function isOnlyWarnings(errors) {
43
+ return !errors.some(line => /\b(error|✖)\b/.test(line));
44
+ }
45
+ function extractDiffHunks(diffText) {
46
+ return diffText.split("\n").filter(line => line.startsWith("@@") || line.startsWith("+") || line.startsWith("-"))
47
+ // skip file headers like "+++ b/" or "--- a/"
48
+ .filter(line => !line.startsWith("+++ ") && !line.startsWith("--- ")).join("\n");
49
+ }
50
+ module.exports = {
51
+ isMergeCommit,
52
+ isOnlyWarnings,
53
+ areAllPluginsInstalled,
54
+ getStagedFiles,
55
+ extractDiffHunks
56
+ };
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+
3
+ const {
4
+ getLastCommitHash,
5
+ getStoredCommitHash,
6
+ updateJsonFile
7
+ } = require("../utils/General/getGeneralInfo");
8
+ const {
9
+ executeMethodsThatReturnBooleanValue
10
+ } = require("../utils/General/wrapperFunctionToExecuteAFunction");
11
+ const {
12
+ cloneViaCdt
13
+ } = require("../utils/CloneCommonLinterRepo/cloneViaCdt");
14
+ const {
15
+ getPluginsToInstall
16
+ } = require("../utils/PluginsInstallation/checkIfPluginsAreInstalled");
17
+ const {
18
+ installPlugins
19
+ } = require("../utils/PluginsInstallation/installPlugins");
20
+ const path = require("path");
21
+ const {
22
+ Logger
23
+ } = require("../utils/Logger/Logger");
24
+ async function hooks() {
25
+ var jsonFilePath = path.join(__dirname, '..', '..', 'jsonUtils', 'fsUtils.json');
26
+ if (!(getLastCommitHash() == getStoredCommitHash())) {
27
+ updateJsonFile(jsonFilePath, data => {
28
+ data.commitHash = getLastCommitHash();
29
+ return data;
30
+ });
31
+ Logger.log(Logger.INFO_TYPE, `Some rules and plugins are being fetched from a remote source and installed...`);
32
+ await executeMethodsThatReturnBooleanValue("Make sure zgit.csez.zohocorpin.com is accessible", cloneViaCdt, null);
33
+ const {
34
+ uninstalledPlugins
35
+ } = getPluginsToInstall();
36
+ await executeMethodsThatReturnBooleanValue("Some issue occurred in installing plugins", installPlugins, uninstalledPlugins);
37
+ }
38
+ require('./Precommit/commit');
39
+ }
40
+ hooks();
package/build/lib/cli.js CHANGED
@@ -16,7 +16,7 @@ const {
16
16
  installPlugins
17
17
  } = require("../utils/PluginsInstallation/installPlugins");
18
18
  const {
19
- checkIfPluginsAreInstalled
19
+ getPluginsToInstall
20
20
  } = require("../utils/PluginsInstallation/checkIfPluginsAreInstalled");
21
21
  const [,, action, ...options] = process.argv;
22
22
  async function run() {
@@ -35,7 +35,7 @@ async function run() {
35
35
  {
36
36
  const {
37
37
  uninstalledPlugins
38
- } = checkIfPluginsAreInstalled();
38
+ } = getPluginsToInstall();
39
39
  await executeMethodsThatReturnBooleanValue("Some issue occurred in installing plugins", installPlugins, uninstalledPlugins);
40
40
  break;
41
41
  }
@@ -7,8 +7,8 @@ const {
7
7
  setupHusky
8
8
  } = require("../utils/HuskySetup/setupHusky");
9
9
  const {
10
- createEslintConfigFile
11
- } = require("../utils/EslintConfigFileUtils/createEslintConfigFile");
10
+ createConfigFile
11
+ } = require("../utils/ConfigFileUtils/createConfigFile");
12
12
  const {
13
13
  Logger
14
14
  } = require("../utils/Logger/Logger");
@@ -34,7 +34,7 @@ async function postInstall() {
34
34
  await executeMethodsThatReturnBooleanValue("Some issue in writing node_modules path to json", writeFsPaths, null);
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
- await executeMethodsThatReturnBooleanValue("Some issue occurred in creating eslint config file.", createEslintConfigFile, null);
37
+ await executeMethodsThatReturnBooleanValue("Some issue occurred in creating eslint config file.", createConfigFile, null);
38
38
  Logger.log(Logger.SUCCESS_TYPE, "Pre commit setup successfull");
39
39
  arePluginsInstalled();
40
40
  } catch (error) {
@@ -16,14 +16,6 @@ const {
16
16
  const {
17
17
  executeSynchronizedCommands
18
18
  } = require('../General/executeSyncCommands');
19
- var {
20
- type,
21
- endPoint,
22
- branch,
23
- cacheDirectory,
24
- commonLinterRepoName,
25
- user
26
- } = require('../../../jsonUtils/commonLinterRepoDetails');
27
19
  const {
28
20
  getConfigurationPrecommit,
29
21
  getRunningEnv
@@ -34,28 +26,49 @@ const {
34
26
  const {
35
27
  Logger
36
28
  } = require("../Logger/Logger");
29
+ const {
30
+ type,
31
+ endPoint,
32
+ branch,
33
+ cacheDirectory,
34
+ commonLinterRepoName,
35
+ user
36
+ } = require('../../../jsonUtils/commonLinterRepoDetails');
37
+
37
38
  /**
38
- * @function cloneViaCdt - Using the "clint development tool" clones the common linter_configuration repo into precommit library
39
- * @returns {boolean} - indicating the success or failure of the cloning process
39
+ * @function cloneViaCdt
40
+ * @description Clones the common linter configuration repo using Clint Development Tool (CDT)
41
+ * @returns {boolean} Indicates the success or failure of the cloning process
40
42
  */
41
-
42
43
  function cloneViaCdt() {
43
- const {
44
- token
45
- } = getConfigurationPrecommit();
46
- 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, process.env.DECRYPT_TOKEN)}@${endPoint}`;
44
+ try {
45
+ const {
46
+ token
47
+ } = getConfigurationPrecommit();
48
+ const currentEnv = getRunningEnv();
49
+ Logger.log(Logger.INFO_TYPE, `Application is running in the following environment:${currentEnv}`);
50
+
51
+ // Clean up existing folder
52
+ const deleteDir = getDeleteDirPath();
53
+ removeFolder(deleteDir);
54
+
55
+ // Construct endpoint with credentials if in CI or automation
56
+ const isAutomatedEnv = currentEnv === "CI" || currentEnv === "DEVAUTOMATION";
57
+ const authenticatedEndpoint = isAutomatedEnv ? `https://${user}:${decrypt(token, 12)}@${endPoint}` : `https://${endPoint}`;
58
+ const cloneCommand = ['npx cdt clone', `--clone:type=${type}`, `--clone:url=${authenticatedEndpoint}`, `--clone:branch=${branch}`, `--clone:cacheDir=${cacheDirectory}`, `--clone:proj:name=${commonLinterRepoName}`].join(' ');
59
+
60
+ // Execute the CDT command
61
+ const clonedDir = getClonedDirPath();
62
+ const successMessage = `Lint Configuration Cloned Successfully - ${getRepoName() || 'common'}`;
63
+ const errorMessage = 'Could not clone the linters common repo';
64
+ const result = executeSynchronizedCommands(execSync, [cloneCommand, {
65
+ cwd: clonedDir
66
+ }], successMessage, errorMessage, false, true);
67
+ return result;
68
+ } catch (error) {
69
+ Logger.log(Logger.ERROR_TYPE, `cloneViaCdt failed: ${error.message}`);
70
+ return false;
53
71
  }
54
- var commandToCloneCommonConfigRepo = `npx cdt clone --clone:type=${type} --clone:url=${absoluteEndPoint} --clone:branch=${process.env.CONFIGURATION_BRANCH || branch} --clone:cacheDir=${cacheDirectory} --clone:proj:name=${commonLinterRepoName}`;
55
- let isCommonConfigurationClonedSuccessfully = executeSynchronizedCommands(execSync, [commandToCloneCommonConfigRepo, {
56
- cwd: getClonedDirPath()
57
- }], `Lint Configuration Cloned Successfully - ${getRepoName() || 'common'}`, 'Could not clone the linters common repo', false, true);
58
- return isCommonConfigurationClonedSuccessfully;
59
72
  }
60
73
  module.exports = {
61
74
  cloneViaCdt
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+
3
+ const path = require('path');
4
+ const {
5
+ writeFileSync,
6
+ existsSync,
7
+ unlinkSync,
8
+ readFileSync
9
+ } = require('fs');
10
+ const {
11
+ getNodeModulesPath
12
+ } = require('../General/getNodeModulesPath.js');
13
+ const {
14
+ Logger
15
+ } = require('../Logger/Logger.js');
16
+ const {
17
+ executeSynchronizedCommands
18
+ } = require('../General/executeSyncCommands.js');
19
+ const {
20
+ getServicePathElseCommon
21
+ } = require('./getLintConfiguration.js');
22
+
23
+ /**
24
+ * @function createConfigFile - creates ESLint and/or Stylelint configuration files based on repo config.
25
+ * @returns {boolean} - true if any config file is created successfully, false otherwise.
26
+ */
27
+ function createConfigFile() {
28
+ const nodeModulesPath = getNodeModulesPath();
29
+ const eslintConfigFilePath = path.join(nodeModulesPath, '.eslintrc.js');
30
+ const stylelintConfigFilePath = path.join(nodeModulesPath, '.stylelintrc.js');
31
+ const {
32
+ pathOfServiceSpecificEslintConfigFile,
33
+ pathOfServiceSpecificCssConfigFile
34
+ } = getServicePathElseCommon();
35
+ try {
36
+ const eslintConfig = executeSynchronizedCommands(readFileSync, [pathOfServiceSpecificEslintConfigFile, 'utf-8'], '', 'Unable to read content of eslint config file.', true, false);
37
+ const cssConfig = executeSynchronizedCommands(readFileSync, [pathOfServiceSpecificCssConfigFile, 'utf-8'], '', 'Unable to read content of stylelint config file.', true, false);
38
+ const cssCreated = handleConfigFile(stylelintConfigFilePath, cssConfig, 'Stylelint');
39
+ const eslintCreated = handleConfigFile(eslintConfigFilePath, eslintConfig, 'Eslint');
40
+ return cssCreated || eslintCreated;
41
+ } catch (error) {
42
+ Logger.log(Logger.FAILURE_TYPE, error);
43
+ Logger.log(Logger.FAILURE_TYPE, 'Issue occurred while generating config files.');
44
+ return false;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * @function handleConfigFile - handles deletion (if exists) and creation of config files.
50
+ * @param {string} filePath - Path to the config file.
51
+ * @param {string} configContent - Configuration content.
52
+ * @param {string} type - Type of configuration (e.g., Eslint, Stylelint).
53
+ * @returns {boolean}
54
+ */
55
+ function handleConfigFile(filePath, configContent, type) {
56
+ if (existsSync(filePath)) {
57
+ executeSynchronizedCommands(unlinkSync, [filePath], `${type} configuration file removed successfully!`, `Unable to remove the ${type.toLowerCase()} config file.`, false, false);
58
+ }
59
+ return executeSynchronizedCommands(writeFileSync, [filePath, configContent, 'utf-8'], `${type} configuration file created successfully!`, `Unable to create and write a ${type.toLowerCase()} configuration file.`, false, true);
60
+ }
61
+ module.exports = {
62
+ createConfigFile
63
+ };
@@ -29,12 +29,12 @@ function getServicePathElseCommon() {
29
29
  const _configurationPath = repoName && existsSync(path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, 'index.js')) ? path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, 'index.js') : commonConfigPath;
30
30
  let _pathOfServiceSpecificEslintConfigFile = repoName && existsSync(path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, '.eslintrc.js')) ? path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, '.eslintrc.js') : path.join(libraryInstalledLocation, commonLinterRepoName, 'common', '.eslintrc.js');
31
31
  let _pluginVersionPath = repoName && existsSync(path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, 'pluginVersion.js')) ? path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, 'pluginVersion.js') : undefined;
32
- let _stylelintPath = repoName && existsSync(path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, '.stylelintrc.js')) ? path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, '.stylelintrc.js') : path.join(libraryInstalledLocation, commonLinterRepoName, 'common', '.stylelintrc.js');
32
+ let _cssLintConfig = repoName && existsSync(path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, '.stylelintrc.js')) ? path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, '.stylelintrc.js') : path.join(libraryInstalledLocation, commonLinterRepoName, 'common', '.stylelintrc.js');
33
33
  return {
34
34
  configurationPath: _configurationPath,
35
35
  pathOfServiceSpecificEslintConfigFile: _pathOfServiceSpecificEslintConfigFile,
36
36
  pluginVersionPath: _pluginVersionPath,
37
- cssLintConfig: _stylelintPath
37
+ pathOfServiceSpecificCssConfigFile: _cssLintConfig
38
38
  };
39
39
  }
40
40
  function getLintConfigurationUtil() {
@@ -3,7 +3,9 @@
3
3
  const {
4
4
  Logger
5
5
  } = require('../Logger/Logger');
6
-
6
+ const {
7
+ existsSync
8
+ } = require("fs");
7
9
  /**
8
10
  * @function filterFiles - removes certain files from set of source files
9
11
  * @param {Array} arrayOfFilesToBeFiltered - array of files which must be filtered
@@ -12,6 +14,29 @@ const {
12
14
  * @returns {Array} - containing the resultant set of files after filtering
13
15
  */
14
16
  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') || currentFile.includes('.properties') && 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
+ }
15
40
  if (filesToBeRemoved.length !== 0) {
16
41
  if (isConfigFileNeedToBeRemoved) {
17
42
  arrayOfFilesToBeFiltered.filter(file => {
@@ -31,7 +56,7 @@ function filterFiles(arrayOfFilesToBeFiltered, filesToBeRemoved, isConfigFileNee
31
56
  return false;
32
57
  }
33
58
  });
34
- return filteredArrayofFilesWithoutConfigFile;
59
+ return filterFilesByExtension(filteredArrayofFilesWithoutConfigFile);
35
60
  } else if (filesToBeRemoved.length === 0) {
36
61
  return arrayOfFilesToBeFiltered;
37
62
  }
@@ -6,6 +6,13 @@ const fs = require("fs");
6
6
  const {
7
7
  execSync
8
8
  } = require('child_process');
9
+ const {
10
+ readOnlyToken,
11
+ commitHashEndPoint
12
+ } = require('../../../jsonUtils/commonLinterRepoDetails');
13
+ const {
14
+ Logger
15
+ } = require('../Logger/Logger');
9
16
 
10
17
  /**
11
18
  * @function getTimeStampInfo - to fetch various timestamp details
@@ -57,8 +64,14 @@ function getSupportedLanguage() {
57
64
  const {
58
65
  supportedExtensions
59
66
  } = getConfigurationPrecommit();
60
- const _language = supportedExtensions;
61
- return _language;
67
+ const _language = supportedExtensions || [];
68
+ _language.push('.js');
69
+ _language.push('.jsx');
70
+ _language.push('.ts');
71
+ _language.push('.tsx');
72
+ _language.push('.css');
73
+ _language.push('.scss');
74
+ return [...new Set(_language)];
62
75
  }
63
76
  function getRunningEnv() {
64
77
  const command = "npm config get lint_env";
@@ -66,10 +79,58 @@ function getRunningEnv() {
66
79
  shell: true
67
80
  }).toString().trim();
68
81
  }
82
+
83
+ /**
84
+ * @function getLastCommitHash - Fetches the last commit hash from a GitLab project using its API.
85
+ *
86
+ * @note This function assumes access to a specific GitLab instance and a hardcoded token and project ID.
87
+ * @returns {string} The latest commit hash (SHA) from the specified GitLab repository.
88
+ * @throws {Error} Will throw an error if the API request fails or returns unexpected data.
89
+ */
90
+
91
+ function getLastCommitHash() {
92
+ try {
93
+ var _JSON$parse$;
94
+ const cmd = `curl --header "PRIVATE-TOKEN: ${readOnlyToken}" --url ${commitHashEndPoint}`;
95
+ return (_JSON$parse$ = JSON.parse(execSync(cmd))[0]) === null || _JSON$parse$ === void 0 ? void 0 : _JSON$parse$.id;
96
+ } catch (err) {
97
+ Logger.log(Logger.FAILURE_TYPE, err);
98
+ return null;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * @function getStoredCommitHash - Loads and returns the stored commit hash from `fsUtils.json`.
104
+ * @returns {string} The commit hash stored in the `fsUtils.json` file.
105
+ * @throws {Error} Will throw if the file does not exist or does not contain a `commitHash` key.
106
+ */
107
+
108
+ function getStoredCommitHash() {
109
+ const commitInfoPath = getJsonUtilsPath();
110
+ return fs.existsSync(commitInfoPath) && require(commitInfoPath).commitHash;
111
+ }
112
+ function getJsonUtilsPath() {
113
+ return path.join(__dirname, '..', '..', '..', 'jsonUtils', 'fsUtils.json');
114
+ }
115
+ function updateJsonFile(filePath, modifier) {
116
+ try {
117
+ const absolutePath = path.resolve(filePath);
118
+ const rawData = fs.readFileSync(absolutePath, "utf-8");
119
+ const jsonData = JSON.parse(rawData);
120
+ const updatedData = modifier(jsonData);
121
+ fs.writeFileSync(absolutePath, JSON.stringify(updatedData, null, 2), "utf-8");
122
+ } catch (error) {
123
+ Logger.log(Logger.FAILURE_TYPE, "Error updating JSON file");
124
+ }
125
+ }
69
126
  module.exports = {
70
127
  getSupportedLanguage,
71
128
  getTimeStampInfo,
72
129
  getEnv,
73
130
  getConfigurationPrecommit,
74
- getRunningEnv
131
+ getRunningEnv,
132
+ getLastCommitHash,
133
+ getStoredCommitHash,
134
+ getJsonUtilsPath,
135
+ updateJsonFile
75
136
  };
@@ -1,13 +1,16 @@
1
1
  "use strict";
2
2
 
3
3
  const path = require('path');
4
+ const {
5
+ getJsonUtilsPath
6
+ } = require('./getGeneralInfo');
4
7
 
5
8
  /**
6
9
  * @function getNodeModulesPath - fetches the absolute path where node_modules of project is present
7
10
  * @returns {string} - path where node_modules of the project is present
8
11
  */
9
12
  function getNodeModulesPath() {
10
- return require(path.join(__dirname, '..', '..', '..', 'jsonUtils', 'fsUtils.json')).nodeModulesPath;
13
+ return require(getJsonUtilsPath()).nodeModulesPath;
11
14
  }
12
15
  module.exports = {
13
16
  getNodeModulesPath
@@ -7,9 +7,13 @@ const {
7
7
  const {
8
8
  executeSynchronizedCommands
9
9
  } = require('./executeSyncCommands');
10
+ const {
11
+ getLastCommitHash
12
+ } = require('./getGeneralInfo');
10
13
  function writeFsPaths() {
11
14
  var fileContent = {
12
- nodeModulesPath: path.resolve(process.cwd(), '..', '..', '..')
15
+ nodeModulesPath: path.resolve(process.cwd(), '..', '..', '..'),
16
+ commitHash: getLastCommitHash()
13
17
  };
14
18
  return executeSynchronizedCommands(writeFileSync, [path.join(process.cwd(), 'jsonUtils', 'fsUtils.json'), JSON.stringify(fileContent), 'utf-8'], 'node_modules path updated in json file', 'Unable to write node_modules path to json file', false, true);
15
19
  }
@@ -1,11 +1,8 @@
1
1
  "use strict";
2
2
 
3
3
  const {
4
- checkIfPluginsAreInstalled
4
+ getPluginsToInstall
5
5
  } = require('./checkIfPluginsAreInstalled');
6
- const {
7
- printUninstalledPlugins
8
- } = require('./printUninstalledPlugins');
9
6
  const {
10
7
  installPlugins
11
8
  } = require('./installPlugins');
@@ -13,12 +10,11 @@ function arePluginsInstalled() {
13
10
  let {
14
11
  uninstalledPlugins,
15
12
  noPluginMessage
16
- } = checkIfPluginsAreInstalled();
13
+ } = getPluginsToInstall();
17
14
  let areAllPluginsInstalled = uninstalledPlugins.length === 0 ? true : false;
18
15
  if (!areAllPluginsInstalled) {
19
16
  installPlugins(uninstalledPlugins);
20
17
  }
21
- // printUninstalledPlugins(uninstalledPlugins,noPluginMessage)
22
18
  }
23
19
  module.exports = {
24
20
  arePluginsInstalled
@@ -1,22 +1,15 @@
1
1
  "use strict";
2
2
 
3
3
  const {
4
- readdirSync,
5
4
  existsSync
6
5
  } = require('fs');
7
6
  const path = require('path');
8
- const {
9
- getNodeModulesPath
10
- } = require('../General/getNodeModulesPath');
11
7
  const {
12
8
  Logger
13
9
  } = require('../Logger/Logger');
14
10
  const {
15
11
  getLibraryInstalledLocation
16
12
  } = require('../General/getLibraryInstalledLocation');
17
- const {
18
- executeSynchronizedCommands
19
- } = require('../General/executeSyncCommands');
20
13
  const {
21
14
  endPoint,
22
15
  commonLinterRepoName
@@ -26,33 +19,7 @@ const {
26
19
  } = require('../General/wrapperFunctionToExecuteAFunction');
27
20
  const {
28
21
  getServicePathElseCommon
29
- } = require('../EslintConfigFileUtils/getLintConfiguration');
30
- function getUnInstalledPlugins(pluginsForCurrentRepo, pluginNamesOfDevDependencyPlugins, devDependencies) {
31
- let pluginsInNodeModules = executeSynchronizedCommands(readdirSync, [path.join(getNodeModulesPath(), 'node_modules')], '', 'Unable to get the plugins inside node_modules', true, false);
32
- let pluginsToBeInstalled = [];
33
- pluginsForCurrentRepo.filter(plugin => {
34
- if (plugin.packageName.startsWith('@')) {
35
- let scope = plugin.packageName.split('/')[0];
36
- let pluginName = plugin.packageName.split('/')[1];
37
- let scopedPlugins = executeSynchronizedCommands(readdirSync, [path.join(getNodeModulesPath(), 'node_modules', scope)], '', 'Unable to get the plugins inside the scope inside node_modules', true, false);
38
- let isPluginInstalled = scopedPlugins.includes(pluginName) ? true : false;
39
- if (!isPluginInstalled) {
40
- pluginsToBeInstalled.push(`${plugin.packageName}@${plugin.version}`);
41
- }
42
- } else {
43
- let isPluginInstalled = pluginsInNodeModules.includes(plugin.packageName) ? true : false;
44
- if (!isPluginInstalled) {
45
- pluginsToBeInstalled.push(`${plugin.packageName}@${plugin.version}`);
46
- }
47
- }
48
- if (pluginNamesOfDevDependencyPlugins.includes(plugin.packageName)) {
49
- if (plugin.version !== devDependencies[plugin.packageName]) {
50
- pluginsToBeInstalled.push(`${plugin.packageName}@${plugin.version}`);
51
- }
52
- }
53
- });
54
- return pluginsToBeInstalled;
55
- }
22
+ } = require('../ConfigFileUtils/getLintConfiguration');
56
23
  function getAllPlugins() {
57
24
  let serviceSpecificPlugins = [];
58
25
  const pathToCommonPluginsFile = path.join(getLibraryInstalledLocation(), commonLinterRepoName, 'common', 'pluginVersion.js');
@@ -79,29 +46,6 @@ function checkIfPluginsAreInstalled() {
79
46
  noPluginMessage: '',
80
47
  uninstalledPlugins: []
81
48
  };
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
49
  uninstalledPlugins = pluginsForCurrentRepo.map(plugin => {
106
50
  const {
107
51
  packageName,
@@ -110,14 +54,42 @@ function checkIfPluginsAreInstalled() {
110
54
  const {
111
55
  isPluginPresent,
112
56
  pluginPath
113
- } = checkPluginsPresentInNodemodules(packageName);
57
+ } = checkPluginsPresentInNodemodules(packageName); // circular installation loop so comment out
114
58
  if (isPluginPresent && checkPluginHasProperVersion(packageName, pluginPath, version)) {
115
59
  return false;
116
60
  }
117
61
  return `${packageName}@${version}`;
118
62
  }).filter(Boolean);
119
63
  if (uninstalledPlugins.length > 0) {
120
- // uninstalledPlugins = getUnInstalledPlugins(pluginsForCurrentRepo, pluginNamesOfDevDependencyPlugins, pluginsIndevDependencies);
64
+ plugin.noPluginMessage = '';
65
+ plugin.uninstalledPlugins = uninstalledPlugins;
66
+ return plugin;
67
+ } else {
68
+ plugin.noPluginMessage = 'No plugins present for the repository';
69
+ plugin.uninstalledPlugins = [];
70
+ return plugin;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * @function getPluginsToInstall - plugins need for this repository
76
+ * @returns {Array<String>}
77
+ */
78
+ function getPluginsToInstall() {
79
+ const pluginsForCurrentRepo = getAllPlugins();
80
+ var uninstalledPlugins = [];
81
+ var plugin = {
82
+ noPluginMessage: '',
83
+ uninstalledPlugins: []
84
+ };
85
+ uninstalledPlugins = pluginsForCurrentRepo.map(plugin => {
86
+ const {
87
+ packageName,
88
+ version
89
+ } = plugin;
90
+ return `${packageName}@${version}`;
91
+ }).filter(Boolean);
92
+ if (uninstalledPlugins.length > 0) {
121
93
  plugin.noPluginMessage = '';
122
94
  plugin.uninstalledPlugins = uninstalledPlugins;
123
95
  return plugin;
@@ -173,5 +145,6 @@ function checkPluginHasProperVersion(rulePluginName, installationPath, remotePlu
173
145
  return remotePluginExactVersion == packageJsonPluginExactVersion ? true : false;
174
146
  }
175
147
  module.exports = {
148
+ getPluginsToInstall,
176
149
  checkIfPluginsAreInstalled
177
150
  };