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

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 +50 -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 -174
  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
@@ -6,18 +6,12 @@ const {
6
6
  const {
7
7
  writeFileSync
8
8
  } = require('fs');
9
- const {
10
- checkIfPluginsAreInstalled
11
- } = require('./checkIfPluginsAreInstalled');
12
9
  const {
13
10
  executeSynchronizedCommands
14
11
  } = require('../General/executeSyncCommands');
15
12
  const {
16
13
  Logger
17
14
  } = require('../Logger/Logger');
18
- const {
19
- createVersionControlFile
20
- } = require('../FileAndFolderOperations/versionControl');
21
15
  const {
22
16
  getNodeModulesPath
23
17
  } = require('../General/getNodeModulesPath');
@@ -27,11 +21,10 @@ const {
27
21
  * @returns {boolean} - indicating if plugins to be installed are installed successfully or not
28
22
  */
29
23
  function installPlugins(pluginsToBeInstalled) {
30
- // let {uninstalledPlugins : pluginsToBeInstalled} = checkIfPluginsAreInstalled()
31
24
  if (pluginsToBeInstalled.length > 0) {
32
25
  let packageJsonBeforePluginsInstallation = getPackageJsonContentBeforeInstallingPlugins();
33
- let installCommand = `npm install --save-dev ${pluginsToBeInstalled.join(' ')}`;
34
26
  Logger.log(Logger.INFO_TYPE, 'Installing plugins ....');
27
+ const installCommand = `npm install --save-dev ${pluginsToBeInstalled.join(' ')} --legacy-peer-deps`;
35
28
  Logger.log(Logger.INFO_TYPE, `Install command being executed: ${installCommand}`);
36
29
  let arePluginsInstalledSuccessfully = executeSynchronizedCommands(execSync, [installCommand, {
37
30
  stdio: 'inherit',
@@ -40,20 +33,21 @@ function installPlugins(pluginsToBeInstalled) {
40
33
  if (arePluginsInstalledSuccessfully) {
41
34
  Logger.log(Logger.SUCCESS_TYPE, 'Plugins installation successful');
42
35
  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
- }
36
+ // if(isPackageJsonRestored){
37
+ // createVersionControlFile(pluginsToBeInstalled)
38
+ // return true
39
+ // }
40
+ // else{
41
+ // Logger.log(Logger.FAILURE_TYPE,'Unable to restore package.json content')
42
+ // return false
43
+ // }
50
44
  } else {
51
- Logger.log(Logger.FAILURE_TYPE, "Unable to install plugins.Kindly retry the command");
52
- // return false
45
+ Logger.log(Logger.FAILURE_TYPE, "Unable to install plugins. Kindly retry the command");
46
+ return false;
53
47
  }
54
48
  } else {
55
49
  Logger.log(Logger.INFO_TYPE, 'Plugins are already installed');
56
- // return true
50
+ return true;
57
51
  }
58
52
  }
59
53
 
@@ -76,53 +70,6 @@ function restorePackageJsonContent(packageJsonContentBeforePluginsInstallation)
76
70
  let isPackageJsonRestored = executeSynchronizedCommands(writeFileSync, [packageJsonFilePath, JSON.stringify(packageJsonContentBeforePluginsInstallation, null, 2)], 'Package.json content restored successfully', 'Unable to restore package.json content', false, true);
77
71
  return isPackageJsonRestored;
78
72
  }
79
-
80
- // function appendInstalledPluginsToPackageJson(pluginsToBeAppendedInPackageJson){
81
- // let packageJsonFilePath = `${nodeModulesPathOfProject}/package.json`
82
- // let packageJsonContent = require(packageJsonFilePath)
83
- // let devDependencies = packageJsonContent.devDependencies
84
- // let pluginsToBeAddedInDevDependencies = {}
85
-
86
- // executeSynchronizedCommands(process.chdir,[nodeModulesPathOfProject],'','Unable to navigate to node_modules path when trying to revert changes in package.json',false,false)
87
-
88
- // let gitDiffOutput = executeSynchronizedCommands(execSync,['git diff --name-only'],'','Unable to execute git diff command while checking if package.json is changed',true,false).toString().trim()
89
- // let isPackageJsonChanged = gitDiffOutput.includes('package.json') ? true : false
90
-
91
- // if(isPackageJsonChanged){
92
- // let packageJsonChangesRevertCommand = `git checkout "${packageJsonFilePath}"`
93
- // isPackageJsonChangesRevertedSuccessfully = executeSynchronizedCommands(execSync,[packageJsonChangesRevertCommand,{stdio:'inherit'}],'Changes in package.json reverted successfully','Unable to revert the changes in package.json file',false,true)
94
-
95
- // if(isPackageJsonChangesRevertedSuccessfully){
96
- // pluginsToBeAppendedInPackageJson.map(uninstalledPlugin => {
97
- // if(uninstalledPlugin.startsWith('@')){
98
- // let indexOfAtCharacter = uninstalledPlugin.indexOf('@')
99
- // let indexOfSecondOccurenceOfAtCharacter = uninstalledPlugin.indexOf('@',indexOfAtCharacter + 1)
100
- // let unInstalledPluginName = uninstalledPlugin.slice(0,indexOfSecondOccurenceOfAtCharacter)
101
- // let unInstalledPluginVersion = uninstalledPlugin.slice(indexOfSecondOccurenceOfAtCharacter + 1)
102
- // pluginsToBeAddedInDevDependencies[unInstalledPluginName] = unInstalledPluginVersion
103
- // }
104
- // else{
105
- // pluginsToBeAddedInDevDependencies[uninstalledPlugin.split('@')[0]] = uninstalledPlugin.split('@')[1]
106
- // }
107
- // })
108
- // let updatedPluginsIndevDependencies = {
109
- // ...devDependencies,
110
- // ...pluginsToBeAddedInDevDependencies
111
- // }
112
- // packageJsonContent.devDependencies = updatedPluginsIndevDependencies
113
-
114
- // let modifiedPackageJson = {
115
- // ...packageJsonContent,
116
- // }
117
- // let isPluginsAddedInPackageJson = executeSynchronizedCommands(writeFileSync,[packageJsonFilePath,JSON.stringify(modifiedPackageJson,null,2)],'Newly installed plugins successfully added to package.json','Unable to append installed plugins to package.json',false,true)
118
- // return isPluginsAddedInPackageJson
119
- // }
120
- // else{
121
- // return true
122
- // }
123
- // }
124
- // }
125
-
126
73
  module.exports = {
127
74
  installPlugins
128
75
  };
@@ -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/changeLog.md CHANGED
@@ -29,4 +29,10 @@
29
29
  # 0.0.6 - Support extended for .properties file
30
30
 
31
31
  1. The file types that are supported by this library can now be configured using the configuration file "lint.config.js"
32
- 2. Support for .properties file is also extended in this version along with existing support for file types .js, .jsx, .ts, .tsx
32
+ 2. Support for .properties file is also extended in this version along with existing support for file types .js, .jsx, .ts, .tsx
33
+
34
+
35
+ # 1.0.0 - Support For Stylelint
36
+
37
+ 1. Enhancement Parser support CSS files and linter
38
+ 2. Clone Configuration Flow Enhancement Validation
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- const { getLintConfigurationUtil } = require("./build/utils/EslintConfigFileUtils/getLintConfiguration");
1
+ const { getLintConfigurationUtil } = require("./build/utils/ConfigFileUtils/getLintConfiguration");
2
2
  const { rulesConfig, plugins, extendPlugins } = getLintConfigurationUtil();
3
3
 
4
4
  module.exports = {
@@ -10,7 +10,7 @@
10
10
 
11
11
  module.exports = {
12
12
  endPoint: "zgit.csez.zohocorpin.com/code_standard/client_linter/linter_configuration.git",
13
- branch: "master",
13
+ branch: process.env.CONFIGURATION_BRANCH || "master",
14
14
  cacheDirectory: "./",
15
15
  commonLinterRepoName: "configuration",
16
16
  type: "git",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zohodesk/codestandard-validator",
3
- "version": "0.0.7",
3
+ "version": "1.0.0-exp-2",
4
4
  "description": "library to enforce code standard using eslint",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -15,8 +15,10 @@
15
15
  },
16
16
  "type": "commonjs",
17
17
  "dependencies": {
18
+ "@zohodesk/codestandard-analytics":"1.0.2-exp-2",
18
19
  "@zohodesk-private/client_deployment_tool": "0.0.5",
19
- "eslint": "8.26.0"
20
+ "eslint": "8.26.0",
21
+ "stylelint":"16.23.0"
20
22
  },
21
23
  "devDependencies": {
22
24
  "@babel/core": "7.24.7",
@@ -1,247 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- const {
8
- exec
9
- } = require('child_process');
10
- const fs = require('fs');
11
- const path = require('path');
12
- const {
13
- getEslintExecutablePath
14
- } = require('../../utils/EslintConfigFileUtils/getEslintExecutablePath');
15
- const {
16
- getNodeModulesPath
17
- } = require('../../utils/General/getNodeModulesPath');
18
- const {
19
- filterFiles
20
- } = require('../../utils/FileAndFolderOperations/filterFiles');
21
- const {
22
- Logger
23
- } = require('../../utils/Logger/Logger');
24
- const {
25
- checkIfPluginsAreInstalled
26
- } = require('../../utils/PluginsInstallation/checkIfPluginsAreInstalled');
27
- const {
28
- getBranchName
29
- } = require('../../utils/GitActions/gitActions');
30
- const {
31
- getConfigurationPrecommit,
32
- getSupportedLanguage
33
- } = require('../../utils/General/getGeneralInfo');
34
- const {
35
- getRootDirectory
36
- } = require('../../utils/General/RootDirectoryUtils/getRootDirectory');
37
- const {
38
- impactBasedPrecommit,
39
- shouldWarningsAbortCommit
40
- } = getConfigurationPrecommit();
41
-
42
- /**
43
- * Checks if the current commit is a merge commit
44
- * @returns {Promise<boolean>} True if it's a merge commit
45
- */
46
- async function isMergeCommit() {
47
- return new Promise(resolve => {
48
- exec('git rev-parse -q --verify MERGE_HEAD', error => {
49
- resolve(!error);
50
- });
51
- });
52
- }
53
-
54
- /**
55
- * Gets staged files while filtering out deleted files
56
- * @returns {Promise<string[]>} Array of staged file paths
57
- */
58
- async function getStagedFiles() {
59
- return new Promise((resolve, reject) => {
60
- exec('git diff --staged --name-only', (error, stdout) => {
61
- if (error) {
62
- return reject("Couldn't fetch staged files");
63
- }
64
- const files = stdout.trim().split('\n').filter(Boolean);
65
- resolve(filterDeletedFiles(files));
66
- });
67
- });
68
- }
69
-
70
- /**
71
- * Filters out deleted files from the staged files list
72
- * @param {string[]} files - Array of file paths
73
- * @returns {string[]} Filtered array of existing files
74
- */
75
- function filterDeletedFiles(files) {
76
- return files.filter(file => {
77
- const absolutePath = path.resolve(getRootDirectory(), file);
78
- return fs.existsSync(absolutePath);
79
- });
80
- }
81
-
82
- /**
83
- * Runs ESLint on a specific file
84
- * @param {string} file - File path to lint
85
- * @returns {Promise<string[]>} ESLint output lines
86
- */
87
- async function runEslintOnFile(file) {
88
- const nodeModulesPath = getNodeModulesPath();
89
- const eslintPath = getEslintExecutablePath();
90
- const configPath = `${nodeModulesPath}/.eslintrc.js`;
91
- if (!fs.existsSync(nodeModulesPath)) {
92
- Logger.log(Logger.INFO_TYPE, 'node_modules not found');
93
- return [];
94
- }
95
- if (!fs.existsSync(eslintPath)) {
96
- Logger.log(Logger.INFO_TYPE, 'Eslint executable not found');
97
- return [];
98
- }
99
- return new Promise(resolve => {
100
- const command = `npx --ignore-existing "${eslintPath}" --config "${configPath}" --no-inline-config --resolve-plugins-relative-to="${nodeModulesPath}/node_modules" ${file}`;
101
- exec(command, (error, stderr) => {
102
- if (stderr) {
103
- resolve(stderr.trim().split('\n'));
104
- } else {
105
- resolve([]);
106
- }
107
- });
108
- });
109
- }
110
-
111
- /**
112
- * Computes git diff for a file against current branch
113
- * @param {string} branch - Current branch name
114
- * @param {string} file - File path
115
- * @returns {Promise<string[]>} Git diff output lines
116
- */
117
- async function getGitDiff(branch, file) {
118
- return new Promise((resolve, reject) => {
119
- exec(`git diff -U0 ${branch.trim()} ${file}`, (error, stderr) => {
120
- if (error) return reject(error);
121
- resolve(stderr ? stderr.trim().split('\n') : []);
122
- });
123
- });
124
- }
125
-
126
- /**
127
- * Extracts changed line ranges from git diff output
128
- * @param {string[]} diffLines - Git diff output
129
- * @returns {Array<{start: number, end: number}>} Array of changed line ranges
130
- */
131
- function parseChangedLines(diffLines) {
132
- return diffLines.filter(line => line.startsWith('@@')).map(line => {
133
- const parts = line.split(' ')[2].split(',');
134
- const start = parseInt(parts[0]);
135
- const end = parts[1] ? start + parseInt(parts[1]) - 1 : start;
136
- return {
137
- start,
138
- end
139
- };
140
- });
141
- }
142
-
143
- /**
144
- * Filters ESLint errors to only include those in changed lines
145
- * @param {string[]} eslintErrors - ESLint output lines
146
- * @param {Array<{start: number, end: number}>} changedRanges - Changed line ranges
147
- * @returns {string[]} Filtered ESLint errors
148
- */
149
- function filterErrorsToChangedLines(eslintErrors, changedRanges) {
150
- return eslintErrors.filter(error => {
151
- const match = error.match(/^(\d+):/);
152
- if (!match) return false;
153
- const line = parseInt(match[1]);
154
- return changedRanges.some(({
155
- start,
156
- end
157
- }) => line >= start && line <= end);
158
- });
159
- }
160
-
161
- /**
162
- * Checks if ESLint output contains only warnings
163
- * @param {string[]} eslintErrors - ESLint output lines
164
- * @returns {boolean} True if only warnings are present
165
- */
166
- function hasOnlyWarnings(eslintErrors) {
167
- return eslintErrors.every(error => error.includes('warning'));
168
- }
169
-
170
- /**
171
- * Processes a file based on impact-based precommit configuration
172
- * @param {string} file - File path to process
173
- * @param {string} branch - Current branch name
174
- * @returns {Promise<boolean>} True if errors should abort commit
175
- */
176
- async function processFile(file, branch) {
177
- if (!getSupportedLanguage().includes(path.extname(file))) return false;
178
- try {
179
- const eslintOutput = await runEslintOnFile(file);
180
- if (eslintOutput.length < 3) return false; // No meaningful errors
181
-
182
- const errors = eslintOutput.slice(1, -2);
183
- if (!impactBasedPrecommit) {
184
- Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${file}\x1b[0m`);
185
- errors.forEach(err => Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${err.trimEnd()}\x1b[0m`));
186
- if (!shouldWarningsAbortCommit && hasOnlyWarnings(errors)) {
187
- return false;
188
- }
189
- return true;
190
- }
191
- const diffOutput = await getGitDiff(branch, file);
192
- const changedRanges = parseChangedLines(diffOutput);
193
- const changedLineErrors = filterErrorsToChangedLines(errors, changedRanges);
194
- if (changedLineErrors.length > 0) {
195
- Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${file}\x1b[0m`);
196
- changedLineErrors.forEach(err => Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${err.trimEnd()}\x1b[0m`));
197
- if (!shouldWarningsAbortCommit && hasOnlyWarnings(changedLineErrors)) {
198
- return false;
199
- }
200
- return true;
201
- }
202
- } catch (error) {
203
- Logger.log(Logger.FAILURE_TYPE, `Error processing ${file}: ${error}`);
204
- }
205
- return false;
206
- }
207
-
208
- /**
209
- * Main pre-push hook execution logic
210
- */
211
- async function prePushCheck() {
212
- Logger.log(Logger.INFO_TYPE, 'Executing pre commit hook...');
213
- if (await isMergeCommit()) {
214
- Logger.log(Logger.INFO_TYPE, 'Merge commit detected. Skipping checks.');
215
- process.exit(0);
216
- }
217
- const pluginsStatus = checkIfPluginsAreInstalled();
218
- if (pluginsStatus.uninstalledPlugins.length > 0) {
219
- Logger.log(Logger.FAILURE_TYPE, 'Commit failed: Required plugins missing');
220
- Logger.log(Logger.INFO_TYPE, 'Run: npx ZDPrecommit setupPlugins');
221
- process.exit(1);
222
- }
223
- try {
224
- const stagedFiles = await getStagedFiles();
225
- if (stagedFiles.length === 0) {
226
- Logger.log(Logger.INFO_TYPE, 'No staged files found');
227
- process.exit(0);
228
- }
229
- const filteredFiles = filterFiles(stagedFiles, ['.eslintrc.js'], true);
230
- const currentBranch = await getBranchName();
231
- let shouldAbort = false;
232
- for (const file of filteredFiles) {
233
- const fileShouldAbort = await processFile(file, currentBranch);
234
- if (fileShouldAbort) shouldAbort = true;
235
- }
236
- if (shouldAbort) {
237
- Logger.log(Logger.FAILURE_TYPE, 'Commit aborted due to ESLint issues');
238
- process.exit(1);
239
- }
240
- Logger.log(Logger.SUCCESS_TYPE, 'Commit successful');
241
- process.exit(0);
242
- } catch (error) {
243
- Logger.log(Logger.FAILURE_TYPE, `Pre-commit hook failed: ${error}`);
244
- process.exit(1);
245
- }
246
- }
247
- var _default = exports.default = prePushCheck;
@@ -1,42 +0,0 @@
1
- "use strict";
2
-
3
- const path = require('path');
4
- const {
5
- existsSync
6
- } = require('fs');
7
-
8
- // this file code implementation will be removed a
9
-
10
- function filterStagedFilesError(files) {
11
- // first index pop for file name
12
- if ((files === null || files === void 0 ? void 0 : files.length) == 0) {
13
- return [];
14
- }
15
- const fileName = files[0];
16
- if (existsSync(fileName)) {
17
- if (fileName.includes('uat')) {
18
- return [...filterByErrorMessage(files, 'Do not hardcode content. Use I18N key instead'), ...files.slice(files.length - 2)];
19
- }
20
- if (fileName.includes('src')) {
21
- return [...filterByErrorMessage(files, 'playwright'), ...files.slice(files.length - 2)];
22
- }
23
- }
24
- }
25
- function filterByErrorMessage(files, errorMessage) {
26
- return files.filter(fileContent => {
27
- if (errorMessage == 'Do not hardcode content. Use I18N key instead' && fileContent.includes('warning')) {
28
- return false;
29
- }
30
- if (fileContent.includes(errorMessage)) {
31
- return false;
32
- }
33
- return true;
34
- });
35
- }
36
- function allowedFiles(file) {
37
- return file.includes('uat') || file.includes('jsapps/supportapp/src') && !file.includes('jsapps/supportapp/src/__testsutils__/') && !file.includes('jsapps/supportapp/src/_actions/') && !file.includes('jsapps/supportapp/src/_doubts/') && !file.includes('jsapps/supportapp/src/_integration/') && !file.includes('jsapps/supportapp/src/_middleware/') && !file.includes('jsapps/supportapp/src/_pubSub/') && !file.includes('jsapps/supportapp/src/_reducers/') && !file.includes('jsapps/supportapp/src/_selectors/') && !file.includes('jsapps/supportapp/src/_store/') && !file.includes('jsapps/supportapp/src/_url/') && !file.includes('jsapps/supportapp/src/_utils/') && !file.includes('.docs.js') && !file.includes('.spec.js') && !file.includes('.specs.js') && !file.includes('.test.js');
38
- }
39
- module.exports = {
40
- filterStagedFilesError,
41
- allowedFiles
42
- };
@@ -1,68 +0,0 @@
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
- * Creates the ESLint configuration file from the service-specific or common template.
25
- * Also creates the Stylelint configuration file if available.
26
- *
27
- * @returns {boolean} Success status of ESLint config creation
28
- */
29
- function createConfigFiles() {
30
- const eslintConfigFilePath = path.join(getNodeModulesPath(), '.eslintrc.js');
31
- const stylelintConfigFilePath = path.join(getNodeModulesPath(), '.stylelintrc.js');
32
- const {
33
- pathOfServiceSpecificEslintConfigFile,
34
- cssLintConfig
35
- } = getServicePathElseCommon();
36
- try {
37
- const eslintContent = readConfig(pathOfServiceSpecificEslintConfigFile, 'eslint');
38
- const stylelintContent = readConfig(cssLintConfig, 'stylelint');
39
- if (stylelintContent) {
40
- writeConfig(stylelintConfigFilePath, stylelintContent, 'stylelint');
41
- }
42
- if (existsSync(eslintConfigFilePath)) {
43
- executeSynchronizedCommands(unlinkSync, [eslintConfigFilePath], 'ESLint configuration file removed successfully!', 'Unable to remove the ESLint config file.', false, false);
44
- }
45
- return writeConfig(eslintConfigFilePath, eslintContent, 'eslint');
46
- } catch (error) {
47
- Logger.log(Logger.FAILURE_TYPE, error);
48
- Logger.log(Logger.FAILURE_TYPE, 'Error occurred while creating ESLint config file');
49
- return false;
50
- }
51
- }
52
-
53
- /**
54
- * Reads a configuration file with logging and error handling.
55
- */
56
- function readConfig(filePath, type) {
57
- return executeSynchronizedCommands(readFileSync, [filePath, 'utf-8'], '', `Unable to read content of ${type} config file.`, true, false);
58
- }
59
-
60
- /**
61
- * Writes a configuration file with logging and error handling.
62
- */
63
- function writeConfig(filePath, content, type) {
64
- return executeSynchronizedCommands(writeFileSync, [filePath, content, 'utf-8'], `${type[0].toUpperCase() + type.slice(1)} configuration file created successfully!`, `Unable to create and write a ${type} configuration file.`, false, true);
65
- }
66
- module.exports = {
67
- createConfigFiles
68
- };
@@ -1,54 +0,0 @@
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
- let eslintConfiguration = ``;
23
-
24
- /**
25
- * @function createEslintConfigFile - creates a eslint configuration file based on the configuration file in the common linters repo
26
- * @returns {boolean} - indicating the success or failure in creating the eslint configuration file
27
- */
28
- function createEslintConfigFile() {
29
- const eslintConfigFilePath = path.join(getNodeModulesPath(), '.eslintrc.js');
30
- const {
31
- pathOfServiceSpecificEslintConfigFile
32
- } = getServicePathElseCommon();
33
- eslintConfiguration = executeSynchronizedCommands(readFileSync, [pathOfServiceSpecificEslintConfigFile, 'utf-8'], '', 'Unable to read content of eslint config file.', true, false);
34
- try {
35
- let isEslintConfigFilePresent = existsSync(eslintConfigFilePath);
36
- if (isEslintConfigFilePresent) {
37
- executeSynchronizedCommands(unlinkSync, [eslintConfigFilePath], 'Eslint configuration file removed successfully!', 'Unable to remove the eslint config file.', false, false);
38
- return createEslintConfigurationFile();
39
- } else if (!isEslintConfigFilePresent) {
40
- return createEslintConfigurationFile();
41
- }
42
- } catch (error) {
43
- Logger.log(Logger.FAILURE_TYPE, error);
44
- Logger.log(Logger.FAILURE_TYPE, 'Issue occured while checking if eslint config file exists');
45
- }
46
- }
47
- function createEslintConfigurationFile() {
48
- const eslintConfigFilePath = path.join(getNodeModulesPath(), '.eslintrc.js');
49
- let isEslintConfigFileCreated = executeSynchronizedCommands(writeFileSync, [eslintConfigFilePath, eslintConfiguration, 'utf-8'], 'Eslint configuration file created successfully!', 'Unable to create and write an eslint configuration file.', false, true);
50
- return isEslintConfigFileCreated;
51
- }
52
- module.exports = {
53
- createEslintConfigFile
54
- };