js-code-detector 0.0.25 → 0.0.27

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.
@@ -6,3 +6,24 @@ export declare function getGitRepositoryAndBranch(): Promise<{
6
6
  export declare function sameCodeDetect(dirOfCwd?: string): Promise<void>;
7
7
  export declare function gitDiffDetect(): Promise<void>;
8
8
  export declare function getEslintCheckResult(today: string): Promise<void>;
9
+ export declare function gitDiffDetectByUrl(inputUrl: string): Promise<{
10
+ mdContent: string;
11
+ dependenceJson: Record<string, any>;
12
+ partialDependenceJson: Record<string, any>;
13
+ reports: {
14
+ dangerIdentifiers: string[];
15
+ blockReports: {
16
+ diff_txt: string[];
17
+ infos: {
18
+ causeBy: string;
19
+ effectsUpstream: string[];
20
+ occupations: string[];
21
+ effectsDownstream: string[];
22
+ }[];
23
+ }[];
24
+ type: "modify" | "add" | "delete";
25
+ filesDependsOnMe: string[];
26
+ undefinedIdentifiers: string[];
27
+ filePath: string;
28
+ }[];
29
+ } | undefined>;
package/dist/cjs/index.js CHANGED
@@ -32,6 +32,7 @@ __export(src_exports, {
32
32
  getEslintCheckResult: () => getEslintCheckResult,
33
33
  getGitRepositoryAndBranch: () => getGitRepositoryAndBranch,
34
34
  gitDiffDetect: () => gitDiffDetect,
35
+ gitDiffDetectByUrl: () => gitDiffDetectByUrl,
35
36
  gitDiffFileName: () => gitDiffFileName,
36
37
  sameCodeDetect: () => sameCodeDetect
37
38
  });
@@ -46,6 +47,9 @@ var import_Core = __toESM(require("./util/ast_util/Core"));
46
47
  var import_constants = require("./util/constants");
47
48
  var import_await_to_js = __toESM(require("await-to-js"));
48
49
  var import_generateGitDiffReport = require("./util/report_util/generateGitDiffReport");
50
+ var import_parseGitLabDiffUril = require("./util/parseGitLabDiffUril");
51
+ var import_getRepoSupportFlag = require("./util/shared/getRepoSupportFlag");
52
+ var import_handleExecaError = require("./util/shared/handleExecaError");
49
53
  var gitDiffFileName = "git_diff.txt";
50
54
  var eslintJsonName = "eslint-report.json";
51
55
  var eslintFinalJsonName = "eslint-final-report.json";
@@ -81,6 +85,14 @@ async function gitDiffDetect() {
81
85
  import_utils.logger.ready(`准备clone源代码到临时目录下的 ${import_constants.TARGET} 文件夹`);
82
86
  await import_utils.execa.execa(`git clone ${gitUrl} ${today}/${import_constants.TARGET}`, { shell: "/bin/bash" });
83
87
  import_utils.logger.info("源代码clone完成");
88
+ const supportFlag = (0, import_getRepoSupportFlag.getRepoSupportFlag)((0, import_path.join)(process.cwd(), today, import_constants.TARGET, "package.json"));
89
+ if (!supportFlag) {
90
+ import_utils.logger.error("该项目不支持检测");
91
+ (0, import_utils.rimraf)((0, import_path.join)(process.cwd(), today), () => {
92
+ import_utils.logger.info("临时目录已删除");
93
+ });
94
+ return;
95
+ }
84
96
  import_utils.logger.ready(`准备clone源代码到临时目录下的 ${import_constants.SOURCE} 文件夹`);
85
97
  await import_utils.execa.execa(`git clone ${gitUrl} ${today}/${import_constants.SOURCE}`, { shell: "/bin/bash" });
86
98
  import_utils.logger.info("源代码clone完成");
@@ -122,11 +134,70 @@ async function getEslintCheckResult(today) {
122
134
  (0, import_fs2.writeFileSync)((0, import_path.join)(process.cwd(), eslintFinalJsonName), JSON.stringify(validEslintJson, null, 2), { encoding: "utf-8", flag: "w" });
123
135
  import_utils.logger.info(`${eslintFinalJsonName} 文件生成`);
124
136
  }
137
+ async function gitDiffDetectByUrl(inputUrl) {
138
+ const today = (0, import_dayjs.default)().format("YYYYMDD_HHmmss") + Math.random().toString(36).slice(-5);
139
+ const { gitRepoUrl: gitUrl, targetBranch: branchName, baseBranch, projectPathPart } = (0, import_parseGitLabDiffUril.parseGitLabCompareUrl)(inputUrl);
140
+ import_utils.logger.ready("准备生成临时工作目录...");
141
+ const [err] = await (0, import_await_to_js.default)(import_utils.execa.execa(`rm -rf ${today}`, { shell: "/bin/bash" }));
142
+ if (err) {
143
+ import_utils.logger.error("临时目录删除失败");
144
+ }
145
+ await import_utils.execa.execa(`mkdir -p ${today}`, { shell: "/bin/bash" });
146
+ import_utils.logger.info("临时目录建立完成");
147
+ try {
148
+ import_utils.logger.ready(`准备clone ${projectPathPart} 源代码到临时目录下的 ${import_constants.TARGET} 文件夹`);
149
+ let stderr, failed;
150
+ ({ stderr, failed } = await import_utils.execa.execa(`git clone ${gitUrl} ${today}/${import_constants.TARGET}`, { shell: "/bin/bash" }));
151
+ (0, import_handleExecaError.handleExecaError)({ failed, stderr });
152
+ import_utils.logger.info("源代码clone完成");
153
+ const supportFlag = (0, import_getRepoSupportFlag.getRepoSupportFlag)((0, import_path.join)(process.cwd(), today, import_constants.TARGET, "package.json"));
154
+ if (!supportFlag) {
155
+ import_utils.logger.error("该项目不支持检测");
156
+ (0, import_utils.rimraf)((0, import_path.join)(process.cwd(), today), () => {
157
+ import_utils.logger.info("临时目录已删除");
158
+ });
159
+ return;
160
+ }
161
+ import_utils.logger.ready(`准备clone ${projectPathPart} 源代码到临时目录下的 ${import_constants.SOURCE} 文件夹`);
162
+ ({ stderr, failed } = await import_utils.execa.execa(`git clone ${gitUrl} ${today}/${import_constants.SOURCE}`, { shell: "/bin/bash" }));
163
+ (0, import_handleExecaError.handleExecaError)({ failed, stderr });
164
+ import_utils.logger.info("源代码clone完成");
165
+ if (baseBranch !== "master") {
166
+ import_utils.logger.ready("准备切换到基准分支");
167
+ ({ stderr, failed } = await import_utils.execa.execa(`cd ${today}/${import_constants.SOURCE} && git fetch origin ${baseBranch}:${baseBranch} && git checkout ${baseBranch}`, { shell: "/bin/bash" }));
168
+ (0, import_handleExecaError.handleExecaError)({ failed, stderr });
169
+ import_utils.logger.info("源代码切换到基准分支完成");
170
+ }
171
+ import_utils.logger.ready("准备切换到目标分支");
172
+ ({ stderr, failed } = await import_utils.execa.execa(`cd ${today}/${import_constants.TARGET} && git fetch origin ${branchName}:${branchName} && git checkout ${branchName}`, { shell: "/bin/bash" }));
173
+ (0, import_handleExecaError.handleExecaError)({ failed, stderr });
174
+ import_utils.logger.info("分支切换完成");
175
+ import_utils.logger.ready("准备生成git_diff.txt文件");
176
+ ({ stderr, failed } = await import_utils.execa.execa(`cd ${today}/${import_constants.TARGET} && git diff ${baseBranch}..${branchName} --unified=0 --output=${gitDiffFileName}`, { shell: "/bin/bash" }));
177
+ (0, import_handleExecaError.handleExecaError)({ failed, stderr });
178
+ import_utils.logger.info("git_diff.txt文件生成完成");
179
+ import_utils.logger.wait("准备生成 入口文件");
180
+ ({ stderr, failed } = await import_utils.execa.execa(`cd ${today}/${import_constants.TARGET} && npx max setup`, { shell: "/bin/bash" }));
181
+ (0, import_handleExecaError.handleExecaError)({ failed, stderr });
182
+ import_utils.logger.info("入口文件 生成完成!");
183
+ import_utils.logger.ready("准备生成报告");
184
+ const res = await (0, import_generateGitDiffReport.generateGitDiffReport)({ targetDirPath: (0, import_path.join)(process.cwd(), today, import_constants.TARGET), generateFile: [] });
185
+ import_utils.logger.info("报告完成");
186
+ return res;
187
+ } catch (error) {
188
+ import_utils.logger.error(error.message);
189
+ } finally {
190
+ (0, import_utils.rimraf)((0, import_path.join)(process.cwd(), today), () => {
191
+ import_utils.logger.info("临时目录已删除");
192
+ });
193
+ }
194
+ }
125
195
  // Annotate the CommonJS export names for ESM import in node:
126
196
  0 && (module.exports = {
127
197
  getEslintCheckResult,
128
198
  getGitRepositoryAndBranch,
129
199
  gitDiffDetect,
200
+ gitDiffDetectByUrl,
130
201
  gitDiffFileName,
131
202
  sameCodeDetect
132
203
  });
@@ -4,7 +4,8 @@
4
4
  * @returns 包含项目Git地址和两个解码后分支名的对象
5
5
  * @throws 当输入链接格式不符合要求时抛出错误
6
6
  */
7
- declare function parseGitLabCompareUrl(compareUrl: string): {
7
+ export declare function parseGitLabCompareUrl(compareUrl: string): {
8
+ projectPathPart: string;
8
9
  gitRepoUrl: string;
9
10
  baseBranch: string;
10
11
  targetBranch: string;
@@ -0,0 +1,63 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/util/parseGitLabDiffUril.ts
20
+ var parseGitLabDiffUril_exports = {};
21
+ __export(parseGitLabDiffUril_exports, {
22
+ parseGitLabCompareUrl: () => parseGitLabCompareUrl
23
+ });
24
+ module.exports = __toCommonJS(parseGitLabDiffUril_exports);
25
+ function parseGitLabCompareUrl(compareUrl) {
26
+ let urlObj;
27
+ try {
28
+ urlObj = new URL(compareUrl);
29
+ } catch (error) {
30
+ throw new Error(`输入不是有效URL:${compareUrl},请检查链接格式`);
31
+ }
32
+ const comparePathMarker = "/-/compare/";
33
+ if (!urlObj.pathname.includes(comparePathMarker)) {
34
+ throw new Error(
35
+ `不是GitLab分支对比链接,链接需包含 "${comparePathMarker}" 路径,当前链接:${compareUrl}`
36
+ );
37
+ }
38
+ const [projectPathPart, branchComparePart] = urlObj.pathname.split(comparePathMarker);
39
+ if (!projectPathPart || !branchComparePart) {
40
+ throw new Error(
41
+ `分支对比链接格式异常,无法拆分项目路径与分支信息,当前链接:${compareUrl}`
42
+ );
43
+ }
44
+ const [encodedBaseBranch, encodedTargetBranch] = branchComparePart.split("...");
45
+ if (!encodedBaseBranch || !encodedTargetBranch) {
46
+ throw new Error(
47
+ `分支对比格式错误,需符合 "分支1...分支2" 格式,当前分支部分:${branchComparePart}`
48
+ );
49
+ }
50
+ const baseBranch = decodeURIComponent(encodedBaseBranch);
51
+ const targetBranch = decodeURIComponent(encodedTargetBranch);
52
+ const gitRepoUrl = `${urlObj.origin}${projectPathPart}.git`;
53
+ return {
54
+ projectPathPart,
55
+ gitRepoUrl,
56
+ baseBranch,
57
+ targetBranch
58
+ };
59
+ }
60
+ // Annotate the CommonJS export names for ESM import in node:
61
+ 0 && (module.exports = {
62
+ parseGitLabCompareUrl
63
+ });
@@ -83,8 +83,8 @@ function diffBlockDetect(gitDiffDetail, index, extra) {
83
83
  }
84
84
  function reportItemDetect(reportItem, absPathPrefix) {
85
85
  const { _fileRemovedNodesPaths, _fileAddedNodesPaths, filePath } = reportItem;
86
- const filePathOfOld = (0, import_path.join)(process.cwd(), "..", import_constants.SOURCE, filePath);
87
- const { mapPathToNodeSet } = (0, import_getAstKitByFilePath.default)(filePath, absPathPrefix);
86
+ const filePathOfNew = (0, import_path.join)(absPathPrefix, filePath);
87
+ const { mapPathToNodeSet } = (0, import_getAstKitByFilePath.default)(filePathOfNew, absPathPrefix);
88
88
  const _fileAddedPaths = _fileAddedNodesPaths.map((e) => e.nodePath);
89
89
  const _fileRemovedPaths = _fileRemovedNodesPaths.map((e) => e.nodePath);
90
90
  const _fileSamePathsNode = _fileAddedPaths.filter((e) => _fileRemovedPaths.includes(e));
@@ -1,3 +1,26 @@
1
+ declare const reportFileName = "git_diff_report.md";
1
2
  export declare function generateGitDiffReport(arg: {
2
3
  targetDirPath: string;
3
- }): Promise<void>;
4
+ generateFile?: ('dependence_map.json' | 'partial_dependence_map.json' | 'report.json' | typeof reportFileName)[];
5
+ }): Promise<{
6
+ mdContent: string;
7
+ dependenceJson: Record<string, any>;
8
+ partialDependenceJson: Record<string, any>;
9
+ reports: {
10
+ dangerIdentifiers: string[];
11
+ blockReports: {
12
+ diff_txt: string[];
13
+ infos: {
14
+ causeBy: string;
15
+ effectsUpstream: string[];
16
+ occupations: string[];
17
+ effectsDownstream: string[];
18
+ }[];
19
+ }[];
20
+ type: "modify" | "add" | "delete";
21
+ filesDependsOnMe: string[];
22
+ undefinedIdentifiers: string[];
23
+ filePath: string;
24
+ }[];
25
+ }>;
26
+ export {};
@@ -53,7 +53,7 @@ var userAliasGetter = (cwd, appData) => {
53
53
  };
54
54
  var reportFileName = "git_diff_report.md";
55
55
  async function generateGitDiffReport(arg) {
56
- const { targetDirPath } = arg;
56
+ const { targetDirPath, generateFile = ["dependence_map.json", "partial_dependence_map.json", "report.json", reportFileName] } = arg;
57
57
  const absSrcPath = (0, import_path.join)(targetDirPath, "src");
58
58
  const diff_txt = (0, import_fs.readFileSync)((0, import_path.join)(targetDirPath, import__.gitDiffFileName), "utf-8");
59
59
  const gitDiffDetail = (0, import_format_git_diff_content.formatGitDiffContent)(diff_txt);
@@ -102,19 +102,26 @@ async function generateGitDiffReport(arg) {
102
102
  const groupGitDiffLines = gitDiffDetail.filter((item) => usingFileNoPrefix.includes(item.filePath));
103
103
  const changedFilePaths = groupGitDiffLines.map((item) => item.filePath);
104
104
  const time = (0, import_dayjs.default)().format("YYYYMDD_HHmm");
105
+ let dependenceJson = {};
106
+ let partialDependenceJson = {};
105
107
  try {
106
- const dependenceJson = (0, import_createDependenceMap.createDependenceMap)(usingFilePaths, parsedAlias, absPathPrefix);
107
- (0, import_fs.writeFileSync)((0, import_path.join)(targetDirPath, "..", "..", `${time}_dependence_map.json`), JSON.stringify(dependenceJson, null, 2), { encoding: "utf-8", flag: "w" });
108
- const partialDependenceJson = Object.fromEntries(changedFilePaths.map((p) => [p, dependenceJson[p]]));
109
- (0, import_fs.writeFileSync)((0, import_path.join)(targetDirPath, "..", "..", `${time}_partial_dependence_map.json`), JSON.stringify(partialDependenceJson, null, 2), { encoding: "utf-8", flag: "w" });
108
+ dependenceJson = (0, import_createDependenceMap.createDependenceMap)(usingFilePaths, parsedAlias, absPathPrefix);
109
+ partialDependenceJson = Object.fromEntries(changedFilePaths.map((p) => [p, dependenceJson[p]]));
110
110
  } catch (e) {
111
111
  console.warn("dependenceJson 生成失败", e);
112
112
  }
113
- (0, import_fs.writeFileSync)((0, import_path.join)(targetDirPath, "..", "..", `${time}_reports_helper.json`), JSON.stringify({ usingFilePaths, groupGitDiffLines, absPathPrefix, tree, filteredAlias, parsedAlias, tsconfig }, null, 2), { encoding: "utf-8", flag: "w" });
114
113
  const reports = (0, import_report_util.createDetectReport)({ groupGitDiffLines, tree, absPathPrefix });
115
- (0, import_fs.writeFileSync)((0, import_path.join)(targetDirPath, "..", "..", `${time}_reports.json`), JSON.stringify(reports, null, 2), { encoding: "utf-8", flag: "w" });
116
114
  const mdContent = (0, import_createMdByJson.createMdByJson)(reports);
117
- (0, import_fs.writeFileSync)((0, import_path.join)(targetDirPath, "..", "..", `${time}_${reportFileName}`), mdContent, { encoding: "utf-8", flag: "w" });
115
+ generateFile.includes("dependence_map.json") && (0, import_fs.writeFileSync)((0, import_path.join)(targetDirPath, "..", "..", `${time}_dependence_map.json`), JSON.stringify(dependenceJson, null, 2), { encoding: "utf-8", flag: "w" });
116
+ generateFile.includes("partial_dependence_map.json") && (0, import_fs.writeFileSync)((0, import_path.join)(targetDirPath, "..", "..", `${time}_partial_dependence_map.json`), JSON.stringify(partialDependenceJson, null, 2), { encoding: "utf-8", flag: "w" });
117
+ generateFile.includes("report.json") && (0, import_fs.writeFileSync)((0, import_path.join)(targetDirPath, "..", "..", `${time}_report.json`), JSON.stringify(reports, null, 2), { encoding: "utf-8", flag: "w" });
118
+ generateFile.includes(reportFileName) && (0, import_fs.writeFileSync)((0, import_path.join)(targetDirPath, "..", "..", `${time}_${reportFileName}`), mdContent, { encoding: "utf-8", flag: "w" });
119
+ return {
120
+ mdContent,
121
+ dependenceJson,
122
+ partialDependenceJson,
123
+ reports
124
+ };
118
125
  }
119
126
  // Annotate the CommonJS export names for ESM import in node:
120
127
  0 && (module.exports = {
@@ -0,0 +1 @@
1
+ export declare function getRepoSupportFlag(jsonPath: string): boolean;
@@ -0,0 +1,45 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/util/shared/getRepoSupportFlag.ts
20
+ var getRepoSupportFlag_exports = {};
21
+ __export(getRepoSupportFlag_exports, {
22
+ getRepoSupportFlag: () => getRepoSupportFlag
23
+ });
24
+ module.exports = __toCommonJS(getRepoSupportFlag_exports);
25
+ var import_fs = require("fs");
26
+ function getRepoSupportFlag(jsonPath) {
27
+ var _a;
28
+ const isExist = (0, import_fs.existsSync)(jsonPath);
29
+ if (!isExist)
30
+ return false;
31
+ const packageJson = (0, import_fs.readFileSync)(jsonPath, "utf-8");
32
+ if (!packageJson)
33
+ return false;
34
+ try {
35
+ const packageJsonObj = JSON.parse(packageJson);
36
+ const supportFlag = !!((_a = packageJsonObj.dependencies) == null ? void 0 : _a["@umijs/max"]);
37
+ return supportFlag;
38
+ } catch (e) {
39
+ return false;
40
+ }
41
+ }
42
+ // Annotate the CommonJS export names for ESM import in node:
43
+ 0 && (module.exports = {
44
+ getRepoSupportFlag
45
+ });
@@ -0,0 +1,4 @@
1
+ export declare function handleExecaError({ failed, stderr }: {
2
+ failed: boolean;
3
+ stderr: string;
4
+ }): void;
@@ -0,0 +1,35 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/util/shared/handleExecaError.ts
20
+ var handleExecaError_exports = {};
21
+ __export(handleExecaError_exports, {
22
+ handleExecaError: () => handleExecaError
23
+ });
24
+ module.exports = __toCommonJS(handleExecaError_exports);
25
+ var import_utils = require("@umijs/utils");
26
+ function handleExecaError({ failed, stderr }) {
27
+ if (failed) {
28
+ import_utils.logger.error(stderr);
29
+ throw new Error(stderr);
30
+ }
31
+ }
32
+ // Annotate the CommonJS export names for ESM import in node:
33
+ 0 && (module.exports = {
34
+ handleExecaError
35
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "js-code-detector",
3
- "version": "0.0.25",
3
+ "version": "0.0.27",
4
4
  "description": "",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",
@@ -35,6 +35,7 @@
35
35
  },
36
36
  "dependencies": {
37
37
  "@babel/parser": "^7.28.3",
38
+ "@umijs/max": "^4.5.3",
38
39
  "@umijs/utils": "^4.4.12",
39
40
  "await-to-js": "^3.0.0",
40
41
  "crypto-js": "^4.2.0",