@zohodesk/codestandard-validator 0.0.7-exp-5 → 0.0.7-exp-7

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.
package/bin/execute.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- require('../build/hooks/Precommit/pre-commit')
3
+ require('../build/hooks/hook')
@@ -144,19 +144,24 @@ function findEslintErrors(file) {
144
144
  * @param {*} params
145
145
  */
146
146
  function findStyleLintErrors(filePath) {
147
- const configFilePath = path.resolve(getNodeModulesPath(), '.stylelintrc.json');
147
+ const configFilePath = path.resolve(getNodeModulesPath(), '.stylelintrc.js');
148
148
  const absolutePath = path.join(getRootDirectory(), filePath);
149
149
  try {
150
150
  return new Promise((resolve, reject) => {
151
151
  exec(`npx stylelint ${absolutePath} --config ${configFilePath}`, {
152
152
  cwd: getNodeModulesPath()
153
153
  }, (error, stderr, stdout) => {
154
- if (stderr) {
154
+ if (stdout) {
155
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 {
156
+ }
157
+ // if(stderr){
158
+ // resolve(stderr.trim().split('\n'))
159
+ // }
160
+ // else if(error){
161
+ // Logger.log(Logger.FAILURE_TYPE,error)
162
+ // reject("Error executing eslint command")
163
+ // }
164
+ else {
160
165
  resolve([]);
161
166
  }
162
167
  });
@@ -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 || 12)}@${endPoint}`;
44
+ try {
45
+ const {
46
+ token
47
+ } = getConfigurationPrecommit();
48
+ const currentEnv = getRunningEnv();
49
+ Logger.log(Logger.INFO_TYPE, `Running in 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
+ };
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+
3
+ const path = require('path');
4
+ const {
5
+ readdirSync
6
+ } = require('fs');
7
+ const {
8
+ getNodeModulesPath
9
+ } = require('../General/getNodeModulesPath');
10
+ const {
11
+ executeSynchronizedCommands
12
+ } = require('../General/executeSyncCommands');
13
+ const {
14
+ getLibraryInstalledLocation
15
+ } = require('../General/getLibraryInstalledLocation');
16
+ function getEslintExecutablePath() {
17
+ let eslintLibraryName = 'eslint';
18
+ let librariesInNodeModulesOfProject = executeSynchronizedCommands(readdirSync, [path.join(getNodeModulesPath(), 'node_modules')], '', 'Unable to get the plugins inside node_modules', true, false);
19
+ let isEslintInstalledinProject = librariesInNodeModulesOfProject.some(library => library === eslintLibraryName);
20
+ return isEslintInstalledinProject ? path.join(getNodeModulesPath(), 'node_modules', eslintLibraryName, 'bin', 'eslint.js') : path.join(getLibraryInstalledLocation(), 'node_modules', eslintLibraryName, 'bin', 'eslint.js');
21
+ }
22
+ module.exports = {
23
+ getEslintExecutablePath
24
+ };
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+
3
+ const path = require('path');
4
+ const {
5
+ existsSync
6
+ } = require('fs');
7
+ const {
8
+ endPoint,
9
+ commonLinterRepoName
10
+ } = require("../../../jsonUtils/commonLinterRepoDetails.js");
11
+ const {
12
+ getRepoName
13
+ } = require('../GitActions/gitActions.js');
14
+ const {
15
+ getLibraryInstalledLocation
16
+ } = require('../General/getLibraryInstalledLocation.js');
17
+ const {
18
+ executeMethodsThatMayThrowException
19
+ } = require("../General/wrapperFunctionToExecuteAFunction.js");
20
+
21
+ /**
22
+ * @function getLintConfiguration - returns eslint configuration file from common linters repo
23
+ * @returns {object} - containing properties of the eslint configuration file
24
+ */
25
+ function getServicePathElseCommon() {
26
+ const repoName = getRepoName();
27
+ const libraryInstalledLocation = getLibraryInstalledLocation();
28
+ let commonConfigPath = path.join(libraryInstalledLocation, commonLinterRepoName, 'common', 'index.js');
29
+ const _configurationPath = repoName && existsSync(path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, 'index.js')) ? path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, 'index.js') : commonConfigPath;
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
+ let _pluginVersionPath = repoName && existsSync(path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, 'pluginVersion.js')) ? path.join(libraryInstalledLocation, commonLinterRepoName, 'services', repoName, 'pluginVersion.js') : undefined;
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
+ return {
34
+ configurationPath: _configurationPath,
35
+ pathOfServiceSpecificEslintConfigFile: _pathOfServiceSpecificEslintConfigFile,
36
+ pluginVersionPath: _pluginVersionPath,
37
+ pathOfServiceSpecificCssConfigFile: _cssLintConfig
38
+ };
39
+ }
40
+ function getLintConfigurationUtil() {
41
+ const {
42
+ configurationPath
43
+ } = getServicePathElseCommon();
44
+ const exceptionHandleObject = {
45
+ rulesConfig: [{}, {}],
46
+ plugins: [],
47
+ extendPlugins: []
48
+ };
49
+ return executeMethodsThatMayThrowException(exceptionHandleObject, `Kindly Ensure that Configuration is setup in Configuration repo \n ${endPoint}`, require, configurationPath);
50
+ }
51
+ module.exports = {
52
+ getLintConfigurationUtil,
53
+ getServicePathElseCommon
54
+ };
@@ -6,6 +6,10 @@ 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');
9
13
 
10
14
  /**
11
15
  * @function getTimeStampInfo - to fetch various timestamp details
@@ -72,10 +76,42 @@ function getRunningEnv() {
72
76
  shell: true
73
77
  }).toString().trim();
74
78
  }
79
+
80
+ /**
81
+ * @function getLastCommitHash - Fetches the last commit hash from a GitLab project using its API.
82
+ *
83
+ * @note This function assumes access to a specific GitLab instance and a hardcoded token and project ID.
84
+ * @returns {string} The latest commit hash (SHA) from the specified GitLab repository.
85
+ * @throws {Error} Will throw an error if the API request fails or returns unexpected data.
86
+ */
87
+
88
+ function getLastCommitHash() {
89
+ try {
90
+ var _JSON$parse$;
91
+ const cmd = `curl --header "PRIVATE-TOKEN: ${readOnlyToken}" --url ${commitHashEndPoint}`;
92
+ return (_JSON$parse$ = JSON.parse(execSync(cmd))[0]) === null || _JSON$parse$ === void 0 ? void 0 : _JSON$parse$.id;
93
+ } catch (err) {
94
+ Logger.log(Logger.FAILURE_TYPE, err);
95
+ return null;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * @function getStoredCommitHash - Loads and returns the stored commit hash from `fsUtils.json`.
101
+ * @returns {string} The commit hash stored in the `fsUtils.json` file.
102
+ * @throws {Error} Will throw if the file does not exist or does not contain a `commitHash` key.
103
+ */
104
+
105
+ function getStoredCommitHash() {
106
+ const commitInfoPath = path.join(__dirname, '..', '..', '..', 'jsonUtils', 'fsUtils.json');
107
+ return fs.existsSync(commitInfoPath) && require(commitInfoPath).commitHash;
108
+ }
75
109
  module.exports = {
76
110
  getSupportedLanguage,
77
111
  getTimeStampInfo,
78
112
  getEnv,
79
113
  getConfigurationPrecommit,
80
- getRunningEnv
114
+ getRunningEnv,
115
+ getLastCommitHash,
116
+ getStoredCommitHash
81
117
  };
@@ -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
  }
@@ -14,11 +14,11 @@ function arePluginsInstalled() {
14
14
  uninstalledPlugins,
15
15
  noPluginMessage
16
16
  } = checkIfPluginsAreInstalled();
17
- // let areAllPluginsInstalled = uninstalledPlugins.length === 0 ? true : false
18
- // if(!areAllPluginsInstalled){
19
- // installPlugins(uninstalledPlugins)
20
- // }
21
- printUninstalledPlugins(uninstalledPlugins, noPluginMessage);
17
+ let areAllPluginsInstalled = uninstalledPlugins.length === 0 ? true : false;
18
+ if (!areAllPluginsInstalled) {
19
+ installPlugins(uninstalledPlugins);
20
+ }
21
+ // printUninstalledPlugins(uninstalledPlugins,noPluginMessage)
22
22
  }
23
23
  module.exports = {
24
24
  arePluginsInstalled
@@ -21,7 +21,7 @@ const {
21
21
  } = require('../General/wrapperFunctionToExecuteAFunction');
22
22
  const {
23
23
  getServicePathElseCommon
24
- } = require('../EslintConfigFileUtils/getLintConfiguration');
24
+ } = require('../ConfigFileUtils/getLintConfiguration');
25
25
 
26
26
  // function getUnInstalledPlugins(pluginsForCurrentRepo,pluginNamesOfDevDependencyPlugins,devDependencies){
27
27
  // let pluginsInNodeModules = executeSynchronizedCommands(readdirSync,[path.join(getNodeModulesPath(),'node_modules')],'','Unable to get the plugins inside node_modules',true,false)
@@ -1,37 +1,44 @@
1
- "use strict";
2
-
3
- const {
4
- existsSync
5
- } = require("fs");
6
- const {
7
- getRootDirectory
8
- } = require('../General/RootDirectoryUtils/getRootDirectory');
9
- const {
10
- getNodeModulesPath
11
- } = require('../General/getNodeModulesPath');
12
- const path = require('path');
13
- const fs = require('fs');
14
- function getCustomPrecommitHookPath() {
15
- return path.resolve(getNodeModulesPath(), "node_modules", "@zohodesk", "codestandard-validator", "bin", "execute.js");
16
- }
17
-
18
1
  /**
19
- * @function updateGitFile - updates default precommit hook provided by git with the custom precommit hook file
20
- * @returns {null}
2
+ * @note currently dead code but helps in future
21
3
  */
22
- function updateGitFile() {
23
- const preCommit_File_Path_Default = path.resolve(getRootDirectory(), '.git', 'hooks', 'pre-commit.sample');
24
- let preCommit_File_Path = path.join(path.dirname(preCommit_File_Path_Default), 'pre-commit');
25
- if (existsSync(preCommit_File_Path_Default)) {
26
- fs.writeFileSync(preCommit_File_Path_Default, `#!/bin/sh${getCustomPrecommitHookPath()}`);
27
- fs.renameSync(preCommit_File_Path_Default, preCommit_File_Path);
28
- return;
29
- }
30
- if (existsSync(preCommit_File_Path)) {
31
- fs.appendFileSync(preCommit_File_Path, `\n${getCustomPrecommitHookPath()}`);
32
- return;
33
- }
34
- }
35
- module.exports = {
36
- updateGitFile
37
- };
4
+
5
+ // const { existsSync } = require("fs")
6
+ // const { getRootDirectory } = require('../General/RootDirectoryUtils/getRootDirectory')
7
+ // const { getNodeModulesPath } = require('../General/getNodeModulesPath')
8
+ // const path = require('path')
9
+ // const fs = require('fs')
10
+
11
+ // function getCustomPrecommitHookPath(){
12
+ // return path.resolve(
13
+ // getNodeModulesPath(),
14
+ // "node_modules",
15
+ // "@zohodesk",
16
+ // "codestandard-validator",
17
+ // "bin",
18
+ // "execute.js",
19
+ // );
20
+ // }
21
+
22
+ // /**
23
+ // * @function updateGitFile - updates default precommit hook provided by git with the custom precommit hook file
24
+ // * @returns {null}
25
+ // */
26
+ // function updateGitFile(){
27
+ // const preCommit_File_Path_Default = path.resolve(getRootDirectory(),'.git','hooks','pre-commit.sample')
28
+ // let preCommit_File_Path = path.join(path.dirname(preCommit_File_Path_Default),'pre-commit')
29
+ // if(existsSync(preCommit_File_Path_Default)){
30
+ // fs.writeFileSync(preCommit_File_Path_Default,`#!/bin/sh${getCustomPrecommitHookPath()}`)
31
+ // fs.renameSync(preCommit_File_Path_Default,preCommit_File_Path)
32
+ // return;
33
+ // }
34
+
35
+ // if(existsSync(preCommit_File_Path)){
36
+ // fs.appendFileSync(preCommit_File_Path,`\n${getCustomPrecommitHookPath()}`)
37
+ // return;
38
+ // }
39
+ // }
40
+
41
+ // module.exports = {
42
+ // updateGitFile
43
+ // }
44
+ "use strict";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zohodesk/codestandard-validator",
3
- "version": "0.0.7-exp-5",
3
+ "version": "0.0.7-exp-7",
4
4
  "description": "library to enforce code standard using eslint",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -16,7 +16,8 @@
16
16
  "type": "commonjs",
17
17
  "dependencies": {
18
18
  "@zohodesk-private/client_deployment_tool": "0.0.5",
19
- "eslint": "8.26.0"
19
+ "eslint": "8.26.0",
20
+ "stylelint":"16.23.0"
20
21
  },
21
22
  "devDependencies": {
22
23
  "@babel/core": "7.24.7",