@zohodesk/codestandard-validator 1.1.4 → 1.2.4-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,193 @@
1
+ "use strict";
2
+
3
+ var _process;
4
+ const {
5
+ execSync
6
+ } = require('child_process');
7
+ const {
8
+ getModifiedLines
9
+ } = require('@zohodesk/codestandard-analytics');
10
+ const {
11
+ getBranchName
12
+ } = require('../utils/GitActions/gitActions');
13
+ const Logger = console;
14
+ const path = require('path');
15
+ const gitEndPoint = 'https://zgit.csez.zohocorpin.com';
16
+ const compareBranch = ((_process = process) === null || _process === void 0 || (_process = _process.env) === null || _process === void 0 ? void 0 : _process.CHUNK_BRANCH) || 'release';
17
+ const configPath = path.resolve(process.cwd(), 'lint.config.js');
18
+ function getGitProjectId() {
19
+ try {
20
+ const config = require(configPath);
21
+ return config.projectId;
22
+ } catch (err) {
23
+ Logger.log(`Failed to Fetch Chunk Details`);
24
+ process.exit(1);
25
+ }
26
+ }
27
+ const projectId = getGitProjectId();
28
+ const token = process.env.ZGIT_TOKEN;
29
+ const shouldEnable = parserBoolean(process.env.SHOULD_ENABLE_CHUNK);
30
+ function isTestOrUATFile(file) {
31
+ const f = file.replace(/\\/g, "/");
32
+ if (f.endsWith(".spec.js") || f.endsWith(".test.js") || f.endsWith(".spec.ts") || f.endsWith(".test.ts") || f.endsWith(".feature") || f.endsWith(".properties")) {
33
+ return true;
34
+ }
35
+
36
+ // UAT folder check
37
+ if (f.includes("/uat/")) {
38
+ return true;
39
+ }
40
+ return false;
41
+ }
42
+ function parserBoolean(value) {
43
+ let defaultValue = false;
44
+ if (value == null || value == undefined) {
45
+ return defaultValue;
46
+ }
47
+ let AcceptedCase = new Set(["true", true]);
48
+ return AcceptedCase.has(value);
49
+ }
50
+ function requestUtilsCLI(command) {
51
+ return execSync(command, {
52
+ shell: true
53
+ });
54
+ }
55
+ function createBranchDiffChunk(branchName) {
56
+ var command;
57
+ const endPoint = `${gitEndPoint}/api/v4/projects/${projectId.toString()}/repository/compare?from=${compareBranch}&to=${branchName}`;
58
+ try {
59
+ command = `curl --header "PRIVATE-TOKEN:${token}" "${endPoint}"`;
60
+ return parserReleaseDiffRemoteAPI(JSON.parse(requestUtilsCLI(command).toString('utf-8')));
61
+ } catch (error) {
62
+ Logger.log(error);
63
+ Logger.log(`\n INFO : If you are using a VPN and encounter an SSL certification issue, ensure that the proxy is enabled for SSH and shell connections.`);
64
+ Logger.log(`\n Make sure that you have access to this repository`);
65
+ }
66
+ }
67
+ function parserReleaseDiffRemoteAPI(rawresponse) {
68
+ var formatted = [];
69
+ if (rawresponse !== null && rawresponse !== void 0 && rawresponse.diffs) {
70
+ formatted = rawresponse.diffs.map(changeset => {
71
+ if (isTestOrUATFile(changeset.new_path)) {
72
+ return null;
73
+ }
74
+ const {
75
+ modifiedLines,
76
+ removedLines
77
+ } = getModifiedLines(changeset.diff);
78
+ chunkSize.$modifieldLines += modifiedLines.length;
79
+ chunkSize.$removedLines += removedLines.length;
80
+ return {
81
+ file: changeset.new_path,
82
+ diff: {
83
+ modifiedLines,
84
+ removedLines
85
+ }
86
+ };
87
+ }).filter(item => item !== null);
88
+ }
89
+ return formatted;
90
+ }
91
+ function parseCombinedDiff(combinedDiffString) {
92
+ if (!combinedDiffString) {
93
+ return [];
94
+ }
95
+ const fileDiffChunks = combinedDiffString.split(/(?=diff --git a\/)/g);
96
+ const structuredDiffs = fileDiffChunks.map(chunk => {
97
+ const fileHeaderMatch = chunk.match(/^diff --git a\/(.*?) b\/(.*?)\n/);
98
+ if (!fileHeaderMatch) {
99
+ return null;
100
+ }
101
+ const filePath = fileHeaderMatch[1];
102
+ if (isTestOrUATFile(filePath)) {
103
+ return null;
104
+ }
105
+ const {
106
+ modifiedLines,
107
+ removedLines
108
+ } = getModifiedLines(chunk.trim());
109
+ chunkSize.$modifieldLines += modifiedLines.length;
110
+ chunkSize.$removedLines += removedLines.length;
111
+ return {
112
+ file: filePath,
113
+ diff: {
114
+ modifiedLines,
115
+ removedLines
116
+ }
117
+ };
118
+ }).filter(item => item !== null);
119
+ return structuredDiffs;
120
+ }
121
+ function runGitCommand(command) {
122
+ try {
123
+ const output = execSync(command, {
124
+ cwd: process.cwd(),
125
+ encoding: 'utf8',
126
+ stdio: ['pipe', 'pipe', 'ignore'],
127
+ maxBuffer: 10 * 1024 * 1024
128
+ }).trim();
129
+ return parseCombinedDiff(output);
130
+ } catch (error) {
131
+ if (error.status === 128) {
132
+ return `ERROR: Git error executing command: '${command}'. Ensure you are in a Git repository and all references exist.`;
133
+ }
134
+ return undefined;
135
+ }
136
+ }
137
+ function getGitChangesets(currentBranch, releaseBranch, upstreamRemote = 'origin') {
138
+ const stagedDiffCommand = 'git diff --staged';
139
+ const stagedChangeset = {
140
+ git_command: stagedDiffCommand,
141
+ description: 'Changes staged in the index, ready to be committed.',
142
+ actual_output: runGitCommand(stagedDiffCommand)
143
+ };
144
+ const releaseComparison = {
145
+ git_command: "giff diff with release",
146
+ description: `Total difference between the tip of branch '${currentBranch}' and the tip of reference '${releaseBranch}'.`,
147
+ actual_output: createBranchDiffChunk(currentBranch)
148
+ };
149
+ const unpushedDiffCommand = `git diff ${upstreamRemote}/${currentBranch}...HEAD`;
150
+ const unpushedChangeset = {
151
+ git_command: unpushedDiffCommand,
152
+ description: `Changes from all local commits that have not been pushed (diff since common ancestor of HEAD and its upstream).`,
153
+ actual_output: runGitCommand(unpushedDiffCommand)
154
+ };
155
+ return {
156
+ stagedChangeset,
157
+ releaseComparison,
158
+ unpushedChangeset
159
+ };
160
+ }
161
+ if (shouldEnable) {
162
+ const myCurrentBranch = getBranchName();
163
+ const targetRelease = process.env.CHUNK_BRANCH || 'release';
164
+ const chunk_size_env = Number(process.env.CHUNK_SIZE) || 800;
165
+ const remoteName = 'origin';
166
+ const Logger = console;
167
+ const RED = '\x1b[31m';
168
+ const GREEN = '\x1b[32m';
169
+ const RESET = '\x1b[0m';
170
+ (async function () {
171
+ Logger.log(`******************************** Experimental Phase Calculation Chunk Size ********************************`);
172
+ if (!(globalThis !== null && globalThis !== void 0 && globalThis.chunkSize)) {
173
+ globalThis.chunkSize = {
174
+ $modifieldLines: 0,
175
+ $removedLines: 0
176
+ };
177
+ try {
178
+ await getGitChangesets(myCurrentBranch, targetRelease, remoteName);
179
+ if (chunkSize.$modifieldLines <= chunk_size_env) {
180
+ Logger.log(`${GREEN}Your Chunk was ${chunkSize.$modifieldLines} and remaining size ${chunk_size_env - chunkSize.$modifieldLines}${RESET}`);
181
+ } else {
182
+ Logger.log(`${RED}Your Chunk was ${chunkSize.$modifieldLines} which exceeded the allowed limit ${chunk_size_env} ${RESET}`);
183
+ // process.exit(1)
184
+ }
185
+ } catch (e) {
186
+ console.log(e);
187
+ Logger.error("Execution failed. Ensure you are running this in a Node.js environment with the 'child_process' module and 'git' installed.");
188
+ Logger.error(e.message);
189
+ }
190
+ Logger.log(`*************************************************************************************`);
191
+ }
192
+ })();
193
+ }
@@ -243,7 +243,7 @@ async function preCommitHook_default() {
243
243
 
244
244
  // CssFiles not Enabled For while
245
245
  areFilesStaged = true;
246
- var stagedFiles = [...staged_filesJS];
246
+ var stagedFiles = [...staged_filesJS, ...CssFiles];
247
247
  for (let file in stagedFiles) {
248
248
  let currentFileName = stagedFiles[file];
249
249
  let changedLinesArray = [];
@@ -24,11 +24,12 @@ const {
24
24
  const {
25
25
  ensurePluginsInstalled
26
26
  } = require('./Precommit/guard');
27
- const config = require(path.join(process.cwd(), 'lint.config.js'));
28
- process.env.SONARQUBE_EXTERNAL = config.metric_token;
29
- process.env.SONARQUBE = config.meticHandler_api_token;
30
- process.env.ZGIT_TOKEN = config.token;
31
- process.env.TOOL_TOKEN = config.toolToken;
27
+ const {
28
+ initConfig,
29
+ getConfigPathExecute
30
+ } = require('../utils/General/Config');
31
+ require("../chunk/chunk_Restriction");
32
+ initConfig(getConfigPathExecute());
32
33
  async function hooks() {
33
34
  var jsonFilePath = path.join(__dirname, '..', '..', 'jsonUtils', 'fsUtils.json');
34
35
  let latestCommit = getLastCommitHash();
@@ -15,27 +15,23 @@ const {
15
15
  const {
16
16
  executeMethodsThatReturnBooleanValue
17
17
  } = require('../utils/General/wrapperFunctionToExecuteAFunction');
18
- const {
19
- arePluginsInstalled
20
- } = require('../utils/PluginsInstallation/arePluginsInstalled');
21
18
  const {
22
19
  isGitInitialized
23
20
  } = require('../utils/GitActions/gitActions');
24
21
  const {
25
22
  writeFsPaths
26
23
  } = require('../utils/General/writeProjectDetailsToJson');
27
- const path = require('path');
24
+ const {
25
+ initConfig,
26
+ getConfigPathPostInstall
27
+ } = require('../utils/General/Config');
28
+
28
29
  /**
29
30
  * @function {postInstall} - This methods setup husky and configuration for executing project
30
31
  * @returns {void}
31
32
  */
32
33
  async function postInstall() {
33
- var actualNodeMoulesPath = path.resolve(process.cwd(), '..', '..', '..');
34
- const config = require(path.join(actualNodeMoulesPath, 'lint.config.js'));
35
- process.env.SONARQUBE_EXTERNAL = config.metric_token;
36
- process.env.SONARQUBE = config.meticHandler_api_token;
37
- process.env.ZGIT_TOKEN = config.token;
38
- process.env.TOOL_TOKEN = config.toolToken;
34
+ initConfig(getConfigPathPostInstall());
39
35
  try {
40
36
  await executeMethodsThatReturnBooleanValue('Some issue in writing node_modules path to json', writeFsPaths, null);
41
37
  isGitInitialized() ? await executeMethodsThatReturnBooleanValue('Some issue occurred in setting up husky.', setupHusky, null) : null;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+
3
+ const path = require('path');
4
+ function initConfig(actualConfigPath) {
5
+ const config = require(path.join(actualConfigPath, 'lint.config.js'));
6
+ process.env.SONARQUBE_EXTERNAL = config.metric_token;
7
+ process.env.SONARQUBE = config.meticHandler_api_token;
8
+ process.env.ZGIT_TOKEN = config.token;
9
+ process.env.TOOL_TOKEN = config.toolToken;
10
+ }
11
+ function getConfigPathPostInstall() {
12
+ return path.resolve(process.cwd(), '..', '..', '..');
13
+ }
14
+ function getConfigPathExecute() {
15
+ return path.resolve(process.cwd());
16
+ }
17
+ module.exports = {
18
+ initConfig,
19
+ getConfigPathExecute,
20
+ getConfigPathPostInstall
21
+ };
@@ -78,7 +78,7 @@ async function fetchProjectIssuesViaCurl(componentKey) {
78
78
  _Logger.Logger.log(_Logger.Logger.INFO_TYPE, `\n Fetching issues (curl) for component: ${componentKey}`);
79
79
  const url = buildIssuesSearchUrl(componentKey);
80
80
  try {
81
- const token = process.env.SONARQUBE; //'sqa_1f6675c05f63c4784dc741ce751efa0066d2693c' || decrypt(getAPIToken(), ); // sonarqube
81
+ const token = process.env.SONARQUBE;
82
82
  const command = `curl --tlsv1.2 -s -u "${token}:" "${url}"`;
83
83
  const output = execSync(command).toString();
84
84
  const json = JSON.parse(output.toString());
package/jest.config.js CHANGED
@@ -1,5 +1,5 @@
1
1
  module.exports = {
2
2
  testEnvironment: 'node',
3
3
  clearMocks: true,
4
- setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
4
+ setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
5
5
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zohodesk/codestandard-validator",
3
- "version": "1.1.4",
3
+ "version": "1.2.4-exp-1",
4
4
  "description": "library to enforce code standard using eslint",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -19,6 +19,8 @@
19
19
  "@zohodesk-private/client_deployment_tool": "0.0.5",
20
20
  "@zohodesk/codestandard-analytics": "1.1.4-exp-2",
21
21
  "eslint": "8.26.0",
22
+ "marked": "9.1.6",
23
+ "marked-terminal": "6.2.0",
22
24
  "stylelint": "16.23.0"
23
25
  },
24
26
  "devDependencies": {