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

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.
@@ -16,6 +16,15 @@ const {
16
16
  const {
17
17
  runLintWorkflow
18
18
  } = require("./lint");
19
+ process.env.DECRYPT_SONARQUBE = 7;
20
+ process.env.DECRYPT_TOKEN = 12;
21
+ global.analytics = {
22
+ status: "SUCCESS",
23
+ sonarQubeStatus: false,
24
+ message: "No issues are found, your code adheres to the required standards.",
25
+ isExemptionApproved: false,
26
+ totalIssues: 0
27
+ };
19
28
  async function preCommitHook() {
20
29
  Logger.log(Logger.INFO_TYPE, "Executing pre commit hook...");
21
30
  Logger.log(Logger.INFO_TYPE, `working dir: ${process.cwd()}`);
@@ -32,10 +41,10 @@ async function preCommitHook() {
32
41
  const branch = await safeGetBranch();
33
42
  const shouldAbort = await runLintWorkflow(JsFiles, branch);
34
43
  if (shouldAbort) {
35
- Logger.log(Logger.FAILURE_TYPE, "There are linter errors/warnings. Commit aborted.");
44
+ Logger.log(Logger.FAILURE_TYPE, "There are linter errors/warnings. Commit aborted 🙁.");
36
45
  process.exit(1);
37
46
  }
38
- Logger.log(Logger.SUCCESS_TYPE, "Commit Successful");
47
+ Logger.log(Logger.SUCCESS_TYPE, `Code is good to go 🙂`);
39
48
  process.exit(0);
40
49
  }
41
50
  preCommitHook();
@@ -4,8 +4,22 @@ const {
4
4
  Logger
5
5
  } = require("../../utils/Logger/Logger");
6
6
  const {
7
- calculateGitDiffForFile
8
- } = require("./lint");
7
+ exec
8
+ } = require('child_process');
9
+ const {
10
+ promisify
11
+ } = require('util');
12
+ const execAsync = promisify(exec);
13
+ async function calculateGitDiffForFile(branch, file) {
14
+ try {
15
+ const {
16
+ stdout
17
+ } = await execAsync(`git diff -U0 ${branch.trim()} ${file}`);
18
+ return stdout;
19
+ } catch (err) {
20
+ throw err;
21
+ }
22
+ }
9
23
  function parseDiffHunks(diff) {
10
24
  return diff.filter(line => line.startsWith("@@")).map(hunk => {
11
25
  const [start, count = 1] = hunk.split(" ")[2].slice(1).split(",").map(Number);
@@ -20,10 +34,6 @@ async function filterErrorsByChangedLines(errors, branch, file) {
20
34
  return changedRanges.some(([s, e]) => line >= s && line <= e);
21
35
  });
22
36
  }
23
- async function createBranchDiff(diff) {
24
- // const diff = await calculateGitDiffForFile(branch, file);
25
- // const changeset = extractDiffHunks(diff)
26
- }
27
37
  function filterFileLevelErrors(errors) {
28
38
  return errors.slice(1, -2); // strip ESLint summary lines
29
39
  }
@@ -35,5 +45,6 @@ module.exports = {
35
45
  filterErrorsByChangedLines,
36
46
  filterFileLevelErrors,
37
47
  logErrors,
38
- parseDiffHunks
48
+ parseDiffHunks,
49
+ calculateGitDiffForFile
39
50
  };
@@ -2,45 +2,48 @@
2
2
 
3
3
  const {
4
4
  exec
5
- } = require("child_process");
5
+ } = require('child_process');
6
6
  const {
7
7
  promisify
8
- } = require("util");
9
- const fs = require("fs");
10
- const path = require("path");
8
+ } = require('util');
9
+ const fs = require('fs');
10
+ const path = require('path');
11
11
  const {
12
12
  getNodeModulesPath
13
- } = require("../../utils/General/getNodeModulesPath");
13
+ } = require('../../utils/General/getNodeModulesPath');
14
14
  const {
15
15
  getEslintExecutablePath
16
- } = require("../../utils/ConfigFileUtils/getEslintExecutablePath");
16
+ } = require('../../utils/ConfigFileUtils/getEslintExecutablePath');
17
17
  const {
18
18
  getRootDirectory
19
- } = require("../../utils/General/RootDirectoryUtils/getRootDirectory");
19
+ } = require('../../utils/General/RootDirectoryUtils/getRootDirectory');
20
20
  const {
21
21
  getSupportedLanguage
22
- } = require("../../utils/General/getGeneralInfo");
22
+ } = require('../../utils/General/getGeneralInfo');
23
23
  const {
24
- filterFileLevelErrors,
25
- filterErrorsByChangedLines,
26
- logErrors
27
- } = require("./errorhelpers");
24
+ calculateGitDiffForFile
25
+ } = require('./errorhelpers');
28
26
  const {
29
- Execution
30
- } = require("@zohodesk/codestandard-analytics");
27
+ Execution,
28
+ SonarQube,
29
+ EsLint
30
+ } = require('@zohodesk/codestandard-analytics');
31
31
  const {
32
32
  getBranchName
33
- } = require("../../utils/GitActions/gitActions");
33
+ } = require('../../utils/GitActions/gitActions');
34
34
  const {
35
35
  extractDiffHunks
36
- } = require("./utils");
36
+ } = require('./utils');
37
+ const {
38
+ Logger
39
+ } = require('../../utils/Logger/Logger');
37
40
  const execAsync = promisify(exec);
38
41
  async function lintFiles(filePath) {
39
42
  const ext = path.extname(filePath);
40
- if ([".js", ".ts", ".tsx", ".jsx", ".properties"].includes(ext)) {
43
+ if (['.js', '.ts', '.tsx', '.jsx', '.properties'].includes(ext)) {
41
44
  return findEslintErrors(filePath);
42
45
  }
43
- if ([".css", ".scss"].includes(ext)) {
46
+ if (['.css', '.scss'].includes(ext)) {
44
47
  return findStyleLintErrors(filePath);
45
48
  }
46
49
  return [];
@@ -51,42 +54,32 @@ async function findEslintErrors(file) {
51
54
  const eslintConfig = `${nodeModulesPath}/.eslintrc.js`;
52
55
  var rulesArrayReport = [];
53
56
  if (!fs.existsSync(nodeModulesPath)) {
54
- Logger.log(Logger.INFO_TYPE, "node_modules not found");
57
+ Logger.log(Logger.INFO_TYPE, 'node_modules not found');
55
58
  return [];
56
59
  }
57
60
  if (!fs.existsSync(eslintPath)) {
58
- Logger.log(Logger.INFO_TYPE, "Eslint executable not found. Make sure eslint plugin is installed");
61
+ Logger.log(Logger.INFO_TYPE, 'Eslint executable not found. Make sure eslint plugin is installed');
59
62
  return [];
60
63
  }
61
64
  return execAsync(`npx --ignore-existing "${eslintPath}" --config "${eslintConfig}" --no-inline-config --resolve-plugins-relative-to="${nodeModulesPath}/node_modules" ${file}`).then(({
62
65
  stderr
63
- }) => stderr ? stderr.trim().split("\n") : []).catch(err => {
66
+ }) => stderr ? stderr.trim().split('\n') : []).catch(err => {
64
67
  Logger.log(Logger.FAILURE_TYPE, err);
65
- throw new Error("Error executing eslint command");
68
+ throw new Error('Error executing eslint command');
66
69
  });
67
70
  }
68
71
  function findStyleLintErrors(filePath) {
69
- const configFile = path.resolve(getNodeModulesPath(), ".stylelintrc.js");
72
+ const configFile = path.resolve(getNodeModulesPath(), '.stylelintrc.js');
70
73
  const absolutePath = path.join(getRootDirectory(), filePath);
71
74
  return execAsync(`npx stylelint ${absolutePath} --config ${configFile}`, {
72
75
  cwd: getNodeModulesPath()
73
76
  }).then(({
74
77
  stdout
75
- }) => stdout ? stdout.trim().split("\n") : []).catch(err => {
78
+ }) => stdout ? stdout.trim().split('\n') : []).catch(err => {
76
79
  Logger.log(Logger.FAILURE_TYPE, err);
77
80
  return [];
78
81
  });
79
82
  }
80
- async function calculateGitDiffForFile(branch, file) {
81
- try {
82
- const {
83
- stdout
84
- } = await execAsync(`git diff -U0 ${branch.trim()} ${file}`);
85
- return stdout;
86
- } catch (err) {
87
- throw err;
88
- }
89
- }
90
83
  async function runLintWorkflow(files, branch) {
91
84
  const branchDiff = {
92
85
  diffs: []
@@ -111,18 +104,22 @@ async function runLintWorkflow(files, branch) {
111
104
  // shouldAbort ||= shouldWarningsAbortCommit || !isOnlyWarnings(filteredErrors);
112
105
  // }
113
106
  }
114
- const diffPath = path.resolve(getNodeModulesPath(), "diffBranch.json");
115
- fs.writeFileSync(diffPath, branchDiff);
116
- const execute = new Execution(EsLint, SonarQube, $cliObjects);
117
- await execute.executeLintHandler().finally(() => {
118
- execute.executeMetricHandler();
107
+ const diffPath = path.resolve(getNodeModulesPath(), 'diffBranch.json');
108
+ fs.writeFileSync(diffPath, JSON.stringify(branchDiff));
109
+ const cliobj = {
110
+ env: 'ci',
111
+ cmdExecuted: 'dev-ci'
112
+ };
113
+ const execute = new Execution(EsLint, SonarQube, cliobj);
114
+ await execute.executeLintHandler().finally(async () => {
115
+ await execute.executeMetricHandler();
119
116
  });
117
+ Logger.log(Logger.INFO_TYPE, global.analytics);
120
118
  return global.analytics.status == 'FAILURE' ? true : false;
121
119
  }
122
120
  module.exports = {
123
121
  runLintWorkflow,
124
122
  lintFiles,
125
123
  findEslintErrors,
126
- findStyleLintErrors,
127
- calculateGitDiffForFile
124
+ findStyleLintErrors
128
125
  };
@@ -1,369 +1,375 @@
1
- "use strict";
1
+ // const {exec} = require('child_process')
2
+ // const fs = require('fs')
3
+ // const path = require('path')
4
+ // const { getEslintExecutablePath } = require('../../utils/ConfigFileUtils/getEslintExecutablePath')
5
+ // const { getNodeModulesPath } = require('../../utils/General/getNodeModulesPath')
6
+ // const { filterFiles } = require('../../utils/FileAndFolderOperations/filterFiles')
7
+ // const { Logger } = require('../../utils/Logger/Logger')
8
+ // const { checkIfPluginsAreInstalled } = require('../../utils/PluginsInstallation/checkIfPluginsAreInstalled')
9
+ // const { getBranchName } = require('../../utils/GitActions/gitActions')
10
+ // const { getConfigurationPrecommit, getSupportedLanguage } = require('../../utils/General/getGeneralInfo')
11
+ // const { getRootDirectory } = require('../../utils/General/RootDirectoryUtils/getRootDirectory')
12
+ // const { impactBasedPrecommit, shouldWarningsAbortCommit } = getConfigurationPrecommit()
2
13
 
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/ConfigFileUtils/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
- const {
27
- getConfigurationPrecommit,
28
- getSupportedLanguage
29
- } = require('../../utils/General/getGeneralInfo');
30
- const {
31
- getRootDirectory
32
- } = require('../../utils/General/RootDirectoryUtils/getRootDirectory');
33
- const {
34
- impactBasedPrecommit,
35
- shouldWarningsAbortCommit
36
- } = getConfigurationPrecommit();
14
+ // /**
15
+ // * @function isMergeCommit - This method check whether it is merge or not
16
+ // * @returns {Boolean} - return boolean based on latest merge changes
17
+ // */
18
+ // async function isMergeCommit() {
19
+ // return new Promise((resolve, reject) => {
20
+ // exec('git rev-parse -q --verify MERGE_HEAD', (error,stderr,stdout) => {
21
+ // if(error){
22
+ // reject(error.toString().trim())
23
+ // }
24
+ // else if(stderr){
25
+ // resolve(stderr.trim())
26
+ // }
27
+ // else if(stdout){
28
+ // resolve(stdout.trim())
29
+ // }
30
+ // })
31
+ // })
37
32
 
38
- /**
39
- * @function isMergeCommit - This method check whether it is merge or not
40
- * @returns {Boolean} - return boolean based on latest merge changes
41
- */
42
- async function isMergeCommit() {
43
- return new Promise((resolve, reject) => {
44
- exec('git rev-parse -q --verify MERGE_HEAD', (error, stderr, stdout) => {
45
- if (error) {
46
- reject(error.toString().trim());
47
- } else if (stderr) {
48
- resolve(stderr.trim());
49
- } else if (stdout) {
50
- resolve(stdout.trim());
51
- }
52
- });
53
- });
54
- }
33
+ // }
55
34
 
56
- /**
57
- * @function {getStagedFiles} - methods return staged files
58
- * @returns {Array<string>} - array of files
59
- */
35
+ // /**
36
+ // * @function {getStagedFiles} - methods return staged files
37
+ // * @returns {Array<string>} - array of files
38
+ // */
60
39
 
61
- async function getStagedFiles() {
62
- return new Promise((resolve, reject) => {
63
- exec("git diff --staged --name-only", (error, stderr, stdout) => {
64
- if (error) {
65
- if (error != null) reject("Couldn't fetch staged files");
66
- } else if (stderr) {
67
- resolve(filterDeltedFileFromStagedFiles(stderr.trim().split('\n')));
68
- } else if (stdout.trim() === '') {
69
- resolve(stdout.trim());
70
- }
71
- });
72
- });
73
- }
40
+ // async function getStagedFiles(){
41
+ // return new Promise((resolve, reject) => {
42
+ // exec("git diff --staged --name-only",(error,stderr,stdout) =>{
43
+ // if (error){
44
+ // if(error != null)
45
+ // reject("Couldn't fetch staged files")
46
+ // }
47
+ // else if(stderr){
48
+ // resolve(filterDeltedFileFromStagedFiles(stderr.trim().split('\n')))
49
+ // }
50
+ // else if(stdout.trim() === ''){
51
+ // resolve(stdout.trim())
52
+ // }
53
+ // })
54
+ // })
74
55
 
75
- /**
76
- * @function {filterDeltedFileFromStagedFiles} - filter deleted staged files
77
- * @param {Array<string>} files - staged files
78
- * @returns
79
- */
80
- function filterDeltedFileFromStagedFiles(files) {
81
- return files.filter(file => {
82
- const absolutePath = path.resolve(getRootDirectory(), file);
83
- if (fs.existsSync(absolutePath)) {
84
- return true;
85
- }
86
- return false;
87
- });
88
- }
89
- async function lintFiles(filePath) {
90
- switch (String(path.extname(filePath))) {
91
- case '.js':
92
- case '.ts':
93
- case '.tsx':
94
- case '.jsx':
95
- case '.properties':
96
- {
97
- return await findEslintErrors(filePath);
98
- }
99
- case '.css':
100
- case '.scss':
101
- {
102
- return await findStyleLintErrors(filePath);
103
- }
104
- default:
105
- {
106
- return [];
107
- }
108
- }
109
- }
56
+ // }
110
57
 
111
- /**
112
- * @function findEslintErrors - method Lint given file based on given configuration
113
- * @param {*} file - path of file to lint
114
- * @returns {Array<string>} - array of command line report as a string
115
- */
58
+ // /**
59
+ // * @function {filterDeltedFileFromStagedFiles} - filter deleted staged files
60
+ // * @param {Array<string>} files - staged files
61
+ // * @returns
62
+ // */
63
+ // function filterDeltedFileFromStagedFiles(files){
64
+ // return files.filter((file) =>{
65
+ // const absolutePath= path.resolve(getRootDirectory(),file)
66
+ // if(fs.existsSync(absolutePath)){
67
+ // return true
68
+ // }
69
+ // return false
70
+ // })
71
+ // }
116
72
 
117
- function findEslintErrors(file) {
118
- let nodeModulesPathOfProject = `${getNodeModulesPath()}`;
119
- let eslintExecutablePath = getEslintExecutablePath();
120
- let eslintConfigurationFilePath = `${nodeModulesPathOfProject}/.eslintrc.js`;
121
- let isEslintExecutablePresent = fs.existsSync(eslintExecutablePath) ? true : false;
122
- let isNodeModulesPresent = fs.existsSync(nodeModulesPathOfProject);
123
- if (isNodeModulesPresent) {
124
- if (isEslintExecutablePresent) {
125
- return new Promise((resolve, reject) => {
126
- exec(`npx --ignore-existing "${eslintExecutablePath}" --config "${eslintConfigurationFilePath}" --no-inline-config --resolve-plugins-relative-to="${nodeModulesPathOfProject}/node_modules" ${file}`, (error, stderr, stdout) => {
127
- if (stderr) {
128
- resolve(stderr.trim().split('\n'));
129
- } else if (error) {
130
- Logger.log(Logger.FAILURE_TYPE, error);
131
- reject("Error executing eslint command");
132
- } else {
133
- resolve([]);
134
- }
135
- });
136
- });
137
- } else {
138
- Logger.log(Logger.INFO_TYPE, 'Eslint executable not found. make sure eslint plugin is installed');
139
- }
140
- } else {
141
- Logger.log(Logger.INFO_TYPE, 'node_modules not found');
142
- }
143
- }
73
+ // async function lintFiles(filePath){
74
+ // switch(String(path.extname(filePath))){
75
+ // case '.js':
76
+ // case'.ts':
77
+ // case '.tsx':
78
+ // case '.jsx' :
79
+ // case '.properties' : {
80
+ // return await findEslintErrors(filePath )
81
+ // }
144
82
 
145
- /**
146
- *
147
- * @param {*} params
148
- */
149
- function findStyleLintErrors(filePath) {
150
- const configFilePath = path.resolve(getNodeModulesPath(), '.stylelintrc.js');
151
- const absolutePath = path.join(getRootDirectory(), filePath);
152
- try {
153
- return new Promise((resolve, reject) => {
154
- exec(`npx stylelint ${absolutePath} --config ${configFilePath}`, {
155
- cwd: getNodeModulesPath()
156
- }, (error, stderr, stdout) => {
157
- if (stdout) {
158
- resolve(stdout.trim().split('\n'));
159
- }
160
- // if(stderr){
161
- // resolve(stderr.trim().split('\n'))
162
- // }
163
- else if (error) {
164
- Logger.log(Logger.FAILURE_TYPE, error);
165
- reject("Error executing stylelint command");
166
- } else {
167
- resolve([]);
168
- }
169
- });
170
- });
171
- } catch (error) {
172
- Logger.log(Logger.FAILURE_TYPE, `Issue is lint css files`);
173
- return [];
174
- }
175
- }
83
+ // case '.css':
84
+ // case '.scss' :{
85
+ // return await findStyleLintErrors(filePath)
86
+ // }
87
+ // default : {
88
+ // return []
89
+ // }
90
+ // }
91
+ // }
176
92
 
177
- /**
178
- * @function {calculateGitDiffForFile} - method calculate diff of file
179
- * @param {*} branch_name - branch name
180
- * @param {*} file - path of file
181
- * @returns {Promise<Array<string>>} - array of command line report as a string
182
- */
183
- async function calculateGitDiffForFile(branch_name, file) {
184
- let gitDiffCommand = `git diff -U0 ${branch_name.trim()} ${file}`;
185
- return new Promise((resolve, reject) => {
186
- exec(gitDiffCommand, (error, stderr) => {
187
- if (stderr) {
188
- resolve(stderr.trim().split('\n'));
189
- } else if (error) {
190
- reject(error);
191
- }
192
- });
193
- });
194
- }
195
- /**
196
- * @function {areAllPluginsInstalled} - method whether plugin is installed or not
197
- * @returns {Boolean} - return boolean based on plugin installed or not
198
- */
93
+ // /**
94
+ // * @function findEslintErrors - method Lint given file based on given configuration
95
+ // * @param {*} file - path of file to lint
96
+ // * @returns {Array<string>} - array of command line report as a string
97
+ // */
199
98
 
200
- function areAllPluginsInstalled() {
201
- let unInstalledPlugins = checkIfPluginsAreInstalled().uninstalledPlugins;
202
- return unInstalledPlugins.length === 0 ? true : false;
203
- }
99
+ // function findEslintErrors(file){
100
+ // let nodeModulesPathOfProject = `${getNodeModulesPath()}`
101
+ // let eslintExecutablePath = getEslintExecutablePath()
102
+ // let eslintConfigurationFilePath = `${nodeModulesPathOfProject}/.eslintrc.js`
103
+ // let isEslintExecutablePresent = fs.existsSync(eslintExecutablePath) ? true : false
104
+ // let isNodeModulesPresent = fs.existsSync(nodeModulesPathOfProject)
204
105
 
205
- /**
206
- * @function {isOnlyWarningsPresentInFile} - method that checks if only eslint warnings are present in a file
207
- * @returns {Boolean} - returns boolean based on only warnings present or not in file
208
- */
209
- function isOnlyWarningsPresentInFile(eslintErrorsPresent) {
210
- let severityOfEachErrorInFile = [];
211
- eslintErrorsPresent.map(error => {
212
- let partsInString = error.split(" ");
213
- let severityOfError = partsInString.find(word => word === 'error' || word === 'warning' || word === '✖');
214
- severityOfEachErrorInFile.push(severityOfError);
215
- });
216
- return !(severityOfEachErrorInFile.includes('✖') || severityOfEachErrorInFile.includes('error'));
217
- }
106
+ // if(isNodeModulesPresent){
107
+ // if(isEslintExecutablePresent){
108
+ // return new Promise ((resolve, reject) => {
109
+ // exec(`npx --ignore-existing "${eslintExecutablePath}" --config "${eslintConfigurationFilePath}" --no-inline-config --resolve-plugins-relative-to="${nodeModulesPathOfProject}/node_modules" ${file}`,(error,stderr,stdout) => {
110
+ // if(stderr){
111
+ // resolve(stderr.trim().split('\n'))
112
+ // }
113
+ // else if(error){
114
+ // Logger.log(Logger.FAILURE_TYPE,error)
115
+ // reject("Error executing eslint command")
116
+ // }
117
+ // else{
118
+ // resolve([])
119
+ // }
120
+ // })
121
+ // })
122
+ // }
123
+ // else{
124
+ // Logger.log(Logger.INFO_TYPE,'Eslint executable not found. make sure eslint plugin is installed')
125
+ // }
126
+ // }
127
+ // else{
128
+ // Logger.log(Logger.INFO_TYPE,'node_modules not found')
129
+ // }
130
+ // }
218
131
 
219
- /**
220
- * @function {preCommitHook} - method execute pre commit hook
221
- * @returns {void}
222
- */
132
+ // /**
133
+ // *
134
+ // * @param {*} params
135
+ // */
136
+ // function findStyleLintErrors(filePath) {
137
+ // const configFilePath = path.resolve(getNodeModulesPath(),'.stylelintrc.js')
138
+ // const absolutePath = path.join(getRootDirectory(),filePath)
139
+ // try{
140
+ // return new Promise ((resolve, reject) => {
141
+ // exec(`npx stylelint ${absolutePath} --config ${configFilePath}`,{cwd:getNodeModulesPath()},(error,stderr,stdout) => {
142
+ // if(stdout){
143
+ // resolve(stdout.trim().split('\n'))
144
+ // }
145
+ // // if(stderr){
146
+ // // resolve(stderr.trim().split('\n'))
147
+ // // }
148
+ // else if(error){
149
+ // Logger.log(Logger.FAILURE_TYPE,error)
150
+ // reject("Error executing stylelint command")
151
+ // }
152
+ // else{
153
+ // resolve([])
154
+ // }
155
+ // })
156
+ // })
157
+ // }catch(error){
158
+ // Logger.log(Logger.FAILURE_TYPE,`Issue is lint css files`)
159
+ // return []
160
+ // }
161
+ // }
223
162
 
224
- async function preCommitHook() {
225
- Logger.log(Logger.INFO_TYPE, 'Executing pre commit hook...');
226
- Logger.log(Logger.INFO_TYPE, `working dir : ${process.cwd()}`);
227
- try {
228
- let isMerge = await isMergeCommit();
229
- Logger.log(Logger.INFO_TYPE, 'Looks like you have merged. So skipping pre commit check');
230
- process.exit(0);
231
- } catch (error) {
232
- if (areAllPluginsInstalled()) {
233
- let staged_files = [];
234
- let eslintConfigFiles = ['.eslintrc.js'];
235
- let exemptionFiles = [];
236
- let current_branch = '';
237
- let hasEslintErrorsInChangedLines = false;
238
- let hasEslintErrorsInFiles = false;
239
- let areFilesStaged = false;
240
- let shouldAbortCommit = false;
241
- try {
242
- current_branch = await getBranchName();
243
- } catch {
244
- Logger.log(Logger.INFO_TYPE, "Error fetching current branch");
245
- }
246
- try {
247
- staged_files = await getStagedFiles();
248
- if (!staged_files.length == 0) {
249
- const {
250
- JsFiles: staged_filesJS,
251
- CssFiles
252
- } = filterFiles(staged_files, eslintConfigFiles, true);
163
+ // /**
164
+ // * @function {calculateGitDiffForFile} - method calculate diff of file
165
+ // * @param {*} branch_name - branch name
166
+ // * @param {*} file - path of file
167
+ // * @returns {Promise<Array<string>>} - array of command line report as a string
168
+ // */
169
+ // async function calculateGitDiffForFile(branch_name,file){
170
+ // let gitDiffCommand = `git diff -U0 ${branch_name.trim()} ${file}`
171
+ // return new Promise ((resolve,reject) => {
172
+ // exec(gitDiffCommand,(error, stderr) => {
173
+ // if(stderr){
174
+ // resolve(stderr.trim().split('\n'))
175
+ // }
176
+ // else if(error) {
177
+ // reject(error)
178
+ // }
179
+ // })
180
+ // })
181
+ // }
182
+ // /**
183
+ // * @function {areAllPluginsInstalled} - method whether plugin is installed or not
184
+ // * @returns {Boolean} - return boolean based on plugin installed or not
185
+ // */
253
186
 
254
- // staged_filesJS = filterFiles(staged_filesJS,exemptionFiles) //this is the code for giving exemption to a file during pre commit
255
- // if(staged_filesJS.length === 0){
256
- // Logger.log(Logger.SUCCESS_TYPE,`Commit Successful`)
257
- // process.exit(0)
258
- // }
187
+ // function areAllPluginsInstalled(){
188
+ // let unInstalledPlugins = checkIfPluginsAreInstalled().uninstalledPlugins
189
+ // return unInstalledPlugins.length === 0 ? true : false
190
+ // }
259
191
 
260
- // CssFiles not Enabled For while
261
- areFilesStaged = true;
262
- var stagedFiles = [...staged_filesJS];
263
- for (let file in stagedFiles) {
264
- let currentFileName = stagedFiles[file];
265
- let changedLinesArray = [];
266
- let eslintErrorsInChangedLines = [];
267
- let isOnlyEslintWarningsPresentInFile = false;
268
- if (getSupportedLanguage().includes(path.extname(stagedFiles[file]))) {
269
- try {
270
- var errorsInFile = await lintFiles(stagedFiles[file]);
271
- // eslintErrorsInFile = impactBasedPrecommit == false ? filterWarningInFile(errorsInFile) : errorsInFile
272
- if (stagedFiles[file] && typeof stagedFiles[file] == 'string') {
273
- if (!errorsInFile.length == 0) {
274
- //Calculating changed lines in a file and storing them in respective arrays
275
- if (impactBasedPrecommit) {
276
- //git diff is computed and stored in an array
277
- let git_diff = await calculateGitDiffForFile(current_branch, stagedFiles[file]);
278
- changedLinesArray = git_diff.filter(line => line.startsWith('@@'));
279
- let changedLinesStartArray = [];
280
- let changedLinesEndArray = [];
281
- for (let number of changedLinesArray) {
282
- let changesStartLine = parseInt(number.split(' ')[2].split(',')[0]);
283
- changedLinesStartArray.push(changesStartLine);
284
- let changesEndLine = number.split(' ')[2].split(',')[1];
285
- if (changesEndLine === undefined) {
286
- changedLinesEndArray.push(changesStartLine);
287
- } else {
288
- changedLinesEndArray.push(changesStartLine + parseInt(changesEndLine) - 1);
289
- }
290
- }
291
- for (let error = 1; error < errorsInFile.length - 2; error++) {
292
- //errorsInFile[error].trim() - 69:26 error => Do not hardcode content. Use I18N key instead no-hardcoding/no-hardcoding,
293
- //errorsInFile[error].trim().split(' ')[0] => 69:26
294
- //errorsInFile[error].trim().split(' ')[0].split(':')[0] => 69
192
+ // /**
193
+ // * @function {isOnlyWarningsPresentInFile} - method that checks if only eslint warnings are present in a file
194
+ // * @returns {Boolean} - returns boolean based on only warnings present or not in file
195
+ // */
196
+ // function isOnlyWarningsPresentInFile(eslintErrorsPresent){
197
+ // let severityOfEachErrorInFile = []
198
+ // eslintErrorsPresent.map(error => {
199
+ // let partsInString = error.split(" ")
200
+ // let severityOfError = partsInString.find(word => word === 'error' || word === 'warning'|| word === '✖')
201
+ // severityOfEachErrorInFile.push(severityOfError)
202
+ // })
203
+ // return !(severityOfEachErrorInFile.includes('✖') || severityOfEachErrorInFile.includes('error'))
204
+ // }
295
205
 
296
- let eslintErrorLineNumber = errorsInFile[error].trim().split(' ')[0].split(':')[0];
297
- for (let lineNumber in changedLinesStartArray) {
298
- if (eslintErrorLineNumber >= changedLinesStartArray[lineNumber] && eslintErrorLineNumber <= changedLinesEndArray[lineNumber]) {
299
- eslintErrorsInChangedLines.push(errorsInFile[error]);
300
- }
301
- }
302
- }
303
- if (eslintErrorsInChangedLines.length > 0) {
304
- isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(eslintErrorsInChangedLines);
305
- Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
306
- for (let eslintError of eslintErrorsInChangedLines) {
307
- Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
308
- }
309
- if (shouldWarningsAbortCommit) {
310
- hasEslintErrorsInChangedLines = true;
311
- shouldAbortCommit = true;
312
- } else if (!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile) {
313
- hasEslintErrorsInChangedLines = false;
314
- } else if (!shouldWarningsAbortCommit && !isOnlyEslintWarningsPresentInFile) {
315
- hasEslintErrorsInChangedLines = true;
316
- shouldAbortCommit = true;
317
- }
318
- }
319
- } else {
320
- if (errorsInFile.length > 0) {
321
- let startIndex = 1;
322
- let endIndex = errorsInFile.length - 2;
323
- let listOsEslintErrors = errorsInFile.slice(startIndex, endIndex);
324
- isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(listOsEslintErrors);
325
- Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${currentFileName}\x1b[0m`);
326
- for (let eslintError of listOsEslintErrors) {
327
- Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${eslintError.trimEnd()}\x1b[0m`);
328
- }
329
- if (shouldWarningsAbortCommit) {
330
- hasEslintErrorsInFiles = true;
331
- shouldAbortCommit = true;
332
- } else if (!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile) {
333
- hasEslintErrorsInFiles = false;
334
- } else if (!shouldWarningsAbortCommit && !isOnlyEslintWarningsPresentInFile) {
335
- hasEslintErrorsInFiles = true;
336
- shouldAbortCommit = true;
337
- }
338
- }
339
- }
340
- }
341
- }
342
- } catch (err) {
343
- Logger.log(Logger.FAILURE_TYPE, err);
344
- Logger.log(Logger.FAILURE_TYPE, "Error in executing lint command");
345
- }
346
- }
347
- }
348
- } else if (staged_files.length === 0) {
349
- Logger.log(Logger.INFO_TYPE, 'No files have been staged. Stage your files before committing');
350
- }
351
- } catch {
352
- Logger.log(Logger.INFO_TYPE, 'Error executing pre commit hook');
353
- }
354
- if (shouldAbortCommit) {
355
- Logger.log(Logger.FAILURE_TYPE, `There are linter errors/warnings present. So commit is aborted.`);
356
- process.exit(1);
357
- } else if (shouldAbortCommit === false && staged_files.length !== 0) {
358
- Logger.log(Logger.SUCCESS_TYPE, `Commit Successful`);
359
- process.exit(0);
360
- }
361
- } else {
362
- Logger.log(Logger.FAILURE_TYPE, 'Commit failed since some lint plugins are not installed');
363
- 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`);
364
- Logger.log(Logger.INFO_TYPE, 'Execute the command and kindly try committing again.');
365
- process.exit(1);
366
- }
367
- }
368
- }
369
- preCommitHook();
206
+ // /**
207
+ // * @function {preCommitHook} - method execute pre commit hook
208
+ // * @returns {void}
209
+ // */
210
+
211
+ // async function preCommitHook() {
212
+ // Logger.log(Logger.INFO_TYPE,'Executing pre commit hook...')
213
+ // Logger.log(Logger.INFO_TYPE,`working dir : ${process.cwd()}`)
214
+ // try{
215
+ // let isMerge = await isMergeCommit();
216
+ // Logger.log(Logger.INFO_TYPE,'Looks like you have merged. So skipping pre commit check');
217
+ // process.exit(0);
218
+ // }
219
+ // catch(error){
220
+ // if(areAllPluginsInstalled()){
221
+ // let staged_files = []
222
+ // let eslintConfigFiles = ['.eslintrc.js']
223
+ // let exemptionFiles = []
224
+ // let current_branch = ''
225
+ // let hasEslintErrorsInChangedLines = false
226
+ // let hasEslintErrorsInFiles = false
227
+ // let areFilesStaged = false
228
+ // let shouldAbortCommit = false
229
+ // try{
230
+ // current_branch = await getBranchName()
231
+ // }
232
+ // catch{
233
+ // Logger.log(Logger.INFO_TYPE,"Error fetching current branch")
234
+ // }
235
+ // try{
236
+ // staged_files = await getStagedFiles()
237
+
238
+ // if(!staged_files.length == 0){
239
+ // const {JsFiles:staged_filesJS, CssFiles} = filterFiles(staged_files,eslintConfigFiles,true)
240
+
241
+ // // staged_filesJS = filterFiles(staged_filesJS,exemptionFiles) //this is the code for giving exemption to a file during pre commit
242
+ // // if(staged_filesJS.length === 0){
243
+ // // Logger.log(Logger.SUCCESS_TYPE,`Commit Successful`)
244
+ // // process.exit(0)
245
+ // // }
246
+
247
+ // // CssFiles not Enabled For while
248
+ // areFilesStaged = true
249
+ // var stagedFiles = [...staged_filesJS]
250
+ // for (let file in stagedFiles){
251
+ // let currentFileName = stagedFiles[file]
252
+ // let changedLinesArray = []
253
+ // let eslintErrorsInChangedLines = []
254
+ // let isOnlyEslintWarningsPresentInFile = false
255
+
256
+ // if(getSupportedLanguage().includes(path.extname(stagedFiles[file]) )){
257
+ // try{
258
+ // var errorsInFile= await lintFiles(stagedFiles[file])
259
+ // // eslintErrorsInFile = impactBasedPrecommit == false ? filterWarningInFile(errorsInFile) : errorsInFile
260
+ // if(stagedFiles[file] && typeof(stagedFiles[file]) == 'string'){
261
+ // if(! errorsInFile.length == 0){
262
+ // //Calculating changed lines in a file and storing them in respective arrays
263
+ // if(impactBasedPrecommit) {
264
+
265
+ // //git diff is computed and stored in an array
266
+ // let git_diff = await calculateGitDiffForFile(current_branch,stagedFiles[file])
267
+ // changedLinesArray = git_diff.filter((line) => line.startsWith('@@'))
268
+
269
+ // let changedLinesStartArray = []
270
+ // let changedLinesEndArray = []
271
+
272
+ // for (let number of changedLinesArray){
273
+ // let changesStartLine = parseInt(number.split(' ')[2].split(',')[0])
274
+ // changedLinesStartArray.push(changesStartLine)
275
+ // let changesEndLine = number.split(' ')[2].split(',')[1]
276
+ // if(changesEndLine === undefined){
277
+ // changedLinesEndArray.push(changesStartLine)
278
+ // }
279
+ // else{
280
+ // changedLinesEndArray.push(changesStartLine + parseInt(changesEndLine) - 1)
281
+ // }
282
+ // }
283
+ // for (let error=1; error < errorsInFile.length - 2; error++){
284
+ // //errorsInFile[error].trim() - 69:26 error => Do not hardcode content. Use I18N key instead no-hardcoding/no-hardcoding,
285
+ // //errorsInFile[error].trim().split(' ')[0] => 69:26
286
+ // //errorsInFile[error].trim().split(' ')[0].split(':')[0] => 69
287
+
288
+ // let eslintErrorLineNumber = errorsInFile[error].trim().split(' ')[0].split(':')[0]
289
+
290
+ // for(let lineNumber in changedLinesStartArray){
291
+ // if(eslintErrorLineNumber >= changedLinesStartArray[lineNumber] &&
292
+ // eslintErrorLineNumber <= changedLinesEndArray[lineNumber]){
293
+ // eslintErrorsInChangedLines.push(errorsInFile[error])
294
+ // }
295
+ // }
296
+ // }
297
+ // if(eslintErrorsInChangedLines.length > 0){
298
+ // isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(eslintErrorsInChangedLines)
299
+ // Logger.log(Logger.FAILURE_TYPE,`\x1b[1m${currentFileName}\x1b[0m`)
300
+ // for(let eslintError of eslintErrorsInChangedLines){
301
+ // Logger.log(Logger.FAILURE_TYPE,`\x1b[37m${eslintError.trimEnd()}\x1b[0m`)
302
+ // }
303
+ // if(shouldWarningsAbortCommit){
304
+ // hasEslintErrorsInChangedLines = true
305
+ // shouldAbortCommit = true
306
+ // }
307
+ // else if(!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile){
308
+ // hasEslintErrorsInChangedLines = false
309
+ // }
310
+ // else if(!shouldWarningsAbortCommit && !isOnlyEslintWarningsPresentInFile){
311
+ // hasEslintErrorsInChangedLines = true
312
+ // shouldAbortCommit = true
313
+ // }
314
+ // }
315
+ // }else{
316
+ // if(errorsInFile.length > 0 ){
317
+ // let startIndex = 1
318
+ // let endIndex = errorsInFile.length - 2
319
+ // let listOsEslintErrors = errorsInFile.slice(startIndex,endIndex)
320
+ // isOnlyEslintWarningsPresentInFile = isOnlyWarningsPresentInFile(listOsEslintErrors)
321
+ // Logger.log(Logger.FAILURE_TYPE,`\x1b[1m${currentFileName}\x1b[0m`)
322
+ // for(let eslintError of listOsEslintErrors){
323
+ // Logger.log(Logger.FAILURE_TYPE,`\x1b[37m${eslintError.trimEnd()}\x1b[0m`)
324
+ // }
325
+ // if(shouldWarningsAbortCommit){
326
+ // hasEslintErrorsInFiles = true
327
+ // shouldAbortCommit = true
328
+ // }
329
+ // else if(!shouldWarningsAbortCommit && isOnlyEslintWarningsPresentInFile){
330
+ // hasEslintErrorsInFiles = false
331
+ // }
332
+ // else if(!shouldWarningsAbortCommit && !isOnlyEslintWarningsPresentInFile){
333
+ // hasEslintErrorsInFiles = true
334
+ // shouldAbortCommit = true
335
+ // }
336
+ // }
337
+ // }
338
+ // }
339
+ // }
340
+ // }
341
+ // catch(err){
342
+ // Logger.log(Logger.FAILURE_TYPE,err)
343
+ // Logger.log(Logger.FAILURE_TYPE,"Error in executing lint command")
344
+ // }
345
+
346
+ // }
347
+ // }
348
+ // }
349
+ // else if(staged_files.length === 0){
350
+ // Logger.log(Logger.INFO_TYPE,'No files have been staged. Stage your files before committing')
351
+ // }
352
+ // }
353
+ // catch{
354
+ // Logger.log(Logger.INFO_TYPE,'Error executing pre commit hook')
355
+ // }
356
+ // if(shouldAbortCommit){
357
+ // Logger.log(Logger.FAILURE_TYPE, `There are linter errors/warnings present. So commit is aborted.`);
358
+ // process.exit(1);
359
+ // }
360
+ // else if(shouldAbortCommit === false && staged_files.length !== 0){
361
+ // Logger.log(Logger.SUCCESS_TYPE, `Commit Successful`);
362
+ // process.exit(0);
363
+ // }
364
+ // }
365
+ // else{
366
+ // Logger.log(Logger.FAILURE_TYPE,'Commit failed since some lint plugins are not installed')
367
+ // 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`)
368
+ // Logger.log(Logger.INFO_TYPE,'Execute the command and kindly try committing again.')
369
+ // process.exit(1)
370
+ // }
371
+ // }
372
+ // }
373
+
374
+ // preCommitHook()
375
+ "use strict";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zohodesk/codestandard-validator",
3
- "version": "1.0.0-exp-1",
3
+ "version": "1.0.0-exp-3",
4
4
  "description": "library to enforce code standard using eslint",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "type": "commonjs",
17
17
  "dependencies": {
18
- "@zohodesk/codestandard-analytics":"1.0.2-exp-1",
18
+ "@zohodesk/codestandard-analytics":"1.0.2-exp-3",
19
19
  "@zohodesk-private/client_deployment_tool": "0.0.5",
20
20
  "eslint": "8.26.0",
21
21
  "stylelint":"16.23.0"