dsh-git-push 0.0.0-stage → 2.8.4
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/.auditignore +30 -0
- package/.gitignore +39 -0
- package/LICENSE +21 -0
- package/README.md +1482 -2
- package/cli.mjs +360 -0
- package/cordis.patch.yml +14 -0
- package/lib/ARCHITECTURE.md +34 -0
- package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
- package/lib/app/apply.js +275 -0
- package/lib/app/audit-api.js +158 -0
- package/lib/app/command-registry.js +262 -0
- package/lib/app/constants.js +16 -0
- package/lib/app/handlers/account.js +166 -0
- package/lib/app/handlers/clone.js +168 -0
- package/lib/app/handlers/http-constants.js +9 -0
- package/lib/app/handlers/identity-rewrite.js +94 -0
- package/lib/app/handlers/meta.js +175 -0
- package/lib/app/handlers/npm.js +169 -0
- package/lib/app/handlers/repo-actions.js +143 -0
- package/lib/app/handlers/repos.js +231 -0
- package/lib/app/handlers/settings.js +62 -0
- package/lib/app/host-doc-checks.js +25 -0
- package/lib/app/http-handlers.js +131 -0
- package/lib/app/index.js +30 -0
- package/lib/app/inject-text.js +191 -0
- package/lib/app/scan-root.js +23 -0
- package/lib/app/schema.js +150 -0
- package/lib/app/settings-bridge.js +167 -0
- package/lib/app/slash-commands.js +395 -0
- package/lib/app/slot-stats.js +35 -0
- package/lib/app/tool-call.js +662 -0
- package/lib/app/tools.js +40 -0
- package/lib/ast/brace.js +105 -0
- package/lib/ast/callgraph.js +135 -0
- package/lib/ast/code-lines.js +114 -0
- package/lib/ast/consts.js +12 -0
- package/lib/ast/control-flow.js +461 -0
- package/lib/ast/credential.js +199 -0
- package/lib/ast/dataflow.js +274 -0
- package/lib/ast/dup-code.js +165 -0
- package/lib/ast/index.js +36 -0
- package/lib/ast/io-risk-const.js +95 -0
- package/lib/ast/io-risk-fn.js +208 -0
- package/lib/ast/io-risk-loop.js +308 -0
- package/lib/ast/io-risk.js +314 -0
- package/lib/ast/lang.js +156 -0
- package/lib/ast/line-count.js +52 -0
- package/lib/ast/magic-number.js +272 -0
- package/lib/ast/naming.js +284 -0
- package/lib/ast/perf.js +472 -0
- package/lib/ast/scope.js +241 -0
- package/lib/ast/shell.js +131 -0
- package/lib/ast/size.js +378 -0
- package/lib/ast/symbol-index.js +399 -0
- package/lib/ast/tokenizer.js +341 -0
- package/lib/audit/analysis-coverage.js +98 -0
- package/lib/audit/audit-file.js +182 -0
- package/lib/audit/checks.js +17 -0
- package/lib/audit/client-entry.js +93 -0
- package/lib/audit/collector.js +477 -0
- package/lib/audit/ext-runner.js +80 -0
- package/lib/audit/file-context.js +138 -0
- package/lib/audit/finding.js +50 -0
- package/lib/audit/gitignore-match.js +113 -0
- package/lib/audit/glob.js +63 -0
- package/lib/audit/history-report.js +100 -0
- package/lib/audit/history.js +126 -0
- package/lib/audit/ignore-blind.js +101 -0
- package/lib/audit/index.js +33 -0
- package/lib/audit/orchestrate.js +476 -0
- package/lib/audit/public.js +24 -0
- package/lib/audit/repo-level.js +30 -0
- package/lib/audit/report-yaml.js +86 -0
- package/lib/audit/slot.js +65 -0
- package/lib/audit-defaults.js +18 -0
- package/lib/audit-rules/audit-rules-comment.yml +247 -0
- package/lib/audit-rules/audit-rules-cpp.yml +22 -0
- package/lib/audit-rules/audit-rules-docs.yml +32 -0
- package/lib/audit-rules/audit-rules-dsh.yml +162 -0
- package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
- package/lib/audit-rules/audit-rules-folder.yml +99 -0
- package/lib/audit-rules/audit-rules-frontend.yml +335 -0
- package/lib/audit-rules/audit-rules-go.yml +22 -0
- package/lib/audit-rules/audit-rules-i18n.yml +45 -0
- package/lib/audit-rules/audit-rules-java.yml +105 -0
- package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
- package/lib/audit-rules/audit-rules-npm.yml +187 -0
- package/lib/audit-rules/audit-rules-paths.yml +92 -0
- package/lib/audit-rules/audit-rules-performance.yml +207 -0
- package/lib/audit-rules/audit-rules-php.yml +22 -0
- package/lib/audit-rules/audit-rules-private.yml +24 -0
- package/lib/audit-rules/audit-rules-python.yml +106 -0
- package/lib/audit-rules/audit-rules-robustness.yml +27 -0
- package/lib/audit-rules/audit-rules-rust.yml +22 -0
- package/lib/audit-rules/audit-rules-structure.yml +159 -0
- package/lib/audit-rules/audit-rules-swift.yml +22 -0
- package/lib/audit-rules/audit-rules-template.yml +108 -0
- package/lib/checks/button-bind.js +276 -0
- package/lib/checks/common.js +170 -0
- package/lib/checks/credential-file.js +43 -0
- package/lib/checks/dataflow.js +40 -0
- package/lib/checks/dispatch.js +112 -0
- package/lib/checks/dup-code.js +69 -0
- package/lib/checks/dup-const.js +232 -0
- package/lib/checks/file-health.js +150 -0
- package/lib/checks/filter.js +131 -0
- package/lib/checks/folder.js +173 -0
- package/lib/checks/hardcoded-path.js +98 -0
- package/lib/checks/index.js +46 -0
- package/lib/checks/io.js +66 -0
- package/lib/checks/magic-number.js +42 -0
- package/lib/checks/npm-json.js +273 -0
- package/lib/checks/private.js +63 -0
- package/lib/checks/regex.js +256 -0
- package/lib/checks/semantic.js +134 -0
- package/lib/checks/structural.js +274 -0
- package/lib/cli/commands-account.mjs +107 -0
- package/lib/cli/commands-audit.mjs +144 -0
- package/lib/cli/commands-doc.mjs +127 -0
- package/lib/cli/commands-vcs.mjs +175 -0
- package/lib/client/index.js +162 -0
- package/lib/client-parts/00-loader.js +33 -0
- package/lib/client-parts/01-const.js +207 -0
- package/lib/client-parts/02-utils.js +62 -0
- package/lib/client-parts/03-icons.js +12 -0
- package/lib/client-parts/10-account.js +83 -0
- package/lib/client-parts/11-browser.js +95 -0
- package/lib/client-parts/20-repo.js +374 -0
- package/lib/client-parts/21-audit.js +301 -0
- package/lib/client-parts/22-settings.js +146 -0
- package/lib/client-parts/23-npm.js +383 -0
- package/lib/client-parts/30-page.js +56 -0
- package/lib/client-parts/40-controller.js +1092 -0
- package/lib/client-parts/41-actions.js +279 -0
- package/lib/client-parts/99-apply.js +72 -0
- package/lib/client.js +3195 -0
- package/lib/commit-push.js +144 -0
- package/lib/context/index.js +363 -0
- package/lib/core/atomic-json.js +98 -0
- package/lib/core/config.js +40 -0
- package/lib/core/credentials.js +274 -0
- package/lib/core/endpoints.js +109 -0
- package/lib/core/exec.js +162 -0
- package/lib/exempt/index.js +292 -0
- package/lib/fs/edit-after-read.js +103 -0
- package/lib/fsx.js +87 -0
- package/lib/git/account-status.js +140 -0
- package/lib/git/account.js +233 -0
- package/lib/git/api.js +136 -0
- package/lib/git/atomic-json.js +6 -0
- package/lib/git/browse.js +38 -0
- package/lib/git/clone-download.js +397 -0
- package/lib/git/clone-history-mode.js +143 -0
- package/lib/git/clone-history.js +175 -0
- package/lib/git/clone-jobs.js +250 -0
- package/lib/git/clone-replay-io.js +172 -0
- package/lib/git/clone-replay.js +275 -0
- package/lib/git/clone.js +445 -0
- package/lib/git/cloud.js +46 -0
- package/lib/git/commit-message.js +141 -0
- package/lib/git/config.js +6 -0
- package/lib/git/cred-env.js +88 -0
- package/lib/git/credentials.js +6 -0
- package/lib/git/endpoints.js +6 -0
- package/lib/git/exec.js +6 -0
- package/lib/git/identity-rewrite.js +297 -0
- package/lib/git/identity.js +150 -0
- package/lib/git/ignore.js +69 -0
- package/lib/git/index.js +41 -0
- package/lib/git/module-splitter.js +47 -0
- package/lib/git/post-push.js +101 -0
- package/lib/git/push-diagnose.js +142 -0
- package/lib/git/push.js +470 -0
- package/lib/git/remote-resolve.js +146 -0
- package/lib/git/remote.js +128 -0
- package/lib/git/repo-index.js +512 -0
- package/lib/git/repos.js +235 -0
- package/lib/git/scan-runner.js +159 -0
- package/lib/git/sensitive.js +134 -0
- package/lib/git/transport.js +430 -0
- package/lib/git/visibility.js +35 -0
- package/lib/git/wrapped-git.js +68 -0
- package/lib/http/index.js +170 -0
- package/lib/index.js +24 -0
- package/lib/link-check/index.js +187 -0
- package/lib/npm/account.js +64 -0
- package/lib/npm/install.js +211 -0
- package/lib/npm/npmrc.js +56 -0
- package/lib/npm/publish.js +167 -0
- package/lib/npm/registry.js +147 -0
- package/lib/plugin/auto-detect.js +92 -0
- package/lib/plugin/auto-push.js +154 -0
- package/lib/plugin/index.js +250 -0
- package/lib/readme-templates/readme.yml +38 -0
- package/lib/rule/compilers/credential.js +62 -0
- package/lib/rule/compilers/dataflow.js +38 -0
- package/lib/rule/compilers/file-health.js +75 -0
- package/lib/rule/compilers/frontend.js +86 -0
- package/lib/rule/compilers/func.js +35 -0
- package/lib/rule/compilers/helpers.js +71 -0
- package/lib/rule/compilers/index.js +29 -0
- package/lib/rule/compilers/link-semantic.js +45 -0
- package/lib/rule/compilers/list-kinds.js +12 -0
- package/lib/rule/compilers/numeric-kinds.js +66 -0
- package/lib/rule/compilers/regex.js +78 -0
- package/lib/rule/compilers/structure.js +80 -0
- package/lib/rule/compilers.js +17 -0
- package/lib/rule/homoglyph.js +45 -0
- package/lib/rule/loader.js +270 -0
- package/lib/rule/registry.js +115 -0
- package/lib/rule/scope.js +67 -0
- package/lib/score/docs-score.js +166 -0
- package/lib/score/index.js +140 -0
- package/lib/self/index.js +193 -0
- package/lib/skip-dirs.js +64 -0
- package/lib/tool-probes.json +50 -0
- package/lib/user-requirements.json +14 -0
- package/lib/vendor/js-yaml/LICENSE +21 -0
- package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
- package/package.json +95 -4
- package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
- package/scripts/audit-ext/_example-readme-present.mjs +34 -0
- package/scripts/audit-ext/variable-min-length.mjs +102 -0
- package/scripts/audit-runner.mjs +35 -0
- package/scripts/audit-runtime-check.mjs +129 -0
- package/scripts/browser-page-probe.mjs +271 -0
- package/scripts/build-client.mjs +119 -0
- package/scripts/check.mjs +88 -0
- package/scripts/clean-date-comments.py +102 -0
- package/scripts/doc-drift.mjs +200 -0
- package/scripts/doc-func.mjs +212 -0
- package/scripts/doc-tree.mjs +456 -0
- package/scripts/doc-version.mjs +220 -0
- package/scripts/frontend-preview-check.mjs +124 -0
- package/scripts/hot-path-probe-cjs.cjs +71 -0
- package/scripts/hot-path-probe-fs-shim.mjs +28 -0
- package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
- package/scripts/hot-path-probe.mjs +153 -0
- package/scripts/module-splitter.py +800 -0
- package/scripts/platform-scan.mjs +168 -0
- package/scripts/preview-gen.mjs +489 -0
- package/scripts/preview-local-runner.mjs +55 -0
- package/scripts/preview-server-direct.mjs +116 -0
- package/scripts/preview-server.mjs +305 -0
- package/scripts/preview-slot-data.mjs +123 -0
- package/scripts/probe-recheck.mjs +47 -0
- package/scripts/readme-gen.mjs +268 -0
- package/scripts/rename-locator.mjs +97 -0
- package/scripts/rule-switch.mjs +97 -0
- package/scripts/rules-solo-audit.mjs +173 -0
- package/scripts/scan-file-io.mjs +713 -0
- package/scripts/scan-hardcoded-paths.mjs +125 -0
- package/scripts/scan-repos.mjs +167 -0
- package/scripts/scan-version.mjs +122 -0
- package/scripts/scrub-user-wording.mjs +420 -0
- package/scripts/symbol-index.mjs +85 -0
- package/scripts/sync-plugin-install.mjs +223 -0
- package/scripts/sync-plugin.mjs +279 -0
- package/scripts/verify-prestep.mjs +100 -0
- package/skills/dev/audit-rule-authoring.md +58 -0
- package/skills/dev/dsh-git-push.md +323 -0
- package/skills/dev/git-push-live-fix.md +45 -0
- package/skills/dsh-repo-index.md +35 -0
- package/skills/guide/guide-audit.md +167 -0
- package/skills/guide/guide-cli-scripts.md +104 -0
- package/skills/guide/guide-clone-repos.md +173 -0
- package/skills/guide/guide-commit-push.md +156 -0
- package/skills/guide/guide-inject-ui.md +166 -0
- package/skills/guide/guide-slash-completion.md +118 -0
- package/skills/workflow/README.md +21 -0
- package/skills/workflow/git-commit-discipline.md +68 -0
- package/skills/workflow/git-project-startup.md +85 -0
- package/skills/workflow/git-rebuild-process.md +57 -0
- package/skills/workflow/github-operations.md +91 -0
- package/skills/workflow/readme-sync-git-md.md +28 -0
- package/skills/workflow/task-completion-report.md +73 -0
- package/skills/workflow/tool-json-add-ask.md +35 -0
- package/skills/workflow/versioning-rule.md +211 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git-push — 审计提交总入口(commitWithAudit)
|
|
3
|
+
* dsh-skip-i18n: 插件为中文零依赖,用户可见文案硬编码为产品设计
|
|
4
|
+
*
|
|
5
|
+
* git_commit_push 工具的核心逻辑抽成独立函数:
|
|
6
|
+
* - 供 lib/index.js 的 callTool('git_commit_push') 复用(单一实现)
|
|
7
|
+
* - 供外部插件(dsh-session-conductor 自动推送)动态 import 调用——
|
|
8
|
+
* 自动推送带审计门禁(blocker 拦截 + 敏感扫描 + .gitignore),不再裸 commit+push
|
|
9
|
+
* 返回结构含 audit 摘要,调用方(工具/外部插件)可据此判断「被阻断」。
|
|
10
|
+
*/
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { buildAuditApiGuide } from './app/inject-text.js';
|
|
13
|
+
import { existsSync } from 'node:fs';
|
|
14
|
+
|
|
15
|
+
import './app/host-doc-checks.js'; // 审计包边界:文档漂移检查器由宿主注入(导入即接线)
|
|
16
|
+
import { auditWithScope } from './audit/index.js';
|
|
17
|
+
import { scoreQuality } from './score/index.js';
|
|
18
|
+
import { commitAndPush } from './git/index.js';
|
|
19
|
+
import { defaultConfig } from './client/index.js';
|
|
20
|
+
import { MAX_MSG_PREVIEW } from './app/constants.js';
|
|
21
|
+
import { isSampleExemptDir } from './exempt/index.js';
|
|
22
|
+
import { resolveRepoVisibility } from './git/index.js';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 同步执行审计门禁(不跑 git)。供 git_commit_push 后台化方案复用:审计同步即时
|
|
26
|
+
* 拦截,通过后再把 commit+push 丢后台。返回 { ok, blocked?, error?, audit }。
|
|
27
|
+
* @param {object} p { repoPath, audit?, rulesetDir?, slots?, cfg?, visibility? }
|
|
28
|
+
* (删除 auditLevel——审计固定完整流程,不留强度参数)
|
|
29
|
+
* visibility:远端可见性(private|public|unknown)——private 时审计只报告不拦截
|
|
30
|
+
* (README「④ 私有库豁免」);缺省按 origin 探测,探测失败按 unknown(保守拦截)。
|
|
31
|
+
* 显式传入可免网络探测(测试/已知场景)。
|
|
32
|
+
*/
|
|
33
|
+
export async function runAudit({ repoPath = '', audit, rulesetDir, slots, cfg: extCfg, visibility: extVisibility } = {}) {
|
|
34
|
+
const cfg = extCfg || defaultConfig();
|
|
35
|
+
const doAudit = audit ?? cfg.auditEnabled;
|
|
36
|
+
if (!doAudit) return { ok: true, audit: null };
|
|
37
|
+
const slotOrder = Array.isArray(slots) && slots.length ? slots
|
|
38
|
+
: Array.isArray(cfg.auditRuleOrder) && cfg.auditRuleOrder.length ? cfg.auditRuleOrder
|
|
39
|
+
: undefined;
|
|
40
|
+
const auditRes = await auditWithScope(repoPath || '.', {
|
|
41
|
+
scope: cfg.auditScanScope || 'diff',
|
|
42
|
+
maxScanFiles: cfg.maxScanFiles,
|
|
43
|
+
rulesetDir: rulesetDir || '', // 自定规则目录已从设置移除,只认显式传参(工具 ruleset 参数)
|
|
44
|
+
slots: slotOrder,
|
|
45
|
+
disabledSlots: Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [],
|
|
46
|
+
});
|
|
47
|
+
// 修复:提交前审计同样消费侧边栏权重覆盖(cfg.weightOverrides,config.json 回读),
|
|
48
|
+
// 与 code_audit 工具同源——此前传空权重,评分恒用默认权重表(侧边栏权重设置对提交审计无效)。
|
|
49
|
+
let auditWeights = {};
|
|
50
|
+
if (typeof cfg.weightOverrides === 'string' && cfg.weightOverrides.trim()) {
|
|
51
|
+
try { auditWeights = JSON.parse(cfg.weightOverrides) || {}; } catch { /* 非法 JSON 回退默认 */ }
|
|
52
|
+
}
|
|
53
|
+
const auditOut = { summary: auditRes.summary, quality: scoreQuality(auditRes.findings, auditWeights, { files: auditRes.files }) };
|
|
54
|
+
// 审计输出改为「级别数量 + 评分 + API 查询用法」——审计明细由聚合 API
|
|
55
|
+
// (/api/git-push/audit)查询,不再内联 findings 全文;blocked 摘要保留(拦截必需)。
|
|
56
|
+
auditOut.apiGuide = buildAuditApiGuide(repoPath, { scope: auditRes.scope, summary: auditRes.summary, quality: auditOut.quality });
|
|
57
|
+
// 只算非示例目录的 blocker(示例目录内的 blocker 是规则演示,不拦真实提交)
|
|
58
|
+
const blocked = auditRes.findings.filter((f) => f.severity === 'blocker' && !isSampleExemptDir(repoPath || '.', f.file));
|
|
59
|
+
auditOut.blocked = blocked.map((f) => ({ file: f.file, line: f.line, rule: f.rule, message: (f.message || '').slice(0, MAX_MSG_PREVIEW) }));
|
|
60
|
+
if (blocked.length > 0) {
|
|
61
|
+
// 【修复】私有库豁免(README「④ 私有库豁免」):远端可见性 = private → 审计只报告不拦截。
|
|
62
|
+
// 修复背景:私有库被拦的回归——
|
|
63
|
+
// 此前拦截判定只看「示例目录」、没有可见性分级,
|
|
64
|
+
// comment / docs / security 等槽位规则不受 private 槽位(凭据 glob)约束,私有留痕仓库被拦。
|
|
65
|
+
// 承诺原文:「私密文件与工作留痕(会话记录/凭据/留痕)在私有仓库可正常提交推送,
|
|
66
|
+
// 不需要额外豁免标记」。此前拦截判定只看「示例目录」、没有任何可见性分级,而
|
|
67
|
+
// conv-*/docs/security 等槽位规则不受 private 槽位(凭据 glob)的可见性分级约束 →
|
|
68
|
+
// 私有留痕仓库被上百条 conv-* blocker 拦下(实测回归:ai-work-archive 192 条)。
|
|
69
|
+
// visibility 可由调用方注入(p.visibility,测试/已知场景免探测);缺省按 origin 探测。
|
|
70
|
+
// 探测失败 / 非 private 一律保守拦截——公开库与不可判定场景不放松红线。
|
|
71
|
+
let visibility = extVisibility;
|
|
72
|
+
if (visibility === undefined) {
|
|
73
|
+
// 统一收口(lib/git/visibility.js,与 push.js 同一入口):token 缺失 / 非 GitHub origin /
|
|
74
|
+
// 探测失败 → unknown → 保守拦截(不放松公开库红线)。
|
|
75
|
+
visibility = (await resolveRepoVisibility(repoPath)).visibility;
|
|
76
|
+
}
|
|
77
|
+
if (visibility === 'private') {
|
|
78
|
+
auditOut.privateExempt = {
|
|
79
|
+
visibility,
|
|
80
|
+
blockedCount: blocked.length,
|
|
81
|
+
note: 'private-repo-report-only(私有库豁免:审计只报告不拦截,明细仍见 blocked)',
|
|
82
|
+
};
|
|
83
|
+
return { ok: true, audit: auditOut };
|
|
84
|
+
}
|
|
85
|
+
const list = blocked.map((f) => {
|
|
86
|
+
const where = f.file ? ` ${f.file}` + (f.line ? `:${f.line}` : '') : '';
|
|
87
|
+
const why = f.rule || f.message || '';
|
|
88
|
+
return where + (why ? `(${why})` : '');
|
|
89
|
+
});
|
|
90
|
+
return {
|
|
91
|
+
ok: false,
|
|
92
|
+
blocked: true,
|
|
93
|
+
error: `审计拦截:${blocked.length} 个 blocker → ${list.join(';')}`,
|
|
94
|
+
audit: auditOut,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
return { ok: true, audit: auditOut };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 带审计门禁的提交推送(git_commit_push 工具旧同步实现,仍保留供外部插件/批量复用)。
|
|
102
|
+
* @param {object} p
|
|
103
|
+
* { repoPath, message, push?, dryRun?, audit?, rulesetDir? }
|
|
104
|
+
* audit 缺省取插件配置 auditEnabled;rulesetDir 只认显式传参(设置项已移除)。
|
|
105
|
+
* @returns {Promise<object>} 审计放行 → commitAndPush 结果(含 audit 摘要);
|
|
106
|
+
* blocker 命中 → { ok:false, blocked:true, audit },不执行 git 操作
|
|
107
|
+
*/
|
|
108
|
+
export async function commitWithAudit({
|
|
109
|
+
repoPath = '',
|
|
110
|
+
message = '',
|
|
111
|
+
push = true,
|
|
112
|
+
dryRun = false,
|
|
113
|
+
audit,
|
|
114
|
+
rulesetDir,
|
|
115
|
+
slots,
|
|
116
|
+
customIgnorePatterns = '',
|
|
117
|
+
requirementsConfirmed = false,
|
|
118
|
+
force = false,
|
|
119
|
+
pushMethod,
|
|
120
|
+
pushGate = false,
|
|
121
|
+
pushConfirmed = false,
|
|
122
|
+
paths = '', // 精确 add 路径(逗号分隔,相对 repoPath);空 = git add -A
|
|
123
|
+
} = {}) {
|
|
124
|
+
const cfg = defaultConfig();
|
|
125
|
+
const a = await runAudit({ repoPath, audit, rulesetDir, slots });
|
|
126
|
+
if (!a.ok) return { ok: false, blocked: true, error: a.error, audit: a.audit };
|
|
127
|
+
// 推送通道缺省取插件配置(默认 ssh:推本地 HEAD、远端 sha 与本地一致)
|
|
128
|
+
const r = await commitAndPush({ repoPath, message, push, dryRun, customIgnorePatterns, requirementsConfirmed, force, pushMethod: pushMethod || cfg.pushMethod || 'ssh', pushGate, pushConfirmed, paths });
|
|
129
|
+
return { ok: r.ok !== false, ...r, audit: a.audit };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 批量提交推送(D16 commitMany):对每个仓库依次 commitAndPush,返回逐仓结果数组。
|
|
134
|
+
* 注意:仅做提交推送(不含审计门禁)——审计请用 commitWithAudit 逐仓调用。
|
|
135
|
+
* @param {{repos: string[], message: string, push?: boolean, dryRun?: boolean, requirementsConfirmed?: boolean, customIgnorePatterns?: string}} opts
|
|
136
|
+
* @returns {Promise<Array<{repo: string, ...commitAndPush 结果}>>}
|
|
137
|
+
*/
|
|
138
|
+
export async function commitMany({ repos = [], message = '', push = true, dryRun = false, requirementsConfirmed = false, customIgnorePatterns = '' } = {}) {
|
|
139
|
+
const results = [];
|
|
140
|
+
for (const repoPath of repos) {
|
|
141
|
+
results.push({ repo: repoPath, ...(await commitAndPush({ repoPath, message, push, dryRun, customIgnorePatterns, requirementsConfirmed })) });
|
|
142
|
+
}
|
|
143
|
+
return results;
|
|
144
|
+
}
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git-push 上下文注入入口
|
|
3
|
+
* 给 AI 会话注入环境:工作目录映射 / 工具安装路径 / skill 总入口。
|
|
4
|
+
*
|
|
5
|
+
* 注入范围收敛为目录级(工具目录 / 工作区目录 / skill 总入口)。
|
|
6
|
+
* 工具清单 json 化(路径不再写死):
|
|
7
|
+
* - 模板:lib/tool-probes.json(**只有工具 key、值为空**,随仓库提交,决定探测哪些工具)
|
|
8
|
+
* - 探测:which/where 实测(同 v1 collectToolPaths 语义),结果落盘运行目录
|
|
9
|
+
* <配置目录>/tools.json(工具为 key、**值为本机实测路径**,不入库、可热改)
|
|
10
|
+
* - 注入:上下文(agent/pre-step,见 lib/app/apply.js)按运行目录 json 注入,模板只控探测范围
|
|
11
|
+
*/
|
|
12
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
13
|
+
import { dirname, join, resolve } from 'node:path';
|
|
14
|
+
import { spawnSync } from 'node:child_process';
|
|
15
|
+
import { hostname as osHostname, networkInterfaces } from 'node:os';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
17
|
+
import { writeJsonAtomic } from '../git/atomic-json.js';
|
|
18
|
+
|
|
19
|
+
/* ───────── 工具探测常量 ───────── */
|
|
20
|
+
const PROBE_TIMEOUT_MS = 8000; // 工具路径/版本探测子进程超时
|
|
21
|
+
const VERSION_MAX_LEN = 120; // 版本串截断长度
|
|
22
|
+
|
|
23
|
+
/** 默认工具清单(探测失败时的静态兜底;探测成功以实测路径为准)。 */
|
|
24
|
+
export const DEFAULT_TOOLS = {
|
|
25
|
+
git: '/usr/bin/git',
|
|
26
|
+
node: '/usr/bin/node',
|
|
27
|
+
npm: '/usr/bin/npm',
|
|
28
|
+
python3: '/usr/bin/python3',
|
|
29
|
+
curl: '/usr/bin/curl',
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** 默认探测的工具清单(名称 → 版本参数;null 表示只查路径)。 */
|
|
33
|
+
export const DEFAULT_TOOL_PROBES = [
|
|
34
|
+
{ name: 'git', versionArgs: ['--version'] },
|
|
35
|
+
{ name: 'node', versionArgs: ['--version'] },
|
|
36
|
+
{ name: 'npm', versionArgs: ['--version'] },
|
|
37
|
+
{ name: 'python3', versionArgs: ['--version'] },
|
|
38
|
+
{ name: 'curl', versionArgs: ['--version'] },
|
|
39
|
+
{ name: 'ssh', versionArgs: ['-V'] },
|
|
40
|
+
{ name: 'unzip', versionArgs: ['-version'] },
|
|
41
|
+
{ name: 'rsync', versionArgs: ['--version'] },
|
|
42
|
+
{ name: '7z', versionArgs: ['-version'] },
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
/** 内置工具版本参数(json 模板只列工具名;版本参数保持代码内默认,探测时用)。 */
|
|
46
|
+
export const TOOL_VERSION_ARGS = {
|
|
47
|
+
git: ['--version'],
|
|
48
|
+
node: ['--version'],
|
|
49
|
+
npm: ['--version'],
|
|
50
|
+
python3: ['--version'],
|
|
51
|
+
curl: ['--version'],
|
|
52
|
+
ssh: ['-V'],
|
|
53
|
+
unzip: ['-version'],
|
|
54
|
+
rsync: ['--version'],
|
|
55
|
+
'7z': ['-version'],
|
|
56
|
+
tar: ['--version'],
|
|
57
|
+
gzip: ['--version'],
|
|
58
|
+
bzip2: ['--version'],
|
|
59
|
+
xz: ['--version'],
|
|
60
|
+
zstd: ['--version'],
|
|
61
|
+
lz4: ['--version'],
|
|
62
|
+
zip: ['--version'],
|
|
63
|
+
rar: [],
|
|
64
|
+
unrar: [],
|
|
65
|
+
synopkg: [],
|
|
66
|
+
synouser: [],
|
|
67
|
+
synogroup: [],
|
|
68
|
+
synoshare: [],
|
|
69
|
+
synoacltool: [],
|
|
70
|
+
smartctl: ['--version'],
|
|
71
|
+
mdadm: ['--version'],
|
|
72
|
+
btrfs: ['--version'],
|
|
73
|
+
lvm: ['version'],
|
|
74
|
+
fnpack: ['--version'],
|
|
75
|
+
'appcenter-cli': ['--version'],
|
|
76
|
+
docker: ['--version'],
|
|
77
|
+
ffmpeg: ['-version'],
|
|
78
|
+
pnpm: ['--version'],
|
|
79
|
+
bash: ['--version'],
|
|
80
|
+
wget: ['--version'],
|
|
81
|
+
jq: ['--version'],
|
|
82
|
+
yq: ['--version'],
|
|
83
|
+
rg: ['--version'],
|
|
84
|
+
fd: ['--version'],
|
|
85
|
+
scp: [],
|
|
86
|
+
tmux: ['-V'],
|
|
87
|
+
screen: ['--version'],
|
|
88
|
+
gcc: ['--version'],
|
|
89
|
+
'g++': ['--version'],
|
|
90
|
+
make: ['--version'],
|
|
91
|
+
'pkg-config': ['--version'],
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** 工具清单模板 json 位置(lib/tool-probes.json,随插件仓库提交)。 */
|
|
95
|
+
const TEMPLATE_FILE = fileURLToPath(new URL('../tool-probes.json', import.meta.url));
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 读取工具清单模板 json:工具为 key、值为空(模板只定探测范围,不写死路径)。
|
|
99
|
+
* 返回 [{name, path:'', versionArgs}];文件缺失 / 坏 JSON / 空 → 回退内置 DEFAULT_TOOL_PROBES。
|
|
100
|
+
* @param {string} [file] 模板路径(缺省 lib/tool-probes.json)
|
|
101
|
+
*/
|
|
102
|
+
export function loadToolProbeTemplate(file = TEMPLATE_FILE) {
|
|
103
|
+
try {
|
|
104
|
+
if (file && existsSync(file)) {
|
|
105
|
+
const probeMap = JSON.parse(String(readFileSync(file, 'utf8')));
|
|
106
|
+
if (probeMap && typeof probeMap === 'object' && !Array.isArray(probeMap)) {
|
|
107
|
+
const out = [];
|
|
108
|
+
for (const [name, probePath] of Object.entries(probeMap)) {
|
|
109
|
+
const n = String(name || '').trim();
|
|
110
|
+
if (!n) continue;
|
|
111
|
+
// Windows 工具可能是 .exe(如 7z.exe):去掉后缀查版本参数表,探测时自动补 .exe
|
|
112
|
+
const bare = n.replace(/\.exe$/i, '');
|
|
113
|
+
out.push({ name: n, path: typeof probePath === 'string' ? probePath.trim() : '', versionArgs: TOOL_VERSION_ARGS[bare] || [] });
|
|
114
|
+
}
|
|
115
|
+
if (out.length) return out;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
} catch { /* 模板坏/不可读 → 回退内置清单 */ }
|
|
119
|
+
return DEFAULT_TOOL_PROBES.map((p) => ({ ...p, path: '' }));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 探测单个工具的安装路径(command -v 语义;Windows 走 where)。
|
|
124
|
+
* 纯只读 + 短超时,失败返回 found:false 不抛错。
|
|
125
|
+
* Windows 兼容:工具可能是 .exe——where 找不到裸名时自动补 `${name}.exe`
|
|
126
|
+
* 再试(如 git.exe / 7z.exe),命中后路径原样带 .exe 后缀返回。
|
|
127
|
+
* @param {string} name 工具名
|
|
128
|
+
* @param {string[]} [versionArgs] 版本参数
|
|
129
|
+
* @returns {{name:string, path:string, version:string, found:boolean}}
|
|
130
|
+
*/
|
|
131
|
+
export function probeToolPath(name, versionArgs = []) {
|
|
132
|
+
const bare = String(name || '').replace(/\.exe$/i, '');
|
|
133
|
+
const finder = process.platform === 'win32' ? 'where' : 'which';
|
|
134
|
+
const candidates = process.platform === 'win32'
|
|
135
|
+
? [name, /\.exe$/i.test(name) ? '' : `${name}.exe`].filter(Boolean)
|
|
136
|
+
: [name];
|
|
137
|
+
let path = '';
|
|
138
|
+
for (const cand of candidates) {
|
|
139
|
+
let r;
|
|
140
|
+
try {
|
|
141
|
+
r = spawnSync(finder, [cand], { encoding: 'utf8', timeout: PROBE_TIMEOUT_MS, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
142
|
+
} catch { continue; }
|
|
143
|
+
path = String(r.stdout || '').split(/\r?\n/).map((x) => x.trim()).find(Boolean) || '';
|
|
144
|
+
if (path) break;
|
|
145
|
+
}
|
|
146
|
+
// node 的 which 兜底——DSH 宿主跑在自带 node,PATH 里没有 node 时
|
|
147
|
+
// which 找不到,回退 process.execPath(运行本插件的 node 绝对路径),确保 node 被探测到。
|
|
148
|
+
if (!path && bare === 'node') {
|
|
149
|
+
try { path = process.execPath || ''; } catch { path = ''; }
|
|
150
|
+
}
|
|
151
|
+
if (!path) return { name, path: '', version: '', found: false };
|
|
152
|
+
let version = '';
|
|
153
|
+
if (versionArgs.length) {
|
|
154
|
+
try {
|
|
155
|
+
const v = spawnSync(path, versionArgs, { encoding: 'utf8', timeout: PROBE_TIMEOUT_MS, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
156
|
+
const out = `${(v.stdout || '').trim()} ${(v.stderr || '').trim()}`.trim();
|
|
157
|
+
const first = out.split(/\r?\n/)[0] || '';
|
|
158
|
+
version = first.length > VERSION_MAX_LEN ? first.slice(0, VERSION_MAX_LEN) : first;
|
|
159
|
+
} catch { /* 版本读不到不影响路径注入 */ }
|
|
160
|
+
}
|
|
161
|
+
return { name, path, version, found: true };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* 批量探测工具安装路径。
|
|
166
|
+
* @param {Array<{name:string, versionArgs?:string[]}>} [probes] 显式探测清单(缺省读模板 json)
|
|
167
|
+
* @param {{templateFile?:string, resultFile?:string}} [opts]
|
|
168
|
+
* templateFile:模板 json 路径(缺省 lib/tool-probes.json;仅当 probes 未传时生效)
|
|
169
|
+
* resultFile:探测结果落盘 json(工具为 key、值为实测路径;只写探测到的;空=不落盘)
|
|
170
|
+
* @returns {Array<object>}
|
|
171
|
+
*/
|
|
172
|
+
export function collectToolPaths(probes = null, { templateFile = TEMPLATE_FILE, resultFile = '' } = {}) {
|
|
173
|
+
const list = probes || loadToolProbeTemplate(templateFile);
|
|
174
|
+
const seen = new Set();
|
|
175
|
+
const out = [];
|
|
176
|
+
for (const p of list) {
|
|
177
|
+
if (!p || !p.name || seen.has(p.name)) continue;
|
|
178
|
+
seen.add(p.name);
|
|
179
|
+
out.push(probeToolPath(p.name, p.versionArgs || []));
|
|
180
|
+
}
|
|
181
|
+
if (resultFile) {
|
|
182
|
+
const writeResult = writeToolResult(resultFile, out);
|
|
183
|
+
if (!writeResult.ok) { /* 落盘失败不阻断注入(需要排查时由调用方日志兜底) */ }
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 把探测结果写成 {工具名: 实际路径} 的 json(运行目录 tools.json;原子写,只写探测到的)。
|
|
190
|
+
* @param {string} file 目标绝对路径
|
|
191
|
+
* @param {Array<object>} results collectToolPaths() 探测结果数组
|
|
192
|
+
* @returns {{ok:boolean, file:string, error?:string, tools:number}}
|
|
193
|
+
*/
|
|
194
|
+
export function writeToolResult(file = '', results = []) {
|
|
195
|
+
const map = {};
|
|
196
|
+
for (const r of results) {
|
|
197
|
+
if (r && r.found && r.path && r.name) map[r.name] = r.path;
|
|
198
|
+
}
|
|
199
|
+
const writeResult = writeJsonAtomic(file, map, { mode: 0o600 });
|
|
200
|
+
return { ...writeResult, tools: Object.keys(map).length };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* 映射工作区目录:cwd、项目实际目录(git 根)、父级链、直接子目录。
|
|
205
|
+
* @param {{workspaceRoot?:string, cwd?:string, maxChildren?:number}} opts
|
|
206
|
+
* @returns {{cwd:string, projectDir:string, parents:string[], children:string[], workspaceRoot:string}}
|
|
207
|
+
*/
|
|
208
|
+
export function mapWorkspaceDirs({ workspaceRoot = '', cwd = process.cwd(), maxChildren = 40 } = {}) {
|
|
209
|
+
const cur = resolve(cwd);
|
|
210
|
+
const root = workspaceRoot ? resolve(workspaceRoot) : cur;
|
|
211
|
+
let projectDir = root;
|
|
212
|
+
try {
|
|
213
|
+
const gitProbe = spawnSync('git', ['rev-parse', '--show-toplevel'], {
|
|
214
|
+
cwd: cur, encoding: 'utf8', timeout: PROBE_TIMEOUT_MS, stdio: ['pipe', 'pipe', 'ignore'],
|
|
215
|
+
});
|
|
216
|
+
const top = String(gitProbe.stdout || '').trim();
|
|
217
|
+
if (gitProbe.status === 0 && top) projectDir = resolve(top);
|
|
218
|
+
} catch { /* 非 git 目录:回退 workspaceRoot */ }
|
|
219
|
+
const parents = [];
|
|
220
|
+
let p = cur;
|
|
221
|
+
for (let i = 0; i < 32 && p && p !== dirname(p); i++) {
|
|
222
|
+
parents.push(p);
|
|
223
|
+
p = dirname(p);
|
|
224
|
+
}
|
|
225
|
+
if (p) parents.push(p);
|
|
226
|
+
const children = [];
|
|
227
|
+
try {
|
|
228
|
+
if (statSync(projectDir).isDirectory()) {
|
|
229
|
+
for (const ent of readdirSync(projectDir, { withFileTypes: true })) {
|
|
230
|
+
if (children.length >= maxChildren) break;
|
|
231
|
+
if (!ent.isDirectory()) continue;
|
|
232
|
+
if (ent.name.startsWith('.') || ent.name === 'node_modules' || ent.name === 'dist' || ent.name === 'build') continue;
|
|
233
|
+
children.push(ent.name);
|
|
234
|
+
}
|
|
235
|
+
children.sort();
|
|
236
|
+
}
|
|
237
|
+
} catch { /* 目录不可读 */ }
|
|
238
|
+
return { cwd: cur, projectDir, parents, children, workspaceRoot: root };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* 生成 AI 环境注入文本(注入上下文 agent/pre-step;必须同步返回)。
|
|
243
|
+
*
|
|
244
|
+
* 起走上下文注入(不再进 systemPrompt section):每次会话每个 agent
|
|
245
|
+
* 首次 step 注入一次(见 lib/app/apply.js 的 registerPreStepInjection 接线)。
|
|
246
|
+
*
|
|
247
|
+
* 注入内容(只到目录级:工具目录 + 工作区目录 + skill 总入口):
|
|
248
|
+
* ① 当前工作目录 / 项目实际目录 / skills **总入口**(只给目录路径,不注正文、不列文件清单)
|
|
249
|
+
* ② 工作区根 + 直接子目录(便于直接定位项目)
|
|
250
|
+
* ③ 工具安装路径(探测结果,格式 name=path / …)
|
|
251
|
+
*
|
|
252
|
+
* @param {{cwd?:string, projectRoot?:string, tools?:object|Array, workspace?:object}} opts
|
|
253
|
+
* tools:{name:path} 对象(旧签名兼容)或 collectToolPaths() 数组(推荐,带版本)
|
|
254
|
+
* workspace:mapWorkspaceDirs() 结果(可选,缺失则跳过工作区目录段)
|
|
255
|
+
*/
|
|
256
|
+
/**
|
|
257
|
+
* 探测本机运行主机名 + 局域网 IPv4(过滤 internal/回环/链路本地,多网卡全列)。
|
|
258
|
+
* @returns {{hostname: string, ips: string[]}}
|
|
259
|
+
*/
|
|
260
|
+
export function detectLocalHost() {
|
|
261
|
+
let host = '';
|
|
262
|
+
try { host = osHostname(); } catch { /* 探测失败给空 */ }
|
|
263
|
+
const ips = [];
|
|
264
|
+
try {
|
|
265
|
+
for (const list of Object.values(networkInterfaces() || {})) {
|
|
266
|
+
for (const net of list || []) {
|
|
267
|
+
if (net.family !== 'IPv4' || net.internal) continue;
|
|
268
|
+
const ip = String(net.address || '').trim();
|
|
269
|
+
if (!ip || ip.startsWith('127.') || ip.startsWith('169.254.')) continue;
|
|
270
|
+
if (!ips.includes(ip)) ips.push(ip);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
} catch { /* 探测失败给空 */ }
|
|
274
|
+
return { hostname: host, ips };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export function createEnvInjectionText({ cwd = '', projectRoot = '', tools = DEFAULT_TOOLS, workspace = null, host = null } = {}) {
|
|
278
|
+
const lines = [];
|
|
279
|
+
lines.push('【dsh-git-push 环境注入】');
|
|
280
|
+
lines.push(`- 当前工作目录 cwd:${cwd}`);
|
|
281
|
+
// 运行主机 + 局域网 IP(默认实时探测;测试可注入 host 覆盖)
|
|
282
|
+
const hostCfg = host && typeof host === 'object' ? host : detectLocalHost();
|
|
283
|
+
const hostLine = hostCfg && hostCfg.hostname
|
|
284
|
+
? `- 运行主机:${hostCfg.hostname}` + (Array.isArray(hostCfg.ips) && hostCfg.ips.length ? `(${hostCfg.ips.join(' / ')})` : '')
|
|
285
|
+
: '';
|
|
286
|
+
if (hostLine) lines.push(hostLine);
|
|
287
|
+
if (projectRoot) {
|
|
288
|
+
lines.push(`- 项目实际目录(git 根):${projectRoot}`);
|
|
289
|
+
lines.push(`- skills 目录:${join(projectRoot, 'skills')}(存在:${existsSync(join(projectRoot, 'skills'))})`);
|
|
290
|
+
}
|
|
291
|
+
// 工作区目录映射(工作区根 + 直接子目录)
|
|
292
|
+
if (workspace && typeof workspace === 'object') {
|
|
293
|
+
if (workspace.workspaceRoot) lines.push(`- 工作区根目录:${workspace.workspaceRoot}`);
|
|
294
|
+
if (Array.isArray(workspace.children) && workspace.children.length) {
|
|
295
|
+
lines.push(`- 工作区子目录:${workspace.children.join(' / ')}`);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
// 工具目录:数组(探测结果)或对象(旧签名)
|
|
299
|
+
let toolPairs = [];
|
|
300
|
+
if (Array.isArray(tools)) {
|
|
301
|
+
toolPairs = tools.filter((t) => t && t.found && t.path).map((t) => `${t.name}=${t.path}`);
|
|
302
|
+
} else {
|
|
303
|
+
toolPairs = Object.entries(tools || {}).map(([k, v]) => `${k}=${v}`);
|
|
304
|
+
}
|
|
305
|
+
lines.push(`- 工具:${toolPairs.join(' / ')}`);
|
|
306
|
+
return lines.join('\n');
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* 路径归属判定:确认 `target` 是否位于 `root` 之下(防目录穿越,跨主机定位用)。
|
|
311
|
+
* @param {string} root 根目录绝对路径
|
|
312
|
+
* @param {string} target 待判定路径
|
|
313
|
+
* @returns {boolean} true=属于该根(或等于根)
|
|
314
|
+
*/
|
|
315
|
+
export function isWithinRoot(root = '', target = '') {
|
|
316
|
+
const norm = (p) => {
|
|
317
|
+
const s = String(p ?? '').trim();
|
|
318
|
+
if (!s) return '';
|
|
319
|
+
const stripped = s.replace(/\/+$/, ''); // 去尾斜杠(多重也归一)
|
|
320
|
+
return stripped || '/'; // 根 '/' 去尾斜杠后为空 → 还原为 '/'
|
|
321
|
+
};
|
|
322
|
+
const r = norm(root);
|
|
323
|
+
const t = norm(target);
|
|
324
|
+
if (!r || !t) return false;
|
|
325
|
+
if (r === '/') return t.startsWith('/'); // 根目录包含一切绝对路径
|
|
326
|
+
return t === r || t.startsWith(r + '/');
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 提取注入段落的键值结构(机器可读,供解析测试)。
|
|
331
|
+
* @param {string} text createEnvInjectionText 输出
|
|
332
|
+
* @returns {object} { cwd, projectRoot, skillsDir, tools: {k:v} }
|
|
333
|
+
*/
|
|
334
|
+
export function parseEnvInjection(text = '') {
|
|
335
|
+
// 字段预置为空串:无对应行时回读为 ''(而非 undefined),消费方无需再判空
|
|
336
|
+
const out = { cwd: '', projectRoot: '', skillsDir: '', workspaceRoot: '', children: [], host: { hostname: '', ips: [] }, tools: {} };
|
|
337
|
+
for (const line of String(text).split('\n')) {
|
|
338
|
+
const match = /^\- ([^::]+):(.*)$/.exec(line.trim());
|
|
339
|
+
if (!match) continue;
|
|
340
|
+
const key = match[1].trim();
|
|
341
|
+
const lineValue = match[2].trim();
|
|
342
|
+
if (key === '当前工作目录 cwd') out.cwd = lineValue;
|
|
343
|
+
else if (key.startsWith('运行主机')) {
|
|
344
|
+
// 格式:主机名(ip1 / ip2)——括号段可选
|
|
345
|
+
const paren = /^([^((]*)(?:[((](.*)[))])?$/.exec(lineValue);
|
|
346
|
+
out.host.hostname = (paren ? paren[1] : lineValue).trim();
|
|
347
|
+
if (paren && paren[2]) {
|
|
348
|
+
out.host.ips = paren[2].split(/[/、]/).map((x) => x.trim()).filter(Boolean);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
else if (key.startsWith('项目实际目录')) out.projectRoot = lineValue;
|
|
352
|
+
else if (key.startsWith('skills 目录')) out.skillsDir = lineValue.replace(/(存在:.*)$/, '');
|
|
353
|
+
else if (key.startsWith('工作区根目录')) out.workspaceRoot = lineValue;
|
|
354
|
+
else if (key.startsWith('工作区子目录')) out.children = lineValue.split(' / ').map((x) => x.trim()).filter(Boolean);
|
|
355
|
+
else if (key === '工具') {
|
|
356
|
+
for (const pair of lineValue.split(' / ')) {
|
|
357
|
+
const [k, v] = pair.split('=');
|
|
358
|
+
if (k && v !== undefined) out.tools[k.trim()] = v.trim();
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return out;
|
|
363
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 统一 JSON 文件原子读写(收敛:多处重复的「读 JSON → 改 → 原子写回」抽成一份)。
|
|
3
|
+
*
|
|
4
|
+
* 消费方(原各自实现):settings-bridge(config.json)、account-status(account-status.json)、
|
|
5
|
+
* scan-runner(scan-live.json)、repo-index(dsh-repo-index.json)、credentials 等。
|
|
6
|
+
*
|
|
7
|
+
* 原子写语义:写同目录 `.tmp` 再 rename(同卷原子替换,避免写一半崩溃留坏文件);
|
|
8
|
+
* CIFS 可能改不了 mode,chmod 失败静默(与各原实现一致)。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync, chmodSync, existsSync } from 'node:fs';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 读 JSON 文件:缺失 / 损坏 / 非对象 → null(不抛)。
|
|
16
|
+
* @param {string} file 绝对路径
|
|
17
|
+
* @returns {object|null}
|
|
18
|
+
*/
|
|
19
|
+
export function readJson(file) {
|
|
20
|
+
try {
|
|
21
|
+
if (!file || !existsSync(file)) return null;
|
|
22
|
+
const v = JSON.parse(readFileSync(file, 'utf8'));
|
|
23
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 读任意 JSON 值(数组/标量也允许;缺失/损坏返回 undefined)。
|
|
31
|
+
* @param {string} file 绝对路径
|
|
32
|
+
* @returns {unknown}
|
|
33
|
+
*/
|
|
34
|
+
export function readJsonAny(file) {
|
|
35
|
+
try {
|
|
36
|
+
if (!file || !existsSync(file)) return undefined;
|
|
37
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
38
|
+
} catch {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 原子写 JSON 文件(先 .tmp 后 rename)。
|
|
45
|
+
* @param {string} file 目标绝对路径
|
|
46
|
+
* @param {unknown} data 任意 JSON 可序列化值
|
|
47
|
+
* @param {{mode?:number, pretty?:boolean}} [opts] mode 默认 0o600;pretty 默认 true(2 空格缩进 + 换行)
|
|
48
|
+
* @returns {{ok:boolean, file:string, error?:string}}
|
|
49
|
+
*/
|
|
50
|
+
export function writeJsonAtomic(file, data, { mode = 0o600, pretty = true } = {}) {
|
|
51
|
+
try {
|
|
52
|
+
if (!file) return { ok: false, file: '', error: '路径为空' };
|
|
53
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
|
|
54
|
+
const content = pretty ? JSON.stringify(data, null, 2) + '\n' : JSON.stringify(data);
|
|
55
|
+
const tmpPath = `${file}.${process.pid}.tmp`;
|
|
56
|
+
writeFileSync(tmpPath, content, { encoding: 'utf8', mode });
|
|
57
|
+
try { chmodSync(tmpPath, mode); } catch { /* CIFS 可能改不了 mode,静默 */ }
|
|
58
|
+
renameSync(tmpPath, file);
|
|
59
|
+
return { ok: true, file };
|
|
60
|
+
} catch (e) {
|
|
61
|
+
return { ok: false, file, error: String(e?.message || e) };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 读-改-写一步到位:读取(缺失返回空对象)→ 应用 updater → 原子写回。
|
|
67
|
+
* @param {string} file 目标绝对路径
|
|
68
|
+
* @param {(cur: object) => object} updater 输入当前对象,返回新对象
|
|
69
|
+
* @param {{mode?:number}} [opts]
|
|
70
|
+
* @returns {{ok:boolean, file:string, error?:string}}
|
|
71
|
+
*/
|
|
72
|
+
export function updateJsonAtomic(file, updater, { mode = 0o600 } = {}) {
|
|
73
|
+
const cur = readJson(file) || {};
|
|
74
|
+
const next = updater(cur);
|
|
75
|
+
return writeJsonAtomic(file, next, { mode });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 原子写**已序列化文本**(调用方已生成 JSON 字符串 / 非 JSON 文本),.tmp + rename。
|
|
80
|
+
* 供 syncRepoIndex 等「内容是字符串」的写入收敛用。
|
|
81
|
+
* @param {string} file 目标绝对路径
|
|
82
|
+
* @param {string} text 已序列化内容
|
|
83
|
+
* @param {{mode?:number}} [opts] mode 默认 0o600
|
|
84
|
+
* @returns {{ok:boolean, file:string, error?:string}}
|
|
85
|
+
*/
|
|
86
|
+
export function writeTextAtomic(file, text, { mode = 0o600 } = {}) {
|
|
87
|
+
try {
|
|
88
|
+
if (!file) return { ok: false, file: '', error: '路径为空' };
|
|
89
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
|
|
90
|
+
const tmpPath = `${file}.${process.pid}.tmp`;
|
|
91
|
+
writeFileSync(tmpPath, String(text ?? ''), { encoding: 'utf8', mode });
|
|
92
|
+
try { chmodSync(tmpPath, mode); } catch { /* CIFS 可能改不了 mode,静默 */ }
|
|
93
|
+
renameSync(tmpPath, file);
|
|
94
|
+
return { ok: true, file };
|
|
95
|
+
} catch (e) {
|
|
96
|
+
return { ok: false, file, error: String(e?.message || e) };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git 执行层 · 路径与配置
|
|
3
|
+
*
|
|
4
|
+
* 职责:插件根目录定位(PLUGIN_ROOT)与开发者要求清单读取(loadRequirements)。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { dirname, join } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { credentialsDir } from './credentials.js';
|
|
11
|
+
|
|
12
|
+
/** 插件根(lib/git/index.js → lib → 插件根;requirements.json 内置清单定位用)。 */
|
|
13
|
+
export const PLUGIN_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 开发者特殊要求清单(D13):
|
|
17
|
+
* 三来源依次尝试(首个有效即返回):
|
|
18
|
+
* 1) credentialsDir()/requirements.json(用户外挂)
|
|
19
|
+
* 2) PLUGIN_ROOT/lib/user-requirements.json(内置默认清单)
|
|
20
|
+
* 3) PLUGIN_ROOT/user-requirements.json
|
|
21
|
+
* 返回 { user, found, items, files };无清单时 found:false(门禁放行)。
|
|
22
|
+
*/
|
|
23
|
+
export function loadRequirements() {
|
|
24
|
+
const candidates = [
|
|
25
|
+
join(credentialsDir(), 'requirements.json'),
|
|
26
|
+
join(PLUGIN_ROOT, 'lib', 'user-requirements.json'),
|
|
27
|
+
join(PLUGIN_ROOT, 'user-requirements.json'),
|
|
28
|
+
];
|
|
29
|
+
for (const f of candidates) {
|
|
30
|
+
try {
|
|
31
|
+
if (!f || !existsSync(f)) continue;
|
|
32
|
+
const parsed = JSON.parse(readFileSync(f, 'utf8'));
|
|
33
|
+
const items = Array.isArray(parsed?.items) ? parsed.items.map((x) => String(x).trim()).filter(Boolean) : [];
|
|
34
|
+
if (items.length) {
|
|
35
|
+
return { user: String(parsed.user || '') || '默认开发者', found: true, items, files: [{ file: f, items }] };
|
|
36
|
+
}
|
|
37
|
+
} catch { /* 坏 JSON 换下一来源 */ }
|
|
38
|
+
}
|
|
39
|
+
return { user: '默认开发者', found: false, items: [], files: [] };
|
|
40
|
+
}
|