@zohodesk/codestandard-validator 0.0.7-exp-13 → 1.0.0-exp-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.
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const {
5
+ filterFiles
6
+ } = require("../../utils/FileAndFolderOperations/filterFiles");
7
+ const {
8
+ Logger
9
+ } = require("../../utils/Logger/Logger");
10
+ const {
11
+ handleMergeCommit,
12
+ ensurePluginsInstalled,
13
+ safeGetStagedFiles,
14
+ safeGetBranch
15
+ } = require("./guard");
16
+ const {
17
+ runLintWorkflow
18
+ } = require("./lint");
19
+ async function preCommitHook() {
20
+ Logger.log(Logger.INFO_TYPE, "Executing pre commit hook...");
21
+ Logger.log(Logger.INFO_TYPE, `working dir: ${process.cwd()}`);
22
+ if (await handleMergeCommit()) return;
23
+ if (!(await ensurePluginsInstalled())) return;
24
+ const stagedFiles = await safeGetStagedFiles();
25
+ if (stagedFiles.length === 0) {
26
+ Logger.log(Logger.INFO_TYPE, "No staged files. Commit skipped.");
27
+ return;
28
+ }
29
+ const {
30
+ JsFiles
31
+ } = filterFiles(stagedFiles, [".eslintrc.js"], true);
32
+ const branch = await safeGetBranch();
33
+ const shouldAbort = await runLintWorkflow(JsFiles, branch);
34
+ if (shouldAbort) {
35
+ Logger.log(Logger.FAILURE_TYPE, "There are linter errors/warnings. Commit aborted.");
36
+ process.exit(1);
37
+ }
38
+ Logger.log(Logger.SUCCESS_TYPE, "Commit Successful");
39
+ process.exit(0);
40
+ }
41
+ preCommitHook();
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+
3
+ const {
4
+ Logger
5
+ } = require("../../utils/Logger/Logger");
6
+ const {
7
+ calculateGitDiffForFile
8
+ } = require("./lint");
9
+ function parseDiffHunks(diff) {
10
+ return diff.filter(line => line.startsWith("@@")).map(hunk => {
11
+ const [start, count = 1] = hunk.split(" ")[2].slice(1).split(",").map(Number);
12
+ return [start, start + (count - 1)];
13
+ });
14
+ }
15
+ async function filterErrorsByChangedLines(errors, branch, file) {
16
+ const diff = await calculateGitDiffForFile(branch, file);
17
+ const changedRanges = parseDiffHunks(diff);
18
+ return errors.filter(err => {
19
+ const line = parseInt(err.split(" ")[0].split(":")[0], 10);
20
+ return changedRanges.some(([s, e]) => line >= s && line <= e);
21
+ });
22
+ }
23
+ async function createBranchDiff(diff) {
24
+ // const diff = await calculateGitDiffForFile(branch, file);
25
+ // const changeset = extractDiffHunks(diff)
26
+ }
27
+ function filterFileLevelErrors(errors) {
28
+ return errors.slice(1, -2); // strip ESLint summary lines
29
+ }
30
+ function logErrors(file, errors) {
31
+ Logger.log(Logger.FAILURE_TYPE, `\x1b[1m${file}\x1b[0m`);
32
+ errors.forEach(err => Logger.log(Logger.FAILURE_TYPE, `\x1b[37m${err.trimEnd()}\x1b[0m`));
33
+ }
34
+ module.exports = {
35
+ filterErrorsByChangedLines,
36
+ filterFileLevelErrors,
37
+ logErrors,
38
+ parseDiffHunks
39
+ };
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+
3
+ const {
4
+ getBranchName
5
+ } = require("../../utils/GitActions/gitActions");
6
+ const {
7
+ Logger
8
+ } = require("../../utils/Logger/Logger");
9
+ const {
10
+ isMergeCommit,
11
+ areAllPluginsInstalled,
12
+ getStagedFiles
13
+ } = require("./utils");
14
+ async function handleMergeCommit() {
15
+ if (await isMergeCommit()) {
16
+ Logger.log(Logger.INFO_TYPE, "Merge detected. Skipping pre-commit check.");
17
+ process.exit(0);
18
+ return true;
19
+ }
20
+ return false;
21
+ }
22
+ async function ensurePluginsInstalled() {
23
+ if (areAllPluginsInstalled()) return true;
24
+ Logger.log(Logger.FAILURE_TYPE, "Commit failed since some lint plugins are not installed");
25
+ Logger.log(Logger.INFO_TYPE, `Run \x1b[37mnpx ZDPrecommit setupPlugins \x1b[33m in the project root to install them.`);
26
+ process.exit(1);
27
+ return false;
28
+ }
29
+ async function safeGetStagedFiles() {
30
+ try {
31
+ return await getStagedFiles();
32
+ } catch {
33
+ Logger.log(Logger.INFO_TYPE, "Error fetching staged files");
34
+ process.exit(1);
35
+ }
36
+ }
37
+ async function safeGetBranch() {
38
+ try {
39
+ return await getBranchName();
40
+ } catch {
41
+ Logger.log(Logger.INFO_TYPE, "Error fetching current branch");
42
+ return "";
43
+ }
44
+ }
45
+ module.exports = {
46
+ safeGetBranch,
47
+ safeGetStagedFiles,
48
+ handleMergeCommit,
49
+ ensurePluginsInstalled
50
+ };
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+
3
+ const {
4
+ exec
5
+ } = require("child_process");
6
+ const {
7
+ promisify
8
+ } = require("util");
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const {
12
+ getNodeModulesPath
13
+ } = require("../../utils/General/getNodeModulesPath");
14
+ const {
15
+ getEslintExecutablePath
16
+ } = require("../../utils/ConfigFileUtils/getEslintExecutablePath");
17
+ const {
18
+ getRootDirectory
19
+ } = require("../../utils/General/RootDirectoryUtils/getRootDirectory");
20
+ const {
21
+ getSupportedLanguage
22
+ } = require("../../utils/General/getGeneralInfo");
23
+ const {
24
+ filterFileLevelErrors,
25
+ filterErrorsByChangedLines,
26
+ logErrors
27
+ } = require("./errorhelpers");
28
+ const {
29
+ Execution
30
+ } = require("@zohodesk/codestandard-analytics");
31
+ const {
32
+ getBranchName
33
+ } = require("../../utils/GitActions/gitActions");
34
+ const {
35
+ extractDiffHunks
36
+ } = require("./utils");
37
+ const execAsync = promisify(exec);
38
+ async function lintFiles(filePath) {
39
+ const ext = path.extname(filePath);
40
+ if ([".js", ".ts", ".tsx", ".jsx", ".properties"].includes(ext)) {
41
+ return findEslintErrors(filePath);
42
+ }
43
+ if ([".css", ".scss"].includes(ext)) {
44
+ return findStyleLintErrors(filePath);
45
+ }
46
+ return [];
47
+ }
48
+ async function findEslintErrors(file) {
49
+ const nodeModulesPath = getNodeModulesPath();
50
+ const eslintPath = getEslintExecutablePath();
51
+ const eslintConfig = `${nodeModulesPath}/.eslintrc.js`;
52
+ var rulesArrayReport = [];
53
+ if (!fs.existsSync(nodeModulesPath)) {
54
+ Logger.log(Logger.INFO_TYPE, "node_modules not found");
55
+ return [];
56
+ }
57
+ if (!fs.existsSync(eslintPath)) {
58
+ Logger.log(Logger.INFO_TYPE, "Eslint executable not found. Make sure eslint plugin is installed");
59
+ return [];
60
+ }
61
+ return execAsync(`npx --ignore-existing "${eslintPath}" --config "${eslintConfig}" --no-inline-config --resolve-plugins-relative-to="${nodeModulesPath}/node_modules" ${file}`).then(({
62
+ stderr
63
+ }) => stderr ? stderr.trim().split("\n") : []).catch(err => {
64
+ Logger.log(Logger.FAILURE_TYPE, err);
65
+ throw new Error("Error executing eslint command");
66
+ });
67
+ }
68
+ function findStyleLintErrors(filePath) {
69
+ const configFile = path.resolve(getNodeModulesPath(), ".stylelintrc.js");
70
+ const absolutePath = path.join(getRootDirectory(), filePath);
71
+ return execAsync(`npx stylelint ${absolutePath} --config ${configFile}`, {
72
+ cwd: getNodeModulesPath()
73
+ }).then(({
74
+ stdout
75
+ }) => stdout ? stdout.trim().split("\n") : []).catch(err => {
76
+ Logger.log(Logger.FAILURE_TYPE, err);
77
+ return [];
78
+ });
79
+ }
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
+ async function runLintWorkflow(files, branch) {
91
+ const branchDiff = {
92
+ diffs: []
93
+ };
94
+ let shouldAbort = false;
95
+ var branchName = getBranchName();
96
+ for (const file of files) {
97
+ if (!getSupportedLanguage().includes(path.extname(file))) continue;
98
+ const changeset = extractDiffHunks(await calculateGitDiffForFile(branchName, file));
99
+ const diff = {
100
+ old_path: file,
101
+ new_path: file,
102
+ diff: changeset
103
+ };
104
+ branchDiff.diffs.push(diff);
105
+ // const filteredErrors = impactBasedPrecommit
106
+ // ? await filterErrorsByChangedLines(errors, branch, file)
107
+ // : filterFileLevelErrors(errors);
108
+
109
+ // if (filteredErrors.length > 0) {
110
+ // logErrors(file, filteredErrors);
111
+ // shouldAbort ||= shouldWarningsAbortCommit || !isOnlyWarnings(filteredErrors);
112
+ // }
113
+ }
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();
119
+ });
120
+ return global.analytics.status == 'FAILURE' ? true : false;
121
+ }
122
+ module.exports = {
123
+ runLintWorkflow,
124
+ lintFiles,
125
+ findEslintErrors,
126
+ findStyleLintErrors,
127
+ calculateGitDiffForFile
128
+ };
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const {
4
- exec,
5
- execSync
4
+ exec
6
5
  } = require('child_process');
7
6
  const fs = require('fs');
8
7
  const path = require('path');
@@ -13,8 +12,7 @@ const {
13
12
  getNodeModulesPath
14
13
  } = require('../../utils/General/getNodeModulesPath');
15
14
  const {
16
- filterFiles,
17
- filterWarningInFile
15
+ filterFiles
18
16
  } = require('../../utils/FileAndFolderOperations/filterFiles');
19
17
  const {
20
18
  Logger
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+
3
+ const {
4
+ exec
5
+ } = require("child_process");
6
+ const {
7
+ promisify
8
+ } = require("util");
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const {
12
+ getRootDirectory
13
+ } = require("../../utils/General/RootDirectoryUtils/getRootDirectory");
14
+ const {
15
+ checkIfPluginsAreInstalled
16
+ } = require("../../utils/PluginsInstallation/checkIfPluginsAreInstalled");
17
+ const execAsync = promisify(exec);
18
+ async function isMergeCommit() {
19
+ try {
20
+ const {
21
+ stdout
22
+ } = await execAsync("git rev-parse -q --verify MERGE_HEAD");
23
+ return Boolean(stdout.trim());
24
+ } catch {
25
+ return false;
26
+ }
27
+ }
28
+ async function getStagedFiles() {
29
+ try {
30
+ const {
31
+ stdout
32
+ } = await execAsync("git diff --staged --name-only");
33
+ const files = stdout.trim().split("\n").filter(Boolean);
34
+ return files.filter(file => fs.existsSync(path.resolve(getRootDirectory(), file)));
35
+ } catch {
36
+ throw new Error("Couldn't fetch staged files");
37
+ }
38
+ }
39
+ function areAllPluginsInstalled() {
40
+ return checkIfPluginsAreInstalled().uninstalledPlugins.length === 0;
41
+ }
42
+ function isOnlyWarnings(errors) {
43
+ return !errors.some(line => /\b(error|✖)\b/.test(line));
44
+ }
45
+ function extractDiffHunks(diffText) {
46
+ return diffText.split("\n").filter(line => line.startsWith("@@") || line.startsWith("+") || line.startsWith("-"))
47
+ // skip file headers like "+++ b/" or "--- a/"
48
+ .filter(line => !line.startsWith("+++ ") && !line.startsWith("--- ")).join("\n");
49
+ }
50
+ module.exports = {
51
+ isMergeCommit,
52
+ isOnlyWarnings,
53
+ areAllPluginsInstalled,
54
+ getStagedFiles,
55
+ extractDiffHunks
56
+ };
@@ -18,6 +18,9 @@ const {
18
18
  installPlugins
19
19
  } = require("../utils/PluginsInstallation/installPlugins");
20
20
  const path = require("path");
21
+ const {
22
+ Logger
23
+ } = require("../utils/Logger/Logger");
21
24
  async function hooks() {
22
25
  var jsonFilePath = path.join(__dirname, '..', '..', 'jsonUtils', 'fsUtils.json');
23
26
  if (!(getLastCommitHash() == getStoredCommitHash())) {
@@ -25,12 +28,13 @@ async function hooks() {
25
28
  data.commitHash = getLastCommitHash();
26
29
  return data;
27
30
  });
31
+ Logger.log(Logger.INFO_TYPE, `Some rules and plugins are being fetched from a remote source and installed...`);
28
32
  await executeMethodsThatReturnBooleanValue("Make sure zgit.csez.zohocorpin.com is accessible", cloneViaCdt, null);
29
33
  const {
30
34
  uninstalledPlugins
31
35
  } = getPluginsToInstall();
32
36
  await executeMethodsThatReturnBooleanValue("Some issue occurred in installing plugins", installPlugins, uninstalledPlugins);
33
37
  }
34
- require('./Precommit/pre-commit');
38
+ require('./Precommit/commit');
35
39
  }
36
40
  hooks();
@@ -46,7 +46,7 @@ function cloneViaCdt() {
46
46
  token
47
47
  } = getConfigurationPrecommit();
48
48
  const currentEnv = getRunningEnv();
49
- Logger.log(Logger.INFO_TYPE, `Running in environment: ${currentEnv}`);
49
+ Logger.log(Logger.INFO_TYPE, `Application is running in the following environment:${currentEnv}`);
50
50
 
51
51
  // Clean up existing folder
52
52
  const deleteDir = getDeleteDirPath();
@@ -64,7 +64,7 @@ function getSupportedLanguage() {
64
64
  const {
65
65
  supportedExtensions
66
66
  } = getConfigurationPrecommit();
67
- const _language = supportedExtensions;
67
+ const _language = supportedExtensions || [];
68
68
  _language.push('.js');
69
69
  _language.push('.jsx');
70
70
  _language.push('.ts');
@@ -12,15 +12,9 @@ const {
12
12
  const {
13
13
  Logger
14
14
  } = require('../Logger/Logger');
15
- const {
16
- createVersionControlFile
17
- } = require('../FileAndFolderOperations/versionControl');
18
15
  const {
19
16
  getNodeModulesPath
20
17
  } = require('../General/getNodeModulesPath');
21
- const {
22
- spawn
23
- } = require('child_process');
24
18
 
25
19
  /**
26
20
  * @function installPlugins - installs uninstalled plugins for the project
@@ -39,13 +33,14 @@ function installPlugins(pluginsToBeInstalled) {
39
33
  if (arePluginsInstalledSuccessfully) {
40
34
  Logger.log(Logger.SUCCESS_TYPE, 'Plugins installation successful');
41
35
  let isPackageJsonRestored = restorePackageJsonContent(packageJsonBeforePluginsInstallation);
42
- if (isPackageJsonRestored) {
43
- createVersionControlFile(pluginsToBeInstalled);
44
- return true;
45
- } else {
46
- Logger.log(Logger.FAILURE_TYPE, 'Unable to restore package.json content');
47
- return false;
48
- }
36
+ // if(isPackageJsonRestored){
37
+ // createVersionControlFile(pluginsToBeInstalled)
38
+ // return true
39
+ // }
40
+ // else{
41
+ // Logger.log(Logger.FAILURE_TYPE,'Unable to restore package.json content')
42
+ // return false
43
+ // }
49
44
  } else {
50
45
  Logger.log(Logger.FAILURE_TYPE, "Unable to install plugins. Kindly retry the command");
51
46
  return false;
package/changeLog.md CHANGED
@@ -32,7 +32,7 @@
32
32
  2. Support for .properties file is also extended in this version along with existing support for file types .js, .jsx, .ts, .tsx
33
33
 
34
34
 
35
- # - Support For Stylelint
35
+ # 1.0.0 - Support For Stylelint
36
36
 
37
37
  1. Enhancement Parser support CSS files and linter
38
- 2. Clonet Configuration Flow Enhancement Validation
38
+ 2. Clone Configuration Flow Enhancement Validation
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zohodesk/codestandard-validator",
3
- "version": "0.0.7-exp-13",
3
+ "version": "1.0.0-exp-1",
4
4
  "description": "library to enforce code standard using eslint",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -15,6 +15,7 @@
15
15
  },
16
16
  "type": "commonjs",
17
17
  "dependencies": {
18
+ "@zohodesk/codestandard-analytics":"1.0.2-exp-1",
18
19
  "@zohodesk-private/client_deployment_tool": "0.0.5",
19
20
  "eslint": "8.26.0",
20
21
  "stylelint":"16.23.0"