@getcodesentinel/codesentinel 1.35.0 → 1.37.0
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.
- package/README.md +19 -1
- package/dist/index.js +633 -149
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1944,7 +1944,12 @@ var analyzeDependencyCandidateFromRegistry = async (input) => {
|
|
|
1944
1944
|
|
|
1945
1945
|
// ../reporter/dist/index.js
|
|
1946
1946
|
import { basename as basename2, posix } from "path";
|
|
1947
|
-
var SNAPSHOT_SCHEMA_VERSION = "codesentinel.snapshot.
|
|
1947
|
+
var SNAPSHOT_SCHEMA_VERSION = "codesentinel.snapshot.v2";
|
|
1948
|
+
var LEGACY_SNAPSHOT_SCHEMA_VERSIONS = ["codesentinel.snapshot.v1"];
|
|
1949
|
+
var SUPPORTED_SNAPSHOT_SCHEMA_VERSIONS = [
|
|
1950
|
+
SNAPSHOT_SCHEMA_VERSION,
|
|
1951
|
+
...LEGACY_SNAPSHOT_SCHEMA_VERSIONS
|
|
1952
|
+
];
|
|
1948
1953
|
var REPORT_SCHEMA_VERSION = "codesentinel.report.v1";
|
|
1949
1954
|
var RISK_MODEL_VERSION = "deterministic-v1";
|
|
1950
1955
|
var round43 = (value) => Number(value.toFixed(4));
|
|
@@ -3071,15 +3076,19 @@ var createSnapshot = (input) => ({
|
|
|
3071
3076
|
generatedAt: input.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
3072
3077
|
riskModelVersion: RISK_MODEL_VERSION,
|
|
3073
3078
|
source: {
|
|
3074
|
-
targetPath: input.analysis.structural.targetPath
|
|
3079
|
+
targetPath: input.analysis.structural.targetPath,
|
|
3080
|
+
...input.source?.commit === void 0 ? {} : { commit: input.source.commit },
|
|
3081
|
+
...input.source?.ref === void 0 ? {} : { ref: input.source.ref }
|
|
3075
3082
|
},
|
|
3076
3083
|
analysis: input.analysis,
|
|
3077
3084
|
...input.trace === void 0 ? {} : { trace: input.trace },
|
|
3078
|
-
...input.analysisConfig === void 0 ? {} : { analysisConfig: input.analysisConfig }
|
|
3085
|
+
...input.analysisConfig === void 0 ? {} : { analysisConfig: input.analysisConfig },
|
|
3086
|
+
...input.ownership === void 0 ? {} : { ownership: input.ownership }
|
|
3079
3087
|
});
|
|
3088
|
+
var isSupportedSchemaVersion = (value) => typeof value === "string" && SUPPORTED_SNAPSHOT_SCHEMA_VERSIONS.includes(value);
|
|
3080
3089
|
var parseSnapshot = (raw) => {
|
|
3081
3090
|
const parsed = JSON.parse(raw);
|
|
3082
|
-
if (parsed.schemaVersion
|
|
3091
|
+
if (!isSupportedSchemaVersion(parsed.schemaVersion)) {
|
|
3083
3092
|
throw new Error("unsupported_snapshot_schema");
|
|
3084
3093
|
}
|
|
3085
3094
|
if (typeof parsed.generatedAt !== "string") {
|
|
@@ -3091,6 +3100,15 @@ var parseSnapshot = (raw) => {
|
|
|
3091
3100
|
if (parsed.source === void 0 || typeof parsed.source.targetPath !== "string") {
|
|
3092
3101
|
throw new Error("invalid_snapshot_source");
|
|
3093
3102
|
}
|
|
3103
|
+
if (parsed.source.commit !== void 0 && (typeof parsed.source.commit !== "string" || parsed.source.commit.length === 0)) {
|
|
3104
|
+
throw new Error("invalid_snapshot_source_commit");
|
|
3105
|
+
}
|
|
3106
|
+
if (parsed.source.ref !== void 0 && (typeof parsed.source.ref !== "string" || parsed.source.ref.length === 0)) {
|
|
3107
|
+
throw new Error("invalid_snapshot_source_ref");
|
|
3108
|
+
}
|
|
3109
|
+
if (parsed.ownership !== void 0 && (typeof parsed.ownership !== "object" || parsed.ownership === null || Array.isArray(parsed.ownership))) {
|
|
3110
|
+
throw new Error("invalid_snapshot_ownership");
|
|
3111
|
+
}
|
|
3094
3112
|
return parsed;
|
|
3095
3113
|
};
|
|
3096
3114
|
var formatReport = (report, format) => {
|
|
@@ -3838,8 +3856,8 @@ var resolveAutoBaselineRef = async (input) => {
|
|
|
3838
3856
|
|
|
3839
3857
|
// src/index.ts
|
|
3840
3858
|
import { readFileSync as readFileSync4 } from "fs";
|
|
3841
|
-
import { readFile as
|
|
3842
|
-
import { dirname as dirname4, resolve as
|
|
3859
|
+
import { readFile as readFile9, writeFile as writeFile10 } from "fs/promises";
|
|
3860
|
+
import { dirname as dirname4, resolve as resolve11 } from "path";
|
|
3843
3861
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
3844
3862
|
|
|
3845
3863
|
// src/application/format-analyze-output.ts
|
|
@@ -4520,7 +4538,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
|
|
|
4520
4538
|
);
|
|
4521
4539
|
return "skip";
|
|
4522
4540
|
}
|
|
4523
|
-
return await new Promise((
|
|
4541
|
+
return await new Promise((resolve12) => {
|
|
4524
4542
|
emitKeypressEvents(stdin);
|
|
4525
4543
|
let selectedIndex = 0;
|
|
4526
4544
|
const previousRawMode = stdin.isRaw;
|
|
@@ -4545,7 +4563,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
|
|
|
4545
4563
|
} else {
|
|
4546
4564
|
stderr.write("\n");
|
|
4547
4565
|
}
|
|
4548
|
-
|
|
4566
|
+
resolve12(choice);
|
|
4549
4567
|
};
|
|
4550
4568
|
const onKeypress = (_str, key) => {
|
|
4551
4569
|
if (key.ctrl === true && key.name === "c") {
|
|
@@ -4739,7 +4757,7 @@ var promptSelection = async (currentVersion, actions) => {
|
|
|
4739
4757
|
if (!stdin2.isTTY || !stderr2.isTTY || typeof stdin2.setRawMode !== "function") {
|
|
4740
4758
|
return "exit";
|
|
4741
4759
|
}
|
|
4742
|
-
return await new Promise((
|
|
4760
|
+
return await new Promise((resolve12) => {
|
|
4743
4761
|
emitKeypressEvents2(stdin2);
|
|
4744
4762
|
let selectedIndex = 0;
|
|
4745
4763
|
const previousRawMode = stdin2.isRaw;
|
|
@@ -4754,7 +4772,7 @@ var promptSelection = async (currentVersion, actions) => {
|
|
|
4754
4772
|
stdin2.setRawMode(previousRawMode);
|
|
4755
4773
|
clearTerminal();
|
|
4756
4774
|
showCursor2();
|
|
4757
|
-
|
|
4775
|
+
resolve12(selection);
|
|
4758
4776
|
};
|
|
4759
4777
|
const onKeypress = (_str, key) => {
|
|
4760
4778
|
if (key.ctrl === true && key.name === "c") {
|
|
@@ -4847,7 +4865,7 @@ var waitForReturnToMenu = async () => {
|
|
|
4847
4865
|
}
|
|
4848
4866
|
stderr2.write(`
|
|
4849
4867
|
${PROMPT_PADDING}Press enter to return to the menu...`);
|
|
4850
|
-
await new Promise((
|
|
4868
|
+
await new Promise((resolve12) => {
|
|
4851
4869
|
emitKeypressEvents2(stdin2);
|
|
4852
4870
|
const previousRawMode = stdin2.isRaw;
|
|
4853
4871
|
const cleanup = () => {
|
|
@@ -4856,7 +4874,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
|
|
|
4856
4874
|
stdin2.setRawMode(previousRawMode);
|
|
4857
4875
|
showCursor2();
|
|
4858
4876
|
stderr2.write("\n");
|
|
4859
|
-
|
|
4877
|
+
resolve12();
|
|
4860
4878
|
};
|
|
4861
4879
|
const onKeypress = (_str, key) => {
|
|
4862
4880
|
if (key.ctrl === true && key.name === "c") {
|
|
@@ -4874,7 +4892,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
|
|
|
4874
4892
|
});
|
|
4875
4893
|
};
|
|
4876
4894
|
var runCliCommand = async (scriptPath2, args) => {
|
|
4877
|
-
return await new Promise((
|
|
4895
|
+
return await new Promise((resolve12, reject) => {
|
|
4878
4896
|
const child = spawn2(process.execPath, [...process.execArgv, scriptPath2, ...args], {
|
|
4879
4897
|
stdio: ["inherit", "pipe", "pipe"],
|
|
4880
4898
|
env: {
|
|
@@ -4888,7 +4906,7 @@ var runCliCommand = async (scriptPath2, args) => {
|
|
|
4888
4906
|
reject(error);
|
|
4889
4907
|
});
|
|
4890
4908
|
child.on("close", (code) => {
|
|
4891
|
-
|
|
4909
|
+
resolve12(code ?? 1);
|
|
4892
4910
|
});
|
|
4893
4911
|
});
|
|
4894
4912
|
};
|
|
@@ -8967,6 +8985,8 @@ var buildAnalysisSnapshot = async (inputPath, authorIdentityMode, options, logge
|
|
|
8967
8985
|
return createSnapshot({
|
|
8968
8986
|
analysis: summary,
|
|
8969
8987
|
...evaluation.trace === void 0 ? {} : { trace: evaluation.trace },
|
|
8988
|
+
...options.source === void 0 ? {} : { source: options.source },
|
|
8989
|
+
...options.ownership === void 0 ? {} : { ownership: options.ownership },
|
|
8970
8990
|
analysisConfig: {
|
|
8971
8991
|
authorIdentityMode,
|
|
8972
8992
|
includeTrace: options.includeTrace,
|
|
@@ -9053,13 +9073,9 @@ var runCheckCommand = async (inputPath, authorIdentityMode, options, logger = cr
|
|
|
9053
9073
|
};
|
|
9054
9074
|
|
|
9055
9075
|
// src/application/run-ci-command.ts
|
|
9076
|
+
import { existsSync as existsSync5 } from "fs";
|
|
9056
9077
|
import { readFile as readFile5, writeFile as writeFile4 } from "fs/promises";
|
|
9057
|
-
import { relative as relative3, resolve as resolve6 } from "path";
|
|
9058
|
-
|
|
9059
|
-
// src/application/build-ownership-audit.ts
|
|
9060
|
-
import { existsSync as existsSync4 } from "fs";
|
|
9061
|
-
import { readFile as readFile4 } from "fs/promises";
|
|
9062
|
-
import { resolve as resolve5 } from "path";
|
|
9078
|
+
import { join as join9, relative as relative3, resolve as resolve6 } from "path";
|
|
9063
9079
|
|
|
9064
9080
|
// ../ownership/dist/index.js
|
|
9065
9081
|
var CODEOWNERS_MAX_BYTES = 3 * 1024 * 1024;
|
|
@@ -9702,6 +9718,11 @@ var auditOwnership = (input) => {
|
|
|
9702
9718
|
};
|
|
9703
9719
|
};
|
|
9704
9720
|
|
|
9721
|
+
// src/application/build-ownership-audit.ts
|
|
9722
|
+
import { existsSync as existsSync4 } from "fs";
|
|
9723
|
+
import { readFile as readFile4 } from "fs/promises";
|
|
9724
|
+
import { resolve as resolve5 } from "path";
|
|
9725
|
+
|
|
9705
9726
|
// src/application/owners-git.ts
|
|
9706
9727
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
9707
9728
|
var RECORD_SEPARATOR = "";
|
|
@@ -9808,6 +9829,18 @@ var readRepositorySnapshot = (targetPath, ref) => {
|
|
|
9808
9829
|
}
|
|
9809
9830
|
return { repositoryPath, ref, commitUnix, trackedFiles };
|
|
9810
9831
|
};
|
|
9832
|
+
var COMMIT_SHA_PATTERN = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i;
|
|
9833
|
+
var readRepositoryContext = (targetPath, ref = "HEAD") => {
|
|
9834
|
+
try {
|
|
9835
|
+
const repositoryPath = runGit2(targetPath, ["rev-parse", "--show-toplevel"]).trim();
|
|
9836
|
+
if (repositoryPath.length === 0) return null;
|
|
9837
|
+
const commit = runGit2(repositoryPath, ["rev-parse", "--verify", `${ref}^{commit}`]).trim();
|
|
9838
|
+
if (!COMMIT_SHA_PATTERN.test(commit)) return null;
|
|
9839
|
+
return { repositoryPath, commit, ref };
|
|
9840
|
+
} catch {
|
|
9841
|
+
return null;
|
|
9842
|
+
}
|
|
9843
|
+
};
|
|
9811
9844
|
var readTextAtRef = (repositoryPath, ref, filePath) => runGit2(repositoryPath, ["show", `${ref}:${filePath}`]);
|
|
9812
9845
|
var accumulateAuthor = (authors, authorId, authorName) => {
|
|
9813
9846
|
const author = authors.get(authorId) ?? { authorName, commits: 0 };
|
|
@@ -10021,6 +10054,96 @@ var buildOwnershipAudit = async (targetPath, options, logger) => {
|
|
|
10021
10054
|
};
|
|
10022
10055
|
};
|
|
10023
10056
|
|
|
10057
|
+
// src/application/report-ownership.ts
|
|
10058
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
10059
|
+
var stripGitSuffix = (path) => path.replace(/\.git\/?$/i, "").replace(/\/+$/, "");
|
|
10060
|
+
var normalizeRepositoryWebUrl = (raw) => {
|
|
10061
|
+
const value = raw.trim();
|
|
10062
|
+
if (value.length === 0) {
|
|
10063
|
+
return null;
|
|
10064
|
+
}
|
|
10065
|
+
if (!value.includes("://")) {
|
|
10066
|
+
const scpMatch = value.match(/^(?:[^@\s]+@)?([^:/\s]+):(.+)$/);
|
|
10067
|
+
if (scpMatch === null) {
|
|
10068
|
+
return null;
|
|
10069
|
+
}
|
|
10070
|
+
const host = scpMatch[1];
|
|
10071
|
+
const path2 = stripGitSuffix(scpMatch[2] ?? "").replace(/^\/+/, "");
|
|
10072
|
+
if (host === void 0 || path2.length === 0) {
|
|
10073
|
+
return null;
|
|
10074
|
+
}
|
|
10075
|
+
return `https://${host}/${path2}`;
|
|
10076
|
+
}
|
|
10077
|
+
let url;
|
|
10078
|
+
try {
|
|
10079
|
+
url = new URL(value);
|
|
10080
|
+
} catch {
|
|
10081
|
+
return null;
|
|
10082
|
+
}
|
|
10083
|
+
if (url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "ssh:") {
|
|
10084
|
+
return null;
|
|
10085
|
+
}
|
|
10086
|
+
const path = stripGitSuffix(url.pathname).replace(/^\/+/, "");
|
|
10087
|
+
if (url.hostname.length === 0 || path.length === 0) {
|
|
10088
|
+
return null;
|
|
10089
|
+
}
|
|
10090
|
+
return `https://${url.hostname}/${path}`;
|
|
10091
|
+
};
|
|
10092
|
+
var readRepositoryWebUrl = (repositoryPath) => {
|
|
10093
|
+
try {
|
|
10094
|
+
const raw = execFileSync3(
|
|
10095
|
+
"git",
|
|
10096
|
+
["-C", repositoryPath, "config", "--get", "remote.origin.url"],
|
|
10097
|
+
{
|
|
10098
|
+
encoding: "utf8",
|
|
10099
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
10100
|
+
}
|
|
10101
|
+
);
|
|
10102
|
+
return normalizeRepositoryWebUrl(raw);
|
|
10103
|
+
} catch {
|
|
10104
|
+
return null;
|
|
10105
|
+
}
|
|
10106
|
+
};
|
|
10107
|
+
var toOwnershipAuditReport = (audit) => {
|
|
10108
|
+
if (!audit.available) {
|
|
10109
|
+
return {
|
|
10110
|
+
available: false,
|
|
10111
|
+
reason: audit.reason,
|
|
10112
|
+
warnings: audit.warnings
|
|
10113
|
+
};
|
|
10114
|
+
}
|
|
10115
|
+
return {
|
|
10116
|
+
available: true,
|
|
10117
|
+
codeowners: {
|
|
10118
|
+
source: audit.codeowners.source,
|
|
10119
|
+
ignoredSources: audit.codeowners.ignoredSources,
|
|
10120
|
+
errors: audit.codeowners.errors
|
|
10121
|
+
},
|
|
10122
|
+
metrics: audit.metrics,
|
|
10123
|
+
ghostOwners: audit.ghostOwners,
|
|
10124
|
+
files: audit.files,
|
|
10125
|
+
warnings: audit.warnings
|
|
10126
|
+
};
|
|
10127
|
+
};
|
|
10128
|
+
var buildReportOwnership = async (repositoryPath, logger) => {
|
|
10129
|
+
const webUrl = readRepositoryWebUrl(repositoryPath);
|
|
10130
|
+
try {
|
|
10131
|
+
const { audit } = await buildOwnershipAudit(repositoryPath, {}, logger);
|
|
10132
|
+
return { ownership: toOwnershipAuditReport(audit), webUrl };
|
|
10133
|
+
} catch (error) {
|
|
10134
|
+
const message = error instanceof Error ? error.message : "Unknown ownership audit error.";
|
|
10135
|
+
logger.warn(`ownership audit unavailable: ${message}`);
|
|
10136
|
+
return {
|
|
10137
|
+
ownership: {
|
|
10138
|
+
available: false,
|
|
10139
|
+
reason: "audit_unavailable",
|
|
10140
|
+
warnings: [message]
|
|
10141
|
+
},
|
|
10142
|
+
webUrl
|
|
10143
|
+
};
|
|
10144
|
+
}
|
|
10145
|
+
};
|
|
10146
|
+
|
|
10024
10147
|
// src/application/run-ci-command.ts
|
|
10025
10148
|
var isPathOutsideBase = (value) => {
|
|
10026
10149
|
return value === ".." || value.startsWith("../") || value.startsWith("..\\");
|
|
@@ -10035,6 +10158,38 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
|
|
|
10035
10158
|
throw new GovernanceConfigurationError("baseline-sha requires --baseline-ref auto");
|
|
10036
10159
|
}
|
|
10037
10160
|
const resolvedTargetPath = resolve6(inputPath ?? process.cwd());
|
|
10161
|
+
const repositoryContext = readRepositoryContext(resolvedTargetPath);
|
|
10162
|
+
const repositoryPath = repositoryContext?.repositoryPath ?? resolvedTargetPath;
|
|
10163
|
+
const ownershipConfigured = options.gateConfig.maxUnownedCritical !== void 0 || options.gateConfig.maxGhostOwners !== void 0 || options.gateConfig.maxDrift !== void 0;
|
|
10164
|
+
const needsOwnershipData = ownershipConfigured || CODEOWNERS_CANDIDATE_PATHS.some((candidate) => existsSync5(join9(repositoryPath, candidate)));
|
|
10165
|
+
let audit;
|
|
10166
|
+
if (needsOwnershipData) {
|
|
10167
|
+
logger.info(
|
|
10168
|
+
ownershipConfigured ? "auditing declared ownership for ownership gates" : "auditing declared ownership for the snapshot"
|
|
10169
|
+
);
|
|
10170
|
+
try {
|
|
10171
|
+
({ audit } = await buildOwnershipAudit(
|
|
10172
|
+
resolvedTargetPath,
|
|
10173
|
+
{
|
|
10174
|
+
...options.ownership?.ref === void 0 ? {} : { ref: options.ownership.ref },
|
|
10175
|
+
...options.ownership?.windowDays === void 0 ? {} : { windowDays: options.ownership.windowDays },
|
|
10176
|
+
...options.ownership?.minCommits === void 0 ? {} : { minCommits: options.ownership.minCommits }
|
|
10177
|
+
},
|
|
10178
|
+
logger
|
|
10179
|
+
));
|
|
10180
|
+
} catch (error) {
|
|
10181
|
+
if (error instanceof OwnersConfigurationError) {
|
|
10182
|
+
if (ownershipConfigured) {
|
|
10183
|
+
throw new GovernanceConfigurationError(error.message);
|
|
10184
|
+
}
|
|
10185
|
+
logger.warn(`ownership data unavailable: ${error.message}`);
|
|
10186
|
+
} else {
|
|
10187
|
+
throw error;
|
|
10188
|
+
}
|
|
10189
|
+
}
|
|
10190
|
+
}
|
|
10191
|
+
const ownershipReport = audit !== void 0 && audit.available ? toOwnershipAuditReport(audit) : void 0;
|
|
10192
|
+
const source = repositoryContext === null ? void 0 : { commit: repositoryContext.commit, ref: repositoryContext.ref };
|
|
10038
10193
|
logger.info("building current snapshot");
|
|
10039
10194
|
const current = await buildAnalysisSnapshot(
|
|
10040
10195
|
inputPath,
|
|
@@ -10042,7 +10197,9 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
|
|
|
10042
10197
|
{
|
|
10043
10198
|
includeTrace: options.includeTrace,
|
|
10044
10199
|
...options.scoringProfile === void 0 ? {} : { scoringProfile: options.scoringProfile },
|
|
10045
|
-
...options.recentWindowDays === void 0 ? {} : { recentWindowDays: options.recentWindowDays }
|
|
10200
|
+
...options.recentWindowDays === void 0 ? {} : { recentWindowDays: options.recentWindowDays },
|
|
10201
|
+
...source === void 0 ? {} : { source },
|
|
10202
|
+
...ownershipReport === void 0 ? {} : { ownership: ownershipReport }
|
|
10046
10203
|
},
|
|
10047
10204
|
logger
|
|
10048
10205
|
);
|
|
@@ -10129,28 +10286,9 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
|
|
|
10129
10286
|
}
|
|
10130
10287
|
diff = compareSnapshots(current, baseline);
|
|
10131
10288
|
}
|
|
10132
|
-
const ownershipConfigured = options.gateConfig.maxUnownedCritical !== void 0 || options.gateConfig.maxGhostOwners !== void 0 || options.gateConfig.maxDrift !== void 0;
|
|
10133
10289
|
let ownershipInput;
|
|
10134
10290
|
let ownershipSummary;
|
|
10135
|
-
if (ownershipConfigured) {
|
|
10136
|
-
logger.info("auditing declared ownership for ownership gates");
|
|
10137
|
-
let audit;
|
|
10138
|
-
try {
|
|
10139
|
-
({ audit } = await buildOwnershipAudit(
|
|
10140
|
-
resolvedTargetPath,
|
|
10141
|
-
{
|
|
10142
|
-
...options.ownership?.ref === void 0 ? {} : { ref: options.ownership.ref },
|
|
10143
|
-
...options.ownership?.windowDays === void 0 ? {} : { windowDays: options.ownership.windowDays },
|
|
10144
|
-
...options.ownership?.minCommits === void 0 ? {} : { minCommits: options.ownership.minCommits }
|
|
10145
|
-
},
|
|
10146
|
-
logger
|
|
10147
|
-
));
|
|
10148
|
-
} catch (error) {
|
|
10149
|
-
if (error instanceof OwnersConfigurationError) {
|
|
10150
|
-
throw new GovernanceConfigurationError(error.message);
|
|
10151
|
-
}
|
|
10152
|
-
throw error;
|
|
10153
|
-
}
|
|
10291
|
+
if (ownershipConfigured && audit !== void 0) {
|
|
10154
10292
|
if (audit.available) {
|
|
10155
10293
|
const metrics = {
|
|
10156
10294
|
declaredCoveragePercent: audit.metrics.declaredCoveragePercent,
|
|
@@ -10222,12 +10360,12 @@ ${ciMarkdown}`;
|
|
|
10222
10360
|
};
|
|
10223
10361
|
|
|
10224
10362
|
// src/application/run-report-command.ts
|
|
10225
|
-
import { join as
|
|
10363
|
+
import { join as join11 } from "path";
|
|
10226
10364
|
import { readFile as readFile7, writeFile as writeFile6 } from "fs/promises";
|
|
10227
10365
|
|
|
10228
10366
|
// src/application/html-report.ts
|
|
10229
10367
|
import { mkdir as mkdir3, readFile as readFile6, rm, stat as stat2, writeFile as writeFile5 } from "fs/promises";
|
|
10230
|
-
import { dirname as dirname2, join as
|
|
10368
|
+
import { dirname as dirname2, join as join10, resolve as resolve7 } from "path";
|
|
10231
10369
|
import { fileURLToPath } from "url";
|
|
10232
10370
|
var HTML_REPORT_DIR = ".codesentinel/report";
|
|
10233
10371
|
var getBundledHtmlAppPath = () => resolve7(dirname2(fileURLToPath(import.meta.url)), "html-report-app");
|
|
@@ -10290,7 +10428,7 @@ var assertHtmlAppAssets = async (assetPath) => {
|
|
|
10290
10428
|
};
|
|
10291
10429
|
var resolveHtmlReportOutputPath = (repositoryPath, outputPath) => {
|
|
10292
10430
|
const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
|
|
10293
|
-
return resolve7(invocationCwd, outputPath ??
|
|
10431
|
+
return resolve7(invocationCwd, outputPath ?? join10(repositoryPath, HTML_REPORT_DIR));
|
|
10294
10432
|
};
|
|
10295
10433
|
var writeHtmlReportBundle = async (report, options) => {
|
|
10296
10434
|
const bundledAppPath = options.bundledAppPath ?? getBundledHtmlAppPath();
|
|
@@ -10326,109 +10464,19 @@ var openPath = async (targetPath) => {
|
|
|
10326
10464
|
if (command === void 0) {
|
|
10327
10465
|
return false;
|
|
10328
10466
|
}
|
|
10329
|
-
return new Promise((
|
|
10467
|
+
return new Promise((resolve12) => {
|
|
10330
10468
|
const child = spawn3(command.command, command.args, {
|
|
10331
10469
|
detached: true,
|
|
10332
10470
|
stdio: "ignore"
|
|
10333
10471
|
});
|
|
10334
|
-
child.once("error", () =>
|
|
10472
|
+
child.once("error", () => resolve12(false));
|
|
10335
10473
|
child.once("spawn", () => {
|
|
10336
10474
|
child.unref();
|
|
10337
|
-
|
|
10475
|
+
resolve12(true);
|
|
10338
10476
|
});
|
|
10339
10477
|
});
|
|
10340
10478
|
};
|
|
10341
10479
|
|
|
10342
|
-
// src/application/report-ownership.ts
|
|
10343
|
-
import { execFileSync as execFileSync3 } from "child_process";
|
|
10344
|
-
var stripGitSuffix = (path) => path.replace(/\.git\/?$/i, "").replace(/\/+$/, "");
|
|
10345
|
-
var normalizeRepositoryWebUrl = (raw) => {
|
|
10346
|
-
const value = raw.trim();
|
|
10347
|
-
if (value.length === 0) {
|
|
10348
|
-
return null;
|
|
10349
|
-
}
|
|
10350
|
-
if (!value.includes("://")) {
|
|
10351
|
-
const scpMatch = value.match(/^(?:[^@\s]+@)?([^:/\s]+):(.+)$/);
|
|
10352
|
-
if (scpMatch === null) {
|
|
10353
|
-
return null;
|
|
10354
|
-
}
|
|
10355
|
-
const host = scpMatch[1];
|
|
10356
|
-
const path2 = stripGitSuffix(scpMatch[2] ?? "").replace(/^\/+/, "");
|
|
10357
|
-
if (host === void 0 || path2.length === 0) {
|
|
10358
|
-
return null;
|
|
10359
|
-
}
|
|
10360
|
-
return `https://${host}/${path2}`;
|
|
10361
|
-
}
|
|
10362
|
-
let url;
|
|
10363
|
-
try {
|
|
10364
|
-
url = new URL(value);
|
|
10365
|
-
} catch {
|
|
10366
|
-
return null;
|
|
10367
|
-
}
|
|
10368
|
-
if (url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "ssh:") {
|
|
10369
|
-
return null;
|
|
10370
|
-
}
|
|
10371
|
-
const path = stripGitSuffix(url.pathname).replace(/^\/+/, "");
|
|
10372
|
-
if (url.hostname.length === 0 || path.length === 0) {
|
|
10373
|
-
return null;
|
|
10374
|
-
}
|
|
10375
|
-
return `https://${url.hostname}/${path}`;
|
|
10376
|
-
};
|
|
10377
|
-
var readRepositoryWebUrl = (repositoryPath) => {
|
|
10378
|
-
try {
|
|
10379
|
-
const raw = execFileSync3(
|
|
10380
|
-
"git",
|
|
10381
|
-
["-C", repositoryPath, "config", "--get", "remote.origin.url"],
|
|
10382
|
-
{
|
|
10383
|
-
encoding: "utf8",
|
|
10384
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
10385
|
-
}
|
|
10386
|
-
);
|
|
10387
|
-
return normalizeRepositoryWebUrl(raw);
|
|
10388
|
-
} catch {
|
|
10389
|
-
return null;
|
|
10390
|
-
}
|
|
10391
|
-
};
|
|
10392
|
-
var toOwnershipAuditReport = (audit) => {
|
|
10393
|
-
if (!audit.available) {
|
|
10394
|
-
return {
|
|
10395
|
-
available: false,
|
|
10396
|
-
reason: audit.reason,
|
|
10397
|
-
warnings: audit.warnings
|
|
10398
|
-
};
|
|
10399
|
-
}
|
|
10400
|
-
return {
|
|
10401
|
-
available: true,
|
|
10402
|
-
codeowners: {
|
|
10403
|
-
source: audit.codeowners.source,
|
|
10404
|
-
ignoredSources: audit.codeowners.ignoredSources,
|
|
10405
|
-
errors: audit.codeowners.errors
|
|
10406
|
-
},
|
|
10407
|
-
metrics: audit.metrics,
|
|
10408
|
-
ghostOwners: audit.ghostOwners,
|
|
10409
|
-
files: audit.files,
|
|
10410
|
-
warnings: audit.warnings
|
|
10411
|
-
};
|
|
10412
|
-
};
|
|
10413
|
-
var buildReportOwnership = async (repositoryPath, logger) => {
|
|
10414
|
-
const webUrl = readRepositoryWebUrl(repositoryPath);
|
|
10415
|
-
try {
|
|
10416
|
-
const { audit } = await buildOwnershipAudit(repositoryPath, {}, logger);
|
|
10417
|
-
return { ownership: toOwnershipAuditReport(audit), webUrl };
|
|
10418
|
-
} catch (error) {
|
|
10419
|
-
const message = error instanceof Error ? error.message : "Unknown ownership audit error.";
|
|
10420
|
-
logger.warn(`ownership audit unavailable: ${message}`);
|
|
10421
|
-
return {
|
|
10422
|
-
ownership: {
|
|
10423
|
-
available: false,
|
|
10424
|
-
reason: "audit_unavailable",
|
|
10425
|
-
warnings: [message]
|
|
10426
|
-
},
|
|
10427
|
-
webUrl
|
|
10428
|
-
};
|
|
10429
|
-
}
|
|
10430
|
-
};
|
|
10431
|
-
|
|
10432
10480
|
// src/application/run-report-command.ts
|
|
10433
10481
|
var runReportCommand = async (inputPath, authorIdentityMode, options, logger = createSilentLogger()) => {
|
|
10434
10482
|
logger.info("building analysis snapshot");
|
|
@@ -10467,7 +10515,7 @@ var runReportCommand = async (inputPath, authorIdentityMode, options, logger = c
|
|
|
10467
10515
|
...options.outputPath === void 0 ? {} : { outputPath: options.outputPath }
|
|
10468
10516
|
});
|
|
10469
10517
|
if (options.open === true) {
|
|
10470
|
-
const opened = await openPath(
|
|
10518
|
+
const opened = await openPath(join11(bundlePath, "index.html"));
|
|
10471
10519
|
if (!opened) {
|
|
10472
10520
|
logger.warn("unable to open html report automatically on this platform");
|
|
10473
10521
|
}
|
|
@@ -10976,9 +11024,402 @@ var runOwnersCommand = async (inputPath, options = {}, logger = createSilentLogg
|
|
|
10976
11024
|
};
|
|
10977
11025
|
var hasConfiguredThreshold = (thresholds) => thresholds.maxUnownedCritical !== null || thresholds.maxGhostOwners !== null || thresholds.maxDrift !== null;
|
|
10978
11026
|
|
|
11027
|
+
// src/application/run-trend-command.ts
|
|
11028
|
+
import { writeFile as writeFile8 } from "fs/promises";
|
|
11029
|
+
|
|
11030
|
+
// src/application/format-trend-output.ts
|
|
11031
|
+
var TREND_SCHEMA_VERSION = "codesentinel.trend.v1";
|
|
11032
|
+
var buildTrendReport = (series, warnings) => {
|
|
11033
|
+
const first = series[0];
|
|
11034
|
+
const last = series[series.length - 1];
|
|
11035
|
+
const deltas = series.length < 2 || first === void 0 || last === void 0 ? null : buildDeltas(first, last);
|
|
11036
|
+
return {
|
|
11037
|
+
schemaVersion: TREND_SCHEMA_VERSION,
|
|
11038
|
+
series: [...series],
|
|
11039
|
+
deltas,
|
|
11040
|
+
warnings: [...warnings]
|
|
11041
|
+
};
|
|
11042
|
+
};
|
|
11043
|
+
var roundToHundredths = (value) => {
|
|
11044
|
+
const rounded = Math.round(value * 100) / 100;
|
|
11045
|
+
return rounded === 0 ? 0 : rounded;
|
|
11046
|
+
};
|
|
11047
|
+
var buildDeltas = (first, last) => ({
|
|
11048
|
+
riskScore: roundToHundredths(last.riskScore - first.riskScore),
|
|
11049
|
+
healthScore: roundToHundredths(last.healthScore - first.healthScore),
|
|
11050
|
+
unownedCritical: first.ownership === null || last.ownership === null ? null : roundToHundredths(last.ownership.unownedCritical - first.ownership.unownedCritical),
|
|
11051
|
+
ghostOwners: first.ownership === null || last.ownership === null ? null : roundToHundredths(last.ownership.ghostOwners - first.ownership.ghostOwners),
|
|
11052
|
+
driftPercent: first.ownership === null || last.ownership === null ? null : roundToHundredths(last.ownership.driftPercent - first.ownership.driftPercent)
|
|
11053
|
+
});
|
|
11054
|
+
var formatDate = (value) => new Date(value).toISOString().slice(0, 16).replace("T", " ");
|
|
11055
|
+
var formatCommit = (commit) => commit === null ? "\u2014" : commit.slice(0, 7);
|
|
11056
|
+
var formatNumber2 = (value) => String(roundToHundredths(value));
|
|
11057
|
+
var formatPercent2 = (value) => `${formatNumber2(value)}%`;
|
|
11058
|
+
var formatDelta = (value) => {
|
|
11059
|
+
const rounded = roundToHundredths(value);
|
|
11060
|
+
return rounded === 0 ? "0" : rounded > 0 ? `+${formatNumber2(rounded)}` : formatNumber2(rounded);
|
|
11061
|
+
};
|
|
11062
|
+
var pointCells = (point) => [
|
|
11063
|
+
formatDate(point.generatedAt),
|
|
11064
|
+
formatCommit(point.commit),
|
|
11065
|
+
formatNumber2(point.riskScore),
|
|
11066
|
+
formatNumber2(point.healthScore),
|
|
11067
|
+
point.ownership === null ? "\u2014" : formatNumber2(point.ownership.unownedCritical),
|
|
11068
|
+
point.ownership === null ? "\u2014" : formatNumber2(point.ownership.ghostOwners),
|
|
11069
|
+
point.ownership === null ? "\u2014" : formatPercent2(point.ownership.driftPercent)
|
|
11070
|
+
];
|
|
11071
|
+
var renderDeltas = (deltas) => [
|
|
11072
|
+
`\u0394 risk ${formatDelta(deltas.riskScore)}`,
|
|
11073
|
+
`\u0394 health ${formatDelta(deltas.healthScore)}`,
|
|
11074
|
+
`\u0394 unowned ${deltas.unownedCritical === null ? "\u2014" : formatDelta(deltas.unownedCritical)}`,
|
|
11075
|
+
`\u0394 ghosts ${deltas.ghostOwners === null ? "\u2014" : formatDelta(deltas.ghostOwners)}`,
|
|
11076
|
+
`\u0394 drift ${deltas.driftPercent === null ? "\u2014" : `${formatDelta(deltas.driftPercent)}pp`}`
|
|
11077
|
+
].join(" ");
|
|
11078
|
+
var renderHeader = (report) => {
|
|
11079
|
+
const count = report.series.length;
|
|
11080
|
+
const label = `${count} ${count === 1 ? "snapshot" : "snapshots"}`;
|
|
11081
|
+
const first = report.series[0];
|
|
11082
|
+
const last = report.series[count - 1];
|
|
11083
|
+
if (first === void 0 || last === void 0) {
|
|
11084
|
+
return `Snapshot trend \u2014 ${label}`;
|
|
11085
|
+
}
|
|
11086
|
+
return `Snapshot trend \u2014 ${label} (${formatDate(first.generatedAt)} \u2192 ${formatDate(last.generatedAt)})`;
|
|
11087
|
+
};
|
|
11088
|
+
var appendWarnings2 = (lines, warnings) => {
|
|
11089
|
+
if (warnings.length === 0) return;
|
|
11090
|
+
lines.push("");
|
|
11091
|
+
lines.push("Warnings");
|
|
11092
|
+
for (const warning of warnings) {
|
|
11093
|
+
lines.push(` - ${warning}`);
|
|
11094
|
+
}
|
|
11095
|
+
};
|
|
11096
|
+
var TREND_HEADERS = ["Date", "Commit", "Risk", "Health", "Unowned", "Ghosts", "Drift"];
|
|
11097
|
+
var renderAlignedRow = (cells, widths) => cells.map((cell, index) => {
|
|
11098
|
+
const width = widths[index] ?? cell.length;
|
|
11099
|
+
return index < 2 ? cell.padEnd(width) : cell.padStart(width);
|
|
11100
|
+
}).join(" ");
|
|
11101
|
+
var renderConsole2 = (report) => {
|
|
11102
|
+
const rows = report.series.map(pointCells);
|
|
11103
|
+
const widths = TREND_HEADERS.map(
|
|
11104
|
+
(header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length))
|
|
11105
|
+
);
|
|
11106
|
+
const lines = [renderHeader(report), ""];
|
|
11107
|
+
lines.push(renderAlignedRow(TREND_HEADERS, widths).trimEnd());
|
|
11108
|
+
for (const row of rows) {
|
|
11109
|
+
lines.push(renderAlignedRow(row, widths).trimEnd());
|
|
11110
|
+
}
|
|
11111
|
+
if (report.deltas === null) {
|
|
11112
|
+
lines.push("");
|
|
11113
|
+
lines.push("not enough history for a trend");
|
|
11114
|
+
} else {
|
|
11115
|
+
lines.push("");
|
|
11116
|
+
lines.push(renderDeltas(report.deltas));
|
|
11117
|
+
}
|
|
11118
|
+
appendWarnings2(lines, report.warnings);
|
|
11119
|
+
return lines.join("\n");
|
|
11120
|
+
};
|
|
11121
|
+
var escapeTableCell2 = (value) => value.replace(/\|/g, "\\|");
|
|
11122
|
+
var renderMarkdownTable2 = (header, rows) => {
|
|
11123
|
+
const lines = [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`];
|
|
11124
|
+
for (const row of rows) {
|
|
11125
|
+
lines.push(`| ${row.map(escapeTableCell2).join(" | ")} |`);
|
|
11126
|
+
}
|
|
11127
|
+
return lines;
|
|
11128
|
+
};
|
|
11129
|
+
var renderMarkdown3 = (report) => {
|
|
11130
|
+
const lines = ["# Snapshot trend", ""];
|
|
11131
|
+
lines.push(`- snapshots: ${report.series.length}`);
|
|
11132
|
+
const first = report.series[0];
|
|
11133
|
+
const last = report.series[report.series.length - 1];
|
|
11134
|
+
if (first !== void 0 && last !== void 0) {
|
|
11135
|
+
lines.push(`- window: ${formatDate(first.generatedAt)} \u2192 ${formatDate(last.generatedAt)}`);
|
|
11136
|
+
}
|
|
11137
|
+
lines.push("");
|
|
11138
|
+
lines.push(...renderMarkdownTable2(TREND_HEADERS, report.series.map(pointCells)));
|
|
11139
|
+
if (report.deltas === null) {
|
|
11140
|
+
lines.push("");
|
|
11141
|
+
lines.push("not enough history for a trend");
|
|
11142
|
+
} else {
|
|
11143
|
+
lines.push("");
|
|
11144
|
+
lines.push(renderDeltas(report.deltas));
|
|
11145
|
+
}
|
|
11146
|
+
if (report.warnings.length > 0) {
|
|
11147
|
+
lines.push("");
|
|
11148
|
+
lines.push("## Warnings");
|
|
11149
|
+
lines.push("");
|
|
11150
|
+
for (const warning of report.warnings) {
|
|
11151
|
+
lines.push(`- ${warning}`);
|
|
11152
|
+
}
|
|
11153
|
+
}
|
|
11154
|
+
return lines.join("\n");
|
|
11155
|
+
};
|
|
11156
|
+
var formatTrendOutput = (report, format) => {
|
|
11157
|
+
if (format === "json") {
|
|
11158
|
+
return JSON.stringify(report, null, 2);
|
|
11159
|
+
}
|
|
11160
|
+
return format === "md" ? renderMarkdown3(report) : renderConsole2(report);
|
|
11161
|
+
};
|
|
11162
|
+
|
|
11163
|
+
// src/application/read-trend-snapshots.ts
|
|
11164
|
+
import { glob, readFile as readFile8, readdir as readdir2, stat as stat3 } from "fs/promises";
|
|
11165
|
+
import { basename as basename5, join as join12, resolve as resolve9 } from "path";
|
|
11166
|
+
var TrendConfigurationError = class extends Error {
|
|
11167
|
+
constructor(message) {
|
|
11168
|
+
super(message);
|
|
11169
|
+
this.name = "TrendConfigurationError";
|
|
11170
|
+
}
|
|
11171
|
+
};
|
|
11172
|
+
var compareText4 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
11173
|
+
var asRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
|
|
11174
|
+
var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
|
|
11175
|
+
var readCommit = (snapshot) => {
|
|
11176
|
+
const candidates = [
|
|
11177
|
+
snapshot["commit"],
|
|
11178
|
+
asRecord(snapshot["git"])?.["commit"],
|
|
11179
|
+
asRecord(snapshot["source"])?.["commit"],
|
|
11180
|
+
asRecord(snapshot["analysisConfig"])?.["commit"]
|
|
11181
|
+
];
|
|
11182
|
+
for (const candidate of candidates) {
|
|
11183
|
+
if (typeof candidate === "string" && candidate.trim().length > 0) {
|
|
11184
|
+
return candidate;
|
|
11185
|
+
}
|
|
11186
|
+
}
|
|
11187
|
+
return null;
|
|
11188
|
+
};
|
|
11189
|
+
var readOwnership = (snapshot) => {
|
|
11190
|
+
const ownership = asRecord(snapshot["ownership"]);
|
|
11191
|
+
if (ownership === null || ownership["available"] === false) {
|
|
11192
|
+
return null;
|
|
11193
|
+
}
|
|
11194
|
+
const source = asRecord(ownership["metrics"]) ?? ownership;
|
|
11195
|
+
const unownedCritical = source["unownedCriticalCount"];
|
|
11196
|
+
const ghostOwners = source["ghostOwnerCount"];
|
|
11197
|
+
const driftPercent = source["driftPercent"];
|
|
11198
|
+
if (!isFiniteNumber(unownedCritical) || !isFiniteNumber(ghostOwners) || !isFiniteNumber(driftPercent)) {
|
|
11199
|
+
return null;
|
|
11200
|
+
}
|
|
11201
|
+
return { unownedCritical, ghostOwners, driftPercent };
|
|
11202
|
+
};
|
|
11203
|
+
var formatSchemaVersion = (value) => {
|
|
11204
|
+
if (value === void 0) return "missing";
|
|
11205
|
+
if (typeof value === "string") return value;
|
|
11206
|
+
if (typeof value === "number" || typeof value === "boolean" || value === null) {
|
|
11207
|
+
return String(value);
|
|
11208
|
+
}
|
|
11209
|
+
return JSON.stringify(value) ?? "invalid";
|
|
11210
|
+
};
|
|
11211
|
+
var isSupportedSchemaVersion2 = (value) => typeof value === "string" && SUPPORTED_SNAPSHOT_SCHEMA_VERSIONS.includes(value);
|
|
11212
|
+
var parseSnapshot2 = (fileName, content) => {
|
|
11213
|
+
let parsed;
|
|
11214
|
+
try {
|
|
11215
|
+
parsed = JSON.parse(content);
|
|
11216
|
+
} catch {
|
|
11217
|
+
return { point: null, warning: `skipped ${fileName}: invalid JSON` };
|
|
11218
|
+
}
|
|
11219
|
+
const snapshot = asRecord(parsed);
|
|
11220
|
+
if (snapshot === null) {
|
|
11221
|
+
return { point: null, warning: `skipped ${fileName}: unsupported schema version "missing"` };
|
|
11222
|
+
}
|
|
11223
|
+
const schemaVersion = snapshot["schemaVersion"];
|
|
11224
|
+
if (!isSupportedSchemaVersion2(schemaVersion)) {
|
|
11225
|
+
const label = formatSchemaVersion(schemaVersion);
|
|
11226
|
+
return {
|
|
11227
|
+
point: null,
|
|
11228
|
+
warning: `skipped ${fileName}: unsupported schema version "${label}"`
|
|
11229
|
+
};
|
|
11230
|
+
}
|
|
11231
|
+
const generatedAt = snapshot["generatedAt"];
|
|
11232
|
+
if (typeof generatedAt !== "string" || Number.isNaN(Date.parse(generatedAt))) {
|
|
11233
|
+
return { point: null, warning: `skipped ${fileName}: missing or invalid generatedAt` };
|
|
11234
|
+
}
|
|
11235
|
+
const analysis = asRecord(snapshot["analysis"]);
|
|
11236
|
+
const riskScore = asRecord(analysis?.["risk"])?.["riskScore"];
|
|
11237
|
+
const healthScore = asRecord(analysis?.["health"])?.["healthScore"];
|
|
11238
|
+
if (!isFiniteNumber(riskScore) || !isFiniteNumber(healthScore)) {
|
|
11239
|
+
return { point: null, warning: `skipped ${fileName}: missing risk or health score` };
|
|
11240
|
+
}
|
|
11241
|
+
return {
|
|
11242
|
+
point: {
|
|
11243
|
+
file: fileName,
|
|
11244
|
+
generatedAt,
|
|
11245
|
+
commit: readCommit(snapshot),
|
|
11246
|
+
riskScore,
|
|
11247
|
+
healthScore,
|
|
11248
|
+
ownership: readOwnership(snapshot)
|
|
11249
|
+
},
|
|
11250
|
+
warning: null
|
|
11251
|
+
};
|
|
11252
|
+
};
|
|
11253
|
+
var pathExists = async (absolutePath) => {
|
|
11254
|
+
try {
|
|
11255
|
+
await stat3(absolutePath);
|
|
11256
|
+
return true;
|
|
11257
|
+
} catch {
|
|
11258
|
+
return false;
|
|
11259
|
+
}
|
|
11260
|
+
};
|
|
11261
|
+
var discoverSnapshotFiles = async (from) => {
|
|
11262
|
+
const cwd = process.env["INIT_CWD"] ?? process.cwd();
|
|
11263
|
+
const resolved = resolve9(cwd, from);
|
|
11264
|
+
const exists = await pathExists(resolved);
|
|
11265
|
+
if (exists) {
|
|
11266
|
+
const info = await stat3(resolved);
|
|
11267
|
+
if (info.isDirectory()) {
|
|
11268
|
+
const entries = await readdir2(resolved, { withFileTypes: true }).catch(() => {
|
|
11269
|
+
throw new TrendConfigurationError(`--from directory is not readable: ${from}`);
|
|
11270
|
+
});
|
|
11271
|
+
const files2 = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => ({ path: join12(resolved, entry.name), name: entry.name })).sort((a, b) => compareText4(a.name, b.name));
|
|
11272
|
+
if (files2.length === 0) {
|
|
11273
|
+
throw new TrendConfigurationError(`no snapshot JSON files found in ${from}`);
|
|
11274
|
+
}
|
|
11275
|
+
return files2;
|
|
11276
|
+
}
|
|
11277
|
+
}
|
|
11278
|
+
const hasGlobMetacharacters = /[*?[\]{}()!]/.test(from);
|
|
11279
|
+
if (!exists && !hasGlobMetacharacters) {
|
|
11280
|
+
throw new TrendConfigurationError(`--from path not found: ${from}`);
|
|
11281
|
+
}
|
|
11282
|
+
const matches = [];
|
|
11283
|
+
try {
|
|
11284
|
+
for await (const match of glob(from, { cwd })) {
|
|
11285
|
+
matches.push(match);
|
|
11286
|
+
}
|
|
11287
|
+
} catch {
|
|
11288
|
+
throw new TrendConfigurationError(`--from pattern could not be read: ${from}`);
|
|
11289
|
+
}
|
|
11290
|
+
const files = [];
|
|
11291
|
+
for (const match of matches.sort(compareText4)) {
|
|
11292
|
+
const absolutePath = resolve9(cwd, match);
|
|
11293
|
+
try {
|
|
11294
|
+
const info = await stat3(absolutePath);
|
|
11295
|
+
if (!info.isFile() || !absolutePath.endsWith(".json")) {
|
|
11296
|
+
continue;
|
|
11297
|
+
}
|
|
11298
|
+
} catch {
|
|
11299
|
+
continue;
|
|
11300
|
+
}
|
|
11301
|
+
files.push({ path: absolutePath, name: basename5(absolutePath) });
|
|
11302
|
+
}
|
|
11303
|
+
if (files.length === 0) {
|
|
11304
|
+
throw new TrendConfigurationError(`--from matched no snapshot JSON files: ${from}`);
|
|
11305
|
+
}
|
|
11306
|
+
return files;
|
|
11307
|
+
};
|
|
11308
|
+
var parseSinceDays = (since) => {
|
|
11309
|
+
if (since === void 0) {
|
|
11310
|
+
return null;
|
|
11311
|
+
}
|
|
11312
|
+
if (!/^\d+d$/.test(since)) {
|
|
11313
|
+
throw new TrendConfigurationError("--since must be a day window like 90d");
|
|
11314
|
+
}
|
|
11315
|
+
const days = Number.parseInt(since.slice(0, -1), 10);
|
|
11316
|
+
if (!Number.isInteger(days) || days <= 0) {
|
|
11317
|
+
throw new TrendConfigurationError("--since must be a day window like 90d");
|
|
11318
|
+
}
|
|
11319
|
+
return days;
|
|
11320
|
+
};
|
|
11321
|
+
var parseLast = (last) => {
|
|
11322
|
+
if (last === void 0) {
|
|
11323
|
+
return null;
|
|
11324
|
+
}
|
|
11325
|
+
if (!Number.isInteger(last) || last <= 0) {
|
|
11326
|
+
throw new TrendConfigurationError("--last must be a positive integer");
|
|
11327
|
+
}
|
|
11328
|
+
return last;
|
|
11329
|
+
};
|
|
11330
|
+
var comparePoints = (a, b) => {
|
|
11331
|
+
const timeDifference = Date.parse(a.generatedAt) - Date.parse(b.generatedAt);
|
|
11332
|
+
if (timeDifference !== 0) {
|
|
11333
|
+
return timeDifference;
|
|
11334
|
+
}
|
|
11335
|
+
return compareText4(a.file, b.file);
|
|
11336
|
+
};
|
|
11337
|
+
var deduplicatePoints = (points) => {
|
|
11338
|
+
const seen = /* @__PURE__ */ new Set();
|
|
11339
|
+
const unique = [];
|
|
11340
|
+
for (const point of points) {
|
|
11341
|
+
const key = point.generatedAt + "\0" + (point.commit ?? "");
|
|
11342
|
+
if (seen.has(key)) {
|
|
11343
|
+
continue;
|
|
11344
|
+
}
|
|
11345
|
+
seen.add(key);
|
|
11346
|
+
unique.push(point);
|
|
11347
|
+
}
|
|
11348
|
+
return unique;
|
|
11349
|
+
};
|
|
11350
|
+
var readTrendSnapshots = async (options) => {
|
|
11351
|
+
const from = options.from;
|
|
11352
|
+
if (from === void 0 || from.trim().length === 0) {
|
|
11353
|
+
throw new TrendConfigurationError("--from is required");
|
|
11354
|
+
}
|
|
11355
|
+
const sinceDays = parseSinceDays(options.since);
|
|
11356
|
+
const last = parseLast(options.last);
|
|
11357
|
+
const files = await discoverSnapshotFiles(from);
|
|
11358
|
+
const warnings = [];
|
|
11359
|
+
const points = [];
|
|
11360
|
+
for (const file of files) {
|
|
11361
|
+
let content;
|
|
11362
|
+
try {
|
|
11363
|
+
content = await readFile8(file.path, "utf8");
|
|
11364
|
+
} catch {
|
|
11365
|
+
warnings.push(`skipped ${file.name}: invalid JSON`);
|
|
11366
|
+
continue;
|
|
11367
|
+
}
|
|
11368
|
+
const parsed = parseSnapshot2(file.name, content);
|
|
11369
|
+
if (parsed.point === null) {
|
|
11370
|
+
warnings.push(parsed.warning);
|
|
11371
|
+
continue;
|
|
11372
|
+
}
|
|
11373
|
+
points.push(parsed.point);
|
|
11374
|
+
}
|
|
11375
|
+
if (points.length === 0) {
|
|
11376
|
+
throw new TrendConfigurationError("no readable snapshots were found");
|
|
11377
|
+
}
|
|
11378
|
+
const ordered = deduplicatePoints([...points].sort(comparePoints));
|
|
11379
|
+
let filtered = ordered;
|
|
11380
|
+
if (sinceDays !== null) {
|
|
11381
|
+
const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
11382
|
+
const cutoff = now.getTime() - sinceDays * 24 * 60 * 60 * 1e3;
|
|
11383
|
+
filtered = filtered.filter((point) => Date.parse(point.generatedAt) >= cutoff);
|
|
11384
|
+
}
|
|
11385
|
+
if (last !== null) {
|
|
11386
|
+
filtered = filtered.slice(-last);
|
|
11387
|
+
}
|
|
11388
|
+
return { series: filtered, warnings };
|
|
11389
|
+
};
|
|
11390
|
+
|
|
11391
|
+
// src/application/run-trend-command.ts
|
|
11392
|
+
var TREND_EXIT_CODES = {
|
|
11393
|
+
ok: 0,
|
|
11394
|
+
invalidConfiguration: 2
|
|
11395
|
+
};
|
|
11396
|
+
var runTrendCommand = async (options, logger = createSilentLogger()) => {
|
|
11397
|
+
const format = options.format ?? "console";
|
|
11398
|
+
const { series, warnings } = await readTrendSnapshots({
|
|
11399
|
+
...options.from === void 0 ? {} : { from: options.from },
|
|
11400
|
+
...options.since === void 0 ? {} : { since: options.since },
|
|
11401
|
+
...options.last === void 0 ? {} : { last: options.last },
|
|
11402
|
+
...options.now === void 0 ? {} : { now: options.now }
|
|
11403
|
+
});
|
|
11404
|
+
const report = buildTrendReport(series, warnings);
|
|
11405
|
+
const rendered = formatTrendOutput(report, format);
|
|
11406
|
+
logger.debug(`trend series: ${report.series.length} snapshot(s)`);
|
|
11407
|
+
if (options.outputPath !== void 0) {
|
|
11408
|
+
await writeFile8(options.outputPath, `${rendered}
|
|
11409
|
+
`, "utf8");
|
|
11410
|
+
logger.info(`trend output written: ${options.outputPath}`);
|
|
11411
|
+
}
|
|
11412
|
+
return {
|
|
11413
|
+
report,
|
|
11414
|
+
rendered,
|
|
11415
|
+
exitCode: TREND_EXIT_CODES.ok,
|
|
11416
|
+
...options.outputPath === void 0 ? {} : { outputPath: options.outputPath }
|
|
11417
|
+
};
|
|
11418
|
+
};
|
|
11419
|
+
|
|
10979
11420
|
// src/application/run-init-command.ts
|
|
10980
|
-
import { access, mkdir as mkdir4, writeFile as
|
|
10981
|
-
import { dirname as dirname3, join as
|
|
11421
|
+
import { access, mkdir as mkdir4, writeFile as writeFile9 } from "fs/promises";
|
|
11422
|
+
import { dirname as dirname3, join as join13, resolve as resolve10 } from "path";
|
|
10982
11423
|
var CODESENTINEL_WORKFLOW_PATH = ".github/workflows/codesentinel.yml";
|
|
10983
11424
|
var CODESENTINEL_OWNERS_PATH = ".codesentinel/owners.json";
|
|
10984
11425
|
var CODESENTINEL_WORKFLOW_TEMPLATE = `name: CodeSentinel
|
|
@@ -11120,7 +11561,7 @@ var fileExists = async (absolutePath) => {
|
|
|
11120
11561
|
};
|
|
11121
11562
|
var anyFileExists = async (targetPath, candidates) => {
|
|
11122
11563
|
for (const candidate of candidates) {
|
|
11123
|
-
if (await fileExists(
|
|
11564
|
+
if (await fileExists(join13(targetPath, candidate))) {
|
|
11124
11565
|
return true;
|
|
11125
11566
|
}
|
|
11126
11567
|
}
|
|
@@ -11128,7 +11569,7 @@ var anyFileExists = async (targetPath, candidates) => {
|
|
|
11128
11569
|
};
|
|
11129
11570
|
var resolveTargetPath3 = (inputPath) => {
|
|
11130
11571
|
const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
|
|
11131
|
-
return
|
|
11572
|
+
return resolve10(invocationCwd, inputPath ?? ".");
|
|
11132
11573
|
};
|
|
11133
11574
|
var runInitCommand = async (inputPath, options = {}) => {
|
|
11134
11575
|
const targetPath = resolveTargetPath3(inputPath);
|
|
@@ -11136,8 +11577,8 @@ var runInitCommand = async (inputPath, options = {}) => {
|
|
|
11136
11577
|
const hasCodeownersFile = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);
|
|
11137
11578
|
const plan = buildInitPlan({
|
|
11138
11579
|
hasCodeownersFile,
|
|
11139
|
-
workflowExists: ci === "github" && await fileExists(
|
|
11140
|
-
ownersFileExists: hasCodeownersFile && await fileExists(
|
|
11580
|
+
workflowExists: ci === "github" && await fileExists(join13(targetPath, CODESENTINEL_WORKFLOW_PATH)),
|
|
11581
|
+
ownersFileExists: hasCodeownersFile && await fileExists(join13(targetPath, CODESENTINEL_OWNERS_PATH)),
|
|
11141
11582
|
options: { ...options, ci }
|
|
11142
11583
|
});
|
|
11143
11584
|
if (options.dryRun !== true) {
|
|
@@ -11145,9 +11586,9 @@ var runInitCommand = async (inputPath, options = {}) => {
|
|
|
11145
11586
|
if (entry.status !== "created" && entry.status !== "updated") {
|
|
11146
11587
|
continue;
|
|
11147
11588
|
}
|
|
11148
|
-
const absolutePath =
|
|
11589
|
+
const absolutePath = join13(targetPath, entry.path);
|
|
11149
11590
|
await mkdir4(dirname3(absolutePath), { recursive: true });
|
|
11150
|
-
await
|
|
11591
|
+
await writeFile9(absolutePath, entry.content ?? "", "utf8");
|
|
11151
11592
|
}
|
|
11152
11593
|
}
|
|
11153
11594
|
return {
|
|
@@ -11160,7 +11601,7 @@ var runInitCommand = async (inputPath, options = {}) => {
|
|
|
11160
11601
|
|
|
11161
11602
|
// src/index.ts
|
|
11162
11603
|
var program = new Command();
|
|
11163
|
-
var packageJsonPath =
|
|
11604
|
+
var packageJsonPath = resolve11(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
|
|
11164
11605
|
var { version } = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
|
|
11165
11606
|
var parseRecentWindowDays = (value) => {
|
|
11166
11607
|
const parsed = Number.parseInt(value, 10);
|
|
@@ -11484,12 +11925,12 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
|
|
|
11484
11925
|
...options.trace === true ? { trace: explain.trace } : {}
|
|
11485
11926
|
});
|
|
11486
11927
|
if (options.snapshot !== void 0) {
|
|
11487
|
-
await
|
|
11928
|
+
await writeFile10(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
|
|
11488
11929
|
logger.info(`snapshot written: ${options.snapshot}`);
|
|
11489
11930
|
}
|
|
11490
11931
|
const report = options.compare === void 0 ? createReport(snapshot) : createReport(
|
|
11491
11932
|
snapshot,
|
|
11492
|
-
compareSnapshots(snapshot, parseSnapshot(await
|
|
11933
|
+
compareSnapshots(snapshot, parseSnapshot(await readFile9(options.compare, "utf8")))
|
|
11493
11934
|
);
|
|
11494
11935
|
if (options.report === "html") {
|
|
11495
11936
|
const htmlOutputPath = await writeHtmlReportBundle(report, {
|
|
@@ -11966,6 +12407,49 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
|
|
|
11966
12407
|
}
|
|
11967
12408
|
}
|
|
11968
12409
|
);
|
|
12410
|
+
program.command("trend").exitOverride().option(
|
|
12411
|
+
"--from <dir-or-glob>",
|
|
12412
|
+
"directory of snapshot JSON files (non-recursive) or a glob pattern (required)"
|
|
12413
|
+
).option("--since <window>", "only include snapshots newer than this window, for example 90d").option("--last <count>", "only include the N most recent snapshots").addOption(
|
|
12414
|
+
new Option(
|
|
12415
|
+
"--format <mode>",
|
|
12416
|
+
"output format: console (default), json (stable payload) or md (pastes into a PR)"
|
|
12417
|
+
).choices(["console", "json", "md"]).default("console")
|
|
12418
|
+
).option("--output <file>", "write the rendered output to a file instead of stdout").addOption(
|
|
12419
|
+
new Option(
|
|
12420
|
+
"--log-level <level>",
|
|
12421
|
+
"log verbosity: silent, error, warn, info, debug (logs are written to stderr)"
|
|
12422
|
+
).choices(["silent", "error", "warn", "info", "debug"]).default(parseLogLevel(process.env["CODESENTINEL_LOG_LEVEL"]))
|
|
12423
|
+
).action(
|
|
12424
|
+
async (options) => {
|
|
12425
|
+
const logger = createStderrLogger(options.logLevel);
|
|
12426
|
+
try {
|
|
12427
|
+
const result = await runTrendCommand(
|
|
12428
|
+
{
|
|
12429
|
+
...options.from === void 0 ? {} : { from: options.from },
|
|
12430
|
+
...options.since === void 0 ? {} : { since: options.since },
|
|
12431
|
+
...options.last === void 0 ? {} : { last: Number(options.last) },
|
|
12432
|
+
format: options.format,
|
|
12433
|
+
...options.output === void 0 ? {} : { outputPath: options.output }
|
|
12434
|
+
},
|
|
12435
|
+
logger
|
|
12436
|
+
);
|
|
12437
|
+
if (result.outputPath === void 0) {
|
|
12438
|
+
process.stdout.write(`${result.rendered}
|
|
12439
|
+
`);
|
|
12440
|
+
}
|
|
12441
|
+
process.exitCode = result.exitCode;
|
|
12442
|
+
} catch (error) {
|
|
12443
|
+
if (error instanceof TrendConfigurationError) {
|
|
12444
|
+
logger.error(error.message);
|
|
12445
|
+
process.exitCode = TREND_EXIT_CODES.invalidConfiguration;
|
|
12446
|
+
return;
|
|
12447
|
+
}
|
|
12448
|
+
logger.error(error instanceof Error ? error.message : "internal error");
|
|
12449
|
+
process.exitCode = TREND_EXIT_CODES.invalidConfiguration;
|
|
12450
|
+
}
|
|
12451
|
+
}
|
|
12452
|
+
);
|
|
11969
12453
|
program.command("init").argument("[path]", "path to the repository to scaffold").option("--force", "overwrite generated files that already exist").addOption(
|
|
11970
12454
|
new Option("--ci <mode>", "CI provider: github (default) or none").choices(["github", "none"]).default("github")
|
|
11971
12455
|
).option("--dry-run", "print what would be written without writing anything").action(
|