@zohodesk/codestandard-validator 1.0.0 → 1.1.1

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