@zohodesk/codestandard-validator 0.0.1 → 0.0.2-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 (38) hide show
  1. package/build/grafana-config/grafana-config.js +16 -0
  2. package/build/grafana-config/grfanaAPI.js +72 -0
  3. package/build/hooks/Precommit/filterUtils.js +42 -0
  4. package/build/hooks/Precommit/pre-commit.js +235 -0
  5. package/build/lib/cli.js +47 -0
  6. package/build/lib/postinstall.js +44 -0
  7. package/build/setup/initialSetup.js +60 -0
  8. package/build/utils/CloneCommonLinterRepo/HelperFunctions/helpers.js +19 -0
  9. package/build/utils/CloneCommonLinterRepo/cloneViaCdt.js +41 -0
  10. package/build/utils/EslintConfigFileUtils/createEslintConfigFile.js +54 -0
  11. package/build/utils/EslintConfigFileUtils/getEslintExecutablePath.js +24 -0
  12. package/build/utils/EslintConfigFileUtils/getLintConfiguration.js +52 -0
  13. package/build/utils/ExtensionInstallation/installEslintExtension.js +25 -0
  14. package/build/utils/FileAndFolderOperations/deleteFile.js +28 -0
  15. package/build/utils/FileAndFolderOperations/filterFiles.js +41 -0
  16. package/build/utils/FileAndFolderOperations/getFileContent.js +23 -0
  17. package/build/utils/FileAndFolderOperations/grantExecutionPermission.js +35 -0
  18. package/build/utils/FileAndFolderOperations/removeFolder.js +37 -0
  19. package/build/utils/General/RootDirectoryUtils/getRootDirectory.js +23 -0
  20. package/build/utils/General/RootDirectoryUtils/navigateToRootDirectory.js +25 -0
  21. package/build/utils/General/executeSyncCommands.js +40 -0
  22. package/build/utils/General/getGeneralInfo.js +31 -0
  23. package/build/utils/General/getLibraryInstalledLocation.js +18 -0
  24. package/build/utils/General/getNodeModulesPath.js +14 -0
  25. package/build/utils/General/wrapperFunctionToExecuteAFunction.js +39 -0
  26. package/build/utils/General/writeProjectDetailsToJson.js +18 -0
  27. package/build/utils/GitActions/gitActions.js +88 -0
  28. package/build/utils/HuskySetup/configurePrecommitHook.js +39 -0
  29. package/build/utils/HuskySetup/initializeHusky.js +35 -0
  30. package/build/utils/HuskySetup/setupHusky.js +83 -0
  31. package/build/utils/Logger/Logger.js +26 -0
  32. package/build/utils/PluginsInstallation/arePluginsInstalled.js +15 -0
  33. package/build/utils/PluginsInstallation/checkIfPluginsAreInstalled.js +112 -0
  34. package/build/utils/PluginsInstallation/installPlugins.js +91 -0
  35. package/build/utils/PluginsInstallation/printUninstalledPlugins.js +27 -0
  36. package/build/utils/PrecommitUsingGitSetup/update-git-precommithook.js +37 -0
  37. package/changeLog.md +3 -0
  38. package/package.json +1 -1
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+
3
+ const {
4
+ getRepoName
5
+ } = require("../utils/GitActions/gitActions");
6
+ module.exports = {
7
+ apiEndPoint: "",
8
+ path: "/",
9
+ requestHostDomain: "",
10
+ auth_token_noExpired: "",
11
+ type: "application/json",
12
+ metricName: `${getRepoName()}_precommit_metrics`,
13
+ metricType: "Counter",
14
+ metricValue: "1.0",
15
+ sleepTime: "600"
16
+ };
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+
3
+ var https = require("http");
4
+ const {
5
+ apiEndPoint,
6
+ path,
7
+ requestHostDomain,
8
+ auth_token_noExpired,
9
+ type,
10
+ metricName,
11
+ metricType,
12
+ metricValue,
13
+ sleepTime
14
+ } = require("./grafana-config");
15
+ // const { getTimeStampInfo } = require("../utils/General/getGeneralInfo");
16
+ const {
17
+ Logger
18
+ } = require("../utils/Logger/Logger");
19
+ function pushInfoToGrafana() {
20
+ var options = {
21
+ method: "POST",
22
+ hostname: apiEndPoint,
23
+ path: path,
24
+ headers: {
25
+ RequestHostDomain: requestHostDomain,
26
+ Authorization: auth_token_noExpired,
27
+ "Content-Type": type
28
+ },
29
+ maxRedirects: 20
30
+ };
31
+ var req = https.request(options, function (res) {
32
+ var chunks = [];
33
+ res.on("data", function (chunk) {
34
+ chunks.push(chunk);
35
+ });
36
+ res.on("end", function () {
37
+ var body = Buffer.concat(chunks);
38
+ Logger.log(Logger.INFO_TYPE, body.toString());
39
+ });
40
+ res.on("error", function (error) {
41
+ Logger.error(Logger.INFO_TYPE, error);
42
+ });
43
+ });
44
+ var metrics = JSON.stringify({
45
+ service_name: requestHostDomain,
46
+ metric_name: metricName,
47
+ metric_type: metricType,
48
+ metric_value: metricValue,
49
+ sleep_time: sleepTime,
50
+ labels: {
51
+ test: "precommit metric"
52
+ }
53
+ });
54
+ req.write(metrics);
55
+ req.end();
56
+ }
57
+ //comments
58
+
59
+ /**
60
+ * username,
61
+ * branch,
62
+ * repo,
63
+ * [{
64
+ * file:"",
65
+ * rule:""
66
+ * }],
67
+ * passed | failed
68
+ */
69
+
70
+ module.exports = {
71
+ pushInfoToGrafana
72
+ };
@@ -0,0 +1,42 @@
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
+ };
@@ -0,0 +1,235 @@
1
+ "use strict";
2
+
3
+ const {
4
+ exec
5
+ } = require('child_process');
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const {
9
+ getEslintExecutablePath
10
+ } = require('../../utils/EslintConfigFileUtils/getEslintExecutablePath');
11
+ const {
12
+ getNodeModulesPath
13
+ } = require('../../utils/General/getNodeModulesPath');
14
+ const {
15
+ filterFiles
16
+ } = require('../../utils/FileAndFolderOperations/filterFiles');
17
+ const {
18
+ Logger
19
+ } = require('../../utils/Logger/Logger');
20
+ const {
21
+ checkIfPluginsAreInstalled
22
+ } = require('../../utils/PluginsInstallation/checkIfPluginsAreInstalled');
23
+ const {
24
+ getBranchName
25
+ } = require('../../utils/GitActions/gitActions');
26
+
27
+ /**
28
+ * @function isMergeCommit - This method check whether it is merge or not
29
+ * @returns {Boolean} - return boolean based on latest merge changes
30
+ */
31
+ async function isMergeCommit() {
32
+ return new Promise((resolve, reject) => {
33
+ exec('git rev-parse -q --verify MERGE_HEAD', (error, stderr, stdout) => {
34
+ if (error) {
35
+ reject(error.toString().trim());
36
+ } else if (stderr) {
37
+ resolve(stderr.trim());
38
+ } else if (stdout) {
39
+ resolve(stdout.trim());
40
+ }
41
+ });
42
+ });
43
+ }
44
+
45
+ /**
46
+ * @function {getStagedFiles} - methods return staged files
47
+ * @returns {Array<string>} - array of files
48
+ */
49
+
50
+ async function getStagedFiles() {
51
+ return new Promise((resolve, reject) => {
52
+ exec("git diff --staged --name-only", (error, stderr, stdout) => {
53
+ if (error) {
54
+ if (error != null) reject("Couldn't fetch staged files");
55
+ } else if (stderr) {
56
+ resolve(stderr.trim().split('\n'));
57
+ } else if (stdout.trim() === '') {
58
+ resolve(stdout.trim());
59
+ }
60
+ });
61
+ });
62
+ }
63
+
64
+ /**
65
+ * @function findEslintErrors - method Lint given file based on given configuration
66
+ * @param {*} file - path of file to lint
67
+ * @returns {Array<string>} - array of command line report as a string
68
+ */
69
+
70
+ async function findEslintErrors(file) {
71
+ let nodeModulesPathOfProject = `${getNodeModulesPath()}`;
72
+ let eslintExecutablePath = getEslintExecutablePath();
73
+ let eslintConfigurationFilePath = `${nodeModulesPathOfProject}/.eslintrc.js`;
74
+ let isEslintExecutablePresent = fs.existsSync(eslintExecutablePath) ? true : false;
75
+ let isNodeModulesPresent = fs.existsSync(nodeModulesPathOfProject);
76
+ if (isNodeModulesPresent) {
77
+ if (isEslintExecutablePresent) {
78
+ return new Promise((resolve, reject) => {
79
+ exec(`npx --ignore-existing "${eslintExecutablePath}" --config "${eslintConfigurationFilePath}" --no-inline-config --resolve-plugins-relative-to="${nodeModulesPathOfProject}/node_modules" ${file}`, (error, stderr, stdout) => {
80
+ if (stderr) {
81
+ resolve(stderr.trim().split('\n'));
82
+ } else if (error) {
83
+ Logger.log(Logger.FAILURE_TYPE, error);
84
+ reject("Error executing eslint command");
85
+ } else {
86
+ resolve([]);
87
+ }
88
+ });
89
+ });
90
+ } else {
91
+ Logger.log(Logger.INFO_TYPE, 'Eslint executable not found. make sure eslint plugin is installed');
92
+ }
93
+ } else {
94
+ Logger.log(Logger.INFO_TYPE, 'node_modules not found');
95
+ }
96
+ }
97
+ /**
98
+ * @function {calculateGitDiffForFile} - method calculate diff of file
99
+ * @param {*} branch_name - branch name
100
+ * @param {*} file - path of file
101
+ * @returns {Promise<Array<string>>} - array of command line report as a string
102
+ */
103
+ async function calculateGitDiffForFile(branch_name, file) {
104
+ let gitDiffCommand = `git diff -U0 ${branch_name.trim()} ${file}`;
105
+ return new Promise((resolve, reject) => {
106
+ exec(gitDiffCommand, (error, stderr) => {
107
+ if (stderr) {
108
+ resolve(stderr.trim().split('\n'));
109
+ } else if (error) {
110
+ reject(error);
111
+ }
112
+ });
113
+ });
114
+ }
115
+ /**
116
+ * @function {areAllPluginsInstalled} - method whether plugin is installed or not
117
+ * @returns {Boolean} - return boolean based on plugin installed or not
118
+ */
119
+
120
+ function areAllPluginsInstalled() {
121
+ let unInstalledPlugins = checkIfPluginsAreInstalled().uninstalledPlugins;
122
+ return unInstalledPlugins.length === 0 ? true : false;
123
+ }
124
+
125
+ /**
126
+ * @function {preCommitHook} - method execute pre commit hook
127
+ * @returns {void}
128
+ */
129
+
130
+ async function preCommitHook() {
131
+ Logger.log(Logger.INFO_TYPE, 'Executing pre commit hook...');
132
+ Logger.log(Logger.INFO_TYPE, `working dir : ${process.cwd()}`);
133
+ try {
134
+ let isMerge = await isMergeCommit();
135
+ Logger.log(Logger.INFO_TYPE, 'Looks like you have merged. So skipping pre commit check');
136
+ process.exit(0);
137
+ } catch (error) {
138
+ if (areAllPluginsInstalled()) {
139
+ let staged_files = [];
140
+ let eslintConfigFiles = ['.eslintrc.js'];
141
+ let exemptionFiles = [];
142
+ let current_branch = '';
143
+ let hasEslintErrorsInChangedLines = false;
144
+ let areFilesStaged = false;
145
+ try {
146
+ current_branch = await getBranchName();
147
+ } catch {
148
+ Logger.log(Logger.INFO_TYPE, "Error fetching current branch");
149
+ }
150
+ try {
151
+ staged_files = await getStagedFiles();
152
+ if (!staged_files.length == 0) {
153
+ staged_files = filterFiles(staged_files, eslintConfigFiles, true);
154
+
155
+ // staged_files = filterFiles(staged_files,exemptionFiles) //this is the code for giving exemption to a file during pre commit
156
+ // if(staged_files.length === 0){
157
+ // Logger.log(Logger.SUCCESS_TYPE,`Commit Successful`)
158
+ // process.exit(0)
159
+ // }
160
+ areFilesStaged = true;
161
+ for (let file in staged_files) {
162
+ let currentFileName = staged_files[file];
163
+ let changedLinesArray = [];
164
+ let eslintErrorsInChangedLines = [];
165
+ if (path.extname(staged_files[file]) === '.js') {
166
+ try {
167
+ let eslintErrorsInFile = await findEslintErrors(staged_files[file]);
168
+ if (staged_files[file] && typeof staged_files[file] == 'string') {
169
+ if (!eslintErrorsInFile.length == 0) {
170
+ //git diff is computed and stored in an array
171
+ let git_diff = await calculateGitDiffForFile(current_branch, staged_files[file]);
172
+ changedLinesArray = git_diff.filter(line => line.startsWith('@@'));
173
+ let changedLinesStartArray = [];
174
+ let changedLinesEndArray = [];
175
+
176
+ //Calculating changed lines in a file and storing them in respective arrays
177
+ for (let number of changedLinesArray) {
178
+ let changesStartLine = parseInt(number.split(' ')[2].split(',')[0]);
179
+ changedLinesStartArray.push(changesStartLine);
180
+ let changesEndLine = number.split(' ')[2].split(',')[1];
181
+ if (changesEndLine === undefined) {
182
+ changedLinesEndArray.push(changesStartLine);
183
+ } else {
184
+ changedLinesEndArray.push(changesStartLine + parseInt(changesEndLine) - 1);
185
+ }
186
+ }
187
+ for (let error = 1; error < eslintErrorsInFile.length - 2; error++) {
188
+ //eslintErrorsInFile[error].trim() - 69:26 error => Do not hardcode content. Use I18N key instead no-hardcoding/no-hardcoding,
189
+ //eslintErrorsInFile[error].trim().split(' ')[0] => 69:26
190
+ //eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0] => 69
191
+
192
+ let eslintErrorLineNumber = eslintErrorsInFile[error].trim().split(' ')[0].split(':')[0];
193
+ for (let lineNumber in changedLinesStartArray) {
194
+ if (eslintErrorLineNumber >= changedLinesStartArray[lineNumber] && eslintErrorLineNumber <= changedLinesEndArray[lineNumber]) {
195
+ eslintErrorsInChangedLines.push(eslintErrorsInFile[error]);
196
+ }
197
+ }
198
+ }
199
+ if (eslintErrorsInChangedLines.length > 0) {
200
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
201
+ for (let eslintError of eslintErrorsInChangedLines) {
202
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
203
+ }
204
+ hasEslintErrorsInChangedLines = true;
205
+ }
206
+ }
207
+ }
208
+ } catch (err) {
209
+ Logger.log(Logger.FAILURE_TYPE, err);
210
+ Logger.log(Logger.FAILURE_TYPE, "Error in executing eslint command");
211
+ }
212
+ }
213
+ }
214
+ } else if (staged_files.length === 0) {
215
+ Logger.log(Logger.INFO_TYPE, 'No files have been staged. Stage your files before committing');
216
+ }
217
+ } catch {
218
+ Logger.log(Logger.INFO_TYPE, 'Error executing pre commit hook');
219
+ }
220
+ if (hasEslintErrorsInChangedLines) {
221
+ Logger.log(Logger.FAILURE_TYPE, `There are eslint errors present. So commit is aborted`);
222
+ process.exit(1);
223
+ } else if (!hasEslintErrorsInChangedLines && areFilesStaged) {
224
+ Logger.log(Logger.SUCCESS_TYPE, `Commit Successful`);
225
+ process.exit(0);
226
+ }
227
+ } else {
228
+ Logger.log(Logger.FAILURE_TYPE, 'Commit failed since some eslint plugins are not installed');
229
+ Logger.log(Logger.INFO_TYPE, `Kindly execute the command \x1b[37mnpx ZDPrecommit setupPlugins \x1b[33mfrom the location where package.json is present to install the plugins`);
230
+ Logger.log(Logger.INFO_TYPE, 'Execute the command and kindly try committing again.');
231
+ process.exit(1);
232
+ }
233
+ }
234
+ }
235
+ preCommitHook();
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+
3
+ const {
4
+ setupHusky
5
+ } = require("../utils/HuskySetup/setupHusky");
6
+ const {
7
+ initialSetup
8
+ } = require("../setup/initialSetup");
9
+ const {
10
+ executeMethodsThatReturnBooleanValue
11
+ } = require("../utils/General/wrapperFunctionToExecuteAFunction");
12
+ const {
13
+ installEslintExtension
14
+ } = require("../utils/ExtensionInstallation/installEslintExtension");
15
+ const {
16
+ installPlugins
17
+ } = require("../utils/PluginsInstallation/installPlugins");
18
+ const [,, action, ...options] = process.argv;
19
+ async function run() {
20
+ switch (action) {
21
+ case "setup":
22
+ {
23
+ await executeMethodsThatReturnBooleanValue("Some issue occurred in setting up husky.", setupHusky, null);
24
+ break;
25
+ }
26
+ case "init":
27
+ {
28
+ initialSetup();
29
+ break;
30
+ }
31
+ case "setupPlugins":
32
+ {
33
+ await executeMethodsThatReturnBooleanValue("Some issue occurred in installing plugins", installPlugins, null);
34
+ break;
35
+ }
36
+ case "setupExtension":
37
+ {
38
+ await executeMethodsThatReturnBooleanValue("Kindly install eslint extension for Vscode manually.", installEslintExtension, null);
39
+ break;
40
+ }
41
+ default:
42
+ {
43
+ break;
44
+ }
45
+ }
46
+ }
47
+ run();
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+
3
+ const {
4
+ cloneViaCdt
5
+ } = require("../utils/CloneCommonLinterRepo/cloneViaCdt");
6
+ const {
7
+ setupHusky
8
+ } = require("../utils/HuskySetup/setupHusky");
9
+ const {
10
+ createEslintConfigFile
11
+ } = require("../utils/EslintConfigFileUtils/createEslintConfigFile");
12
+ const {
13
+ Logger
14
+ } = require("../utils/Logger/Logger");
15
+ const {
16
+ executeMethodsThatReturnBooleanValue
17
+ } = require("../utils/General/wrapperFunctionToExecuteAFunction");
18
+ const {
19
+ arePluginsInstalled
20
+ } = require("../utils/PluginsInstallation/arePluginsInstalled");
21
+ const {
22
+ isGitInitialized
23
+ } = require("../utils/GitActions/gitActions");
24
+ const {
25
+ writeFsPaths
26
+ } = require("../utils/General/writeProjectDetailsToJson");
27
+
28
+ /**
29
+ * @function {postInstall} - This methods setup husky and configuration for executing project
30
+ * @returns {void}
31
+ */
32
+ async function postInstall() {
33
+ try {
34
+ await executeMethodsThatReturnBooleanValue("Some issue in writing node_modules path to json", writeFsPaths, null);
35
+ isGitInitialized() ? await executeMethodsThatReturnBooleanValue("Some issue occurred in setting up husky.", setupHusky, null) : null;
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);
38
+ Logger.log(Logger.SUCCESS_TYPE, "Pre commit setup successful");
39
+ arePluginsInstalled();
40
+ } catch (error) {
41
+ Logger.log(Logger.FAILURE_TYPE, `Kindly retry npm install. & ${error.message}`);
42
+ }
43
+ }
44
+ postInstall();
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+
3
+ const {
4
+ existsSync,
5
+ writeFileSync
6
+ } = require("fs");
7
+ const path = require("path");
8
+ const {
9
+ Logger
10
+ } = require("../utils/Logger/Logger");
11
+
12
+ /**
13
+ * @function initialSetup - Initialize prerequisite setup For Library
14
+ * @requires {void}
15
+ */
16
+
17
+ function initialSetup() {
18
+ const package_json_path = path.resolve(process.cwd(), "package.json");
19
+ updatePackageJSON(package_json_path, 'scripts', getSetupScript());
20
+ }
21
+
22
+ /**
23
+ * @function {getSetupScript} - get setup commands
24
+ * @returns {JSON | Object} - returns script command as key and value as executable command
25
+ */
26
+
27
+ function getSetupScript() {
28
+ return {
29
+ installRulePlugins: "ZDPrecommit setupPlugins",
30
+ setupVSCodeExtension: "ZDPrecommit setupExtension"
31
+ };
32
+ }
33
+
34
+ /**
35
+ * @function {updatePackageJSON} - method is updated scripts in package.json
36
+ * @param {string} packageJsonPath - path of package.json
37
+ * @param {string | Object} partToUpdate - param passed which part of package.json to update
38
+ * @param {string} updateObject - script to be updated in package.json
39
+ * @returns {void}
40
+ */
41
+ function updatePackageJSON(packageJsonPath, partToUpdate, updateObject) {
42
+ if (existsSync(packageJsonPath)) {
43
+ const packageContents = require(packageJsonPath);
44
+ const existingJSON = packageContents[partToUpdate] || {};
45
+ const modifiedScripts = {
46
+ ...existingJSON,
47
+ ...updateObject
48
+ };
49
+ const modifiedConfigJSON = {
50
+ ...packageContents,
51
+ scripts: modifiedScripts
52
+ };
53
+ writeFileSync(packageJsonPath, JSON.stringify(modifiedConfigJSON, null, 2));
54
+ } else {
55
+ Logger.log(Logger.FAILURE_TYPE, "Unable to find package json. Run init command in the root path of the project.");
56
+ }
57
+ }
58
+ module.exports = {
59
+ initialSetup
60
+ };
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+
3
+ const path = require('path');
4
+ const {
5
+ getLibraryInstalledLocation
6
+ } = require('../../General/getLibraryInstalledLocation');
7
+ const {
8
+ commonLinterRepoName
9
+ } = require('../../../../jsonUtils/commonLinterRepoDetails');
10
+ function getClonedDirPath() {
11
+ return getLibraryInstalledLocation();
12
+ }
13
+ function getDeleteDirPath() {
14
+ return path.resolve(getLibraryInstalledLocation(), commonLinterRepoName);
15
+ }
16
+ module.exports = {
17
+ getClonedDirPath,
18
+ getDeleteDirPath
19
+ };
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+
3
+ const {
4
+ execSync
5
+ } = require("child_process");
6
+ const {
7
+ getClonedDirPath,
8
+ getDeleteDirPath
9
+ } = require('./HelperFunctions/helpers');
10
+ const {
11
+ getRepoName
12
+ } = require("../GitActions/gitActions");
13
+ const {
14
+ removeFolder
15
+ } = require("../FileAndFolderOperations/removeFolder");
16
+ const {
17
+ executeSynchronizedCommands
18
+ } = require('../General/executeSyncCommands');
19
+ const {
20
+ type,
21
+ endPoint,
22
+ branch,
23
+ cacheDirectory,
24
+ commonLinterRepoName
25
+ } = require('../../../jsonUtils/commonLinterRepoDetails');
26
+ /**
27
+ * @function cloneViaCdt - Using the "clint development tool" clones the common linter_configuration repo into precommit library
28
+ * @returns {boolean} - indicating the success or failure of the cloning process
29
+ */
30
+
31
+ function cloneViaCdt() {
32
+ removeFolder(getDeleteDirPath());
33
+ const commandToCloneCommonConfigRepo = `npx cdt clone --clone:type=${type} --clone:url=${endPoint} --clone:branch=${branch} --clone:cacheDir=${cacheDirectory} --clone:proj:name=${commonLinterRepoName}`;
34
+ let isCommonConfigurationClonedSuccessfully = executeSynchronizedCommands(execSync, [commandToCloneCommonConfigRepo, {
35
+ cwd: getClonedDirPath()
36
+ }], `Lint Configuration Cloned Successfully - ${getRepoName() || 'common'}`, 'Could not clone the linters common repo', false, true);
37
+ return isCommonConfigurationClonedSuccessfully;
38
+ }
39
+ module.exports = {
40
+ cloneViaCdt
41
+ };
@@ -0,0 +1,54 @@
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
+ };
@@ -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
+ };