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,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* git_cred_env —— 凭据传递工具。
|
|
3
|
+
*
|
|
4
|
+
* 目标:插件保管凭据(config.json 的 githubToken + 配置目录 SSH 私钥),把凭据转成
|
|
5
|
+
* 「可直接粘贴的环境变量前缀」供 AI 执行**任意外部 git 命令**时使用,AI 全程不接触明文:
|
|
6
|
+
* · SSH 通道:GIT_SSH_COMMAND 指向插件私钥**路径**(AI 只接触路径,私钥明文不经手)
|
|
7
|
+
* · HTTPS 通道:GIT_ASKPASS 指向生成的 askpass 脚本(脚本从 config.json 读 token 回显;
|
|
8
|
+
* AI 只接触脚本路径,token 明文仅存在于 config.json 与 git 进程内存)
|
|
9
|
+
* 本模块只做凭据传递,不覆盖 git 功能(git 操作仍由 AI 用任意命令执行)。
|
|
10
|
+
* 复用存量:resolveSshKey(私钥解析)/ resolveToken(token 探测)/ credentialsDir(配置目录)。
|
|
11
|
+
*/
|
|
12
|
+
import { chmodSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { credentialsDir, resolveSshKey, resolveToken } from './credentials.js';
|
|
15
|
+
|
|
16
|
+
/** 宿主 node 绝对路径(askpass 脚本自包含,不依赖 PATH)。 */
|
|
17
|
+
const NODE = process.execPath;
|
|
18
|
+
|
|
19
|
+
/** 组装 SSH 通道的 GIT_SSH_COMMAND(插件内部 buildLsRemoteSshCmd 是 ls-remote 专用,
|
|
20
|
+
* 含 ControlMaster/临时 known_hosts,不适合粘贴给外部 git——这里组装简洁可粘贴版本)。 */
|
|
21
|
+
function buildSshEnvPrefix(keyPath) {
|
|
22
|
+
return `GIT_SSH_COMMAND="ssh -i '${keyPath}' -p 443 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5"`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 构建凭据环境变量输出(不输出 token/私钥明文)。
|
|
27
|
+
* @param {{workspaceRoot?: string}} [opts]
|
|
28
|
+
* @returns {{provided: string[], hasSshKey: boolean, hasToken: boolean, ssh: object|null, https: object|null, hint: string}}
|
|
29
|
+
*/
|
|
30
|
+
export function buildCredEnv({ workspaceRoot = '' } = {}) {
|
|
31
|
+
const dir = credentialsDir({ workspaceRoot });
|
|
32
|
+
const sshKey = resolveSshKey({ workspaceRoot });
|
|
33
|
+
// 存量约定:resolveSshKey 无密钥时返回 { keyPath: '', kind: '' } 占位对象(非 null)——
|
|
34
|
+
// 判据用 keyPath 非空,不能 !!obj(占位对象恒真,会把「无私钥」误判成有)
|
|
35
|
+
const hasKey = !!(sshKey && sshKey.keyPath);
|
|
36
|
+
const tok = resolveToken({ workspaceRoot });
|
|
37
|
+
const out = {
|
|
38
|
+
provided: [],
|
|
39
|
+
hasSshKey: hasKey,
|
|
40
|
+
hasToken: !!(tok && tok.token),
|
|
41
|
+
ssh: null,
|
|
42
|
+
https: null,
|
|
43
|
+
hint: '',
|
|
44
|
+
};
|
|
45
|
+
// SSH 通道:传私钥路径(路径非明文)
|
|
46
|
+
if (hasKey) {
|
|
47
|
+
const envPrefix = buildSshEnvPrefix(sshKey.keyPath);
|
|
48
|
+
out.ssh = {
|
|
49
|
+
channel: 'ssh',
|
|
50
|
+
keyPath: sshKey.keyPath,
|
|
51
|
+
envPrefix,
|
|
52
|
+
example: `${envPrefix} git clone git@github.com:<owner>/<repo>.git`,
|
|
53
|
+
};
|
|
54
|
+
out.provided.push('ssh');
|
|
55
|
+
}
|
|
56
|
+
// HTTPS 通道:askpass 脚本(配置目录 git-askpass.sh,从 config.json 读 token 回显)
|
|
57
|
+
if (tok && tok.token) {
|
|
58
|
+
const askpass = join(dir, 'git-askpass.sh');
|
|
59
|
+
const script = [
|
|
60
|
+
'#!/bin/sh',
|
|
61
|
+
'# dsh-git-push git-askpass:从插件 config.json 读 githubToken 回显(AI 不经手明文;token 只在 config.json 与 git 进程内存)',
|
|
62
|
+
`CFG='${dir}/config.json'`,
|
|
63
|
+
`TOKEN=$(${NODE} -e "const fs=require('fs');const m=fs.readFileSync(process.argv[1],'utf8').match(/\\"githubToken\\"\\s*:\\s*\\"([^\\"]+)\\"/);process.stdout.write(m?m[1]:'')" "$CFG")`,
|
|
64
|
+
'case "$1" in',
|
|
65
|
+
' *[Uu]sername*) echo "git" ;;', // GitHub 个人访问 token 认证时用户名可为任意非空
|
|
66
|
+
' *) echo "$TOKEN" ;;',
|
|
67
|
+
'esac',
|
|
68
|
+
'',
|
|
69
|
+
].join('\n');
|
|
70
|
+
try {
|
|
71
|
+
writeFileSync(askpass, script, { mode: 0o600 });
|
|
72
|
+
chmodSync(askpass, 0o755);
|
|
73
|
+
out.https = {
|
|
74
|
+
channel: 'https',
|
|
75
|
+
askpass,
|
|
76
|
+
envPrefix: `GIT_ASKPASS="${askpass}" GIT_TERMINAL_PROMPT=0`,
|
|
77
|
+
example: `GIT_ASKPASS="${askpass}" git clone https://github.com/<owner>/<repo>.git`,
|
|
78
|
+
};
|
|
79
|
+
out.provided.push('https');
|
|
80
|
+
} catch { /* 写 askpass 失败 → 无 HTTPS 通道(SSH 若可用仍提供) */ }
|
|
81
|
+
}
|
|
82
|
+
if (!out.provided.length) {
|
|
83
|
+
out.hint = '插件未保管可用凭据:config.json 无 githubToken 且配置目录无 SSH 私钥——先 git_gen_ssh_key 生成私钥,或在设置侧边栏保存 token 后再试。';
|
|
84
|
+
} else {
|
|
85
|
+
out.hint = '凭据由插件保管,上方只有路径/命令串(无明文);把 envPrefix 直接粘到 git 命令前即可执行。';
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
package/lib/git/exec.js
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git-push — 提交身份历史改写(把仓库里非规范身份的作者/committer 统一成规范身份)
|
|
3
|
+
*
|
|
4
|
+
* 【为什么做进插件】历史上混着工具/AI 产生的身份(DSH Agent / eightfs@local / v2-clone@local)
|
|
5
|
+
* 与账号身份的旧变体(无 id、小写的 noreply)——这些提交在 GitHub 上关联不到账号、贡献图断裂。
|
|
6
|
+
* 把「识别 → 改写 → 自检 → 安全强推」做成插件能力(工具/CLI/HTTP 同一份实现),AI 就不必
|
|
7
|
+
* 手写 filter-branch 脚本、也不必自己判断该用什么身份。
|
|
8
|
+
*
|
|
9
|
+
* 【安全设计(每一步都不可跳过)】
|
|
10
|
+
* ① 只改「作者或 committer 命中指定身份集合」的提交:其它人/其它身份的提交**自身字段与树内容**
|
|
11
|
+
* 一个字节不动(但它的 sha 会随祖先提交被改写而变化 —— git 提交对象哈希包含父提交 sha,
|
|
12
|
+
* 这是历史重写的必然语义,不是「改了别人的提交」)
|
|
13
|
+
* ② 已跟踪文件有改动 → 拒绝改写(不把未保存的工作卷进历史重写)
|
|
14
|
+
* ③ 每个分支先建备份引用 `refs/backup/identity-rewrite/<时间戳>/<分支>`,可原样回滚
|
|
15
|
+
* ④ 改写后逐分支自检:提交数不变 + 工作树内容不变 + 身份全规范;任一不过立即停,绝不推
|
|
16
|
+
* ⑤ 推送仅在「远端分支 sha == 改写前本地 sha」时用 `--force-with-lease`(远端动过则自动拒绝)
|
|
17
|
+
* ⑥ 默认 dryRun:只报「会改哪些分支、多少提交」,不写任何东西;真正改写必须显式 dryRun:false
|
|
18
|
+
* ⑦ 只处理 origin 属于登录账号的仓库(别人的仓库不碰)
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** 工具/AI 产生的非账号身份(默认要统一的):这些不可能是人有意的身份选择。 */
|
|
22
|
+
export const AI_GENERATED_EMAILS = ['agent@dsh.local', 'eightfs@local', 'v2-clone@local'];
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 需要统一的身份集合(小写去重)。
|
|
26
|
+
* @param {{account?:object, extra?:string[]}} [opts]
|
|
27
|
+
* account: `{ login }` —— 会补上该账号的 noreply 旧变体(无 id 形式 / 小写形式)
|
|
28
|
+
* extra: 额外要统一的邮箱(如历史里出现过的真实邮箱)
|
|
29
|
+
* @returns {string[]}
|
|
30
|
+
*/
|
|
31
|
+
export function wrongIdentityEmails({ account = null, extra = [] } = {}) {
|
|
32
|
+
const list = [...AI_GENERATED_EMAILS];
|
|
33
|
+
const login = String(account?.login || account?.username || '').trim();
|
|
34
|
+
if (login) {
|
|
35
|
+
list.push(`${login}@users.noreply.github.com`);
|
|
36
|
+
list.push(`${login.toLowerCase()}@users.noreply.github.com`);
|
|
37
|
+
}
|
|
38
|
+
for (const e of extra || []) {
|
|
39
|
+
const t = String(e || '').trim();
|
|
40
|
+
if (t) list.push(t);
|
|
41
|
+
}
|
|
42
|
+
return [...new Set(list.map((s) => s.toLowerCase()))];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 拼 shell 片段用的安全包裹:值都是身份名/邮箱(无反斜杠/引号风险),用 JSON 双引号包裹即可。 */
|
|
46
|
+
function shq(s) {
|
|
47
|
+
return JSON.stringify(String(s));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 解析 GitHub 远端地址 → { owner, repo }(支持 ssh/https/api 三种写法)。
|
|
52
|
+
* @param {string} url
|
|
53
|
+
* @returns {{owner:string, repo:string}|null}
|
|
54
|
+
*/
|
|
55
|
+
export function parseGithubRepo(url) {
|
|
56
|
+
const u = String(url || '').trim();
|
|
57
|
+
// github.com:<端口>/<owner>/<repo>(ssh 走 443 时常见)、github.com/<owner>/<repo>、
|
|
58
|
+
// api.github.com/repos/<owner>/<repo> 三种写法都要认
|
|
59
|
+
const m = u.match(/github\.com(?::\d+)?[/:]([^/]+)\/([^/]+?)(?:\.git)?$/i)
|
|
60
|
+
|| u.match(/api\.github\.com\/repos\/([^/]+)\/([^/]+?)(?:\.git)?$/i);
|
|
61
|
+
return m ? { owner: m[1], repo: m[2] } : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 该分支上命中待统一身份的提交清单(作者或 committer 命中;大小写不敏感)。 */
|
|
65
|
+
export function identityHits(repoPath, { runGit, wrongEmails, branch = '' } = {}) {
|
|
66
|
+
const set = new Set((wrongEmails || []).map((s) => s.toLowerCase()));
|
|
67
|
+
const args = ['log', ...(branch ? [branch] : []), '--format=%H%x1f%ae%x1f%ce'];
|
|
68
|
+
const r = runGit(args, { cwd: repoPath });
|
|
69
|
+
if (!r || !r.ok) return [];
|
|
70
|
+
return String(r.stdout || '')
|
|
71
|
+
.split('\n')
|
|
72
|
+
.filter(Boolean)
|
|
73
|
+
.map((line) => {
|
|
74
|
+
const [sha, ae, ce] = line.split('\x1f');
|
|
75
|
+
const hitA = set.has(String(ae || '').toLowerCase());
|
|
76
|
+
const hitC = set.has(String(ce || '').toLowerCase());
|
|
77
|
+
return hitA || hitC ? { sha, author: ae, committer: ce, side: hitA && hitC ? 'both' : (hitA ? 'author' : 'committer') } : null;
|
|
78
|
+
})
|
|
79
|
+
.filter(Boolean);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 生成 filter-branch 的 --env-filter 片段(把命中身份换成规范身份)。 */
|
|
83
|
+
function buildEnvFilter(canonicalName, canonicalEmail, wrongEmails) {
|
|
84
|
+
const list = wrongEmails.join('|');
|
|
85
|
+
const lower = 'tr A-Z a-z';
|
|
86
|
+
return [
|
|
87
|
+
'ae="$(printf %s "$GIT_AUTHOR_EMAIL" | ' + lower + ')"',
|
|
88
|
+
'ce="$(printf %s "$GIT_COMMITTER_EMAIL" | ' + lower + ')"',
|
|
89
|
+
'case "$ae" in ' + list + ') GIT_AUTHOR_NAME=' + shq(canonicalName) + '; GIT_AUTHOR_EMAIL=' + shq(canonicalEmail) + ';; esac',
|
|
90
|
+
'case "$ce" in ' + list + ') GIT_COMMITTER_NAME=' + shq(canonicalName) + '; GIT_COMMITTER_EMAIL=' + shq(canonicalEmail) + ';; esac',
|
|
91
|
+
].join('\n');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 改写单个仓库的身份(多分支一起改;带备份与自检;可选安全强推)。
|
|
96
|
+
*
|
|
97
|
+
* @param {string} repoPath 仓库路径
|
|
98
|
+
* @param {object} opts
|
|
99
|
+
* @param {Function} opts.runGit 注入的 git 执行器 runGit(args,{cwd,env}) → {ok,stdout,stderr}
|
|
100
|
+
* @param {{name:string,email:string}} opts.canonical 规范身份
|
|
101
|
+
* @param {string[]} opts.wrongEmails 要统一的身份集合(小写)
|
|
102
|
+
* @param {boolean} [opts.dryRun=true] true=只报告
|
|
103
|
+
* @param {boolean} [opts.push=false] 自检通过后是否强推
|
|
104
|
+
* @param {string} [opts.timestamp] 备份引用用的时间戳
|
|
105
|
+
* @param {object} [opts.credEnv] 推送用的凭据环境(不传则用 runGit 默认环境)
|
|
106
|
+
* @returns {object} 报告 { repo, skipped?, reason?, branches:[{branch,hits,before,after,pushed,remote}] }
|
|
107
|
+
*/
|
|
108
|
+
export function rewriteRepoIdentity(repoPath, opts = {}) {
|
|
109
|
+
const {
|
|
110
|
+
runGit, canonical, wrongEmails = [], dryRun = true, push = false,
|
|
111
|
+
timestamp = new Date().toISOString().slice(0, 10).replace(/-/g, ''), credEnv = {},
|
|
112
|
+
} = opts;
|
|
113
|
+
if (typeof runGit !== 'function') throw new TypeError('rewriteRepoIdentity 需要注入 runGit');
|
|
114
|
+
const name = repoPath.split('/').filter(Boolean).pop() || repoPath;
|
|
115
|
+
const report = { repo: repoPath, name, branches: [] };
|
|
116
|
+
|
|
117
|
+
const pre = preflightRepo(repoPath, { runGit });
|
|
118
|
+
if (pre.skipped) return { ...report, skipped: true, reason: pre.reason };
|
|
119
|
+
report.origin = pre.origin;
|
|
120
|
+
report.pushUrl = pre.pushUrl;
|
|
121
|
+
|
|
122
|
+
for (const branch of pre.branches) {
|
|
123
|
+
const hits = identityHits(repoPath, { runGit, wrongEmails, branch });
|
|
124
|
+
if (!hits.length) { report.branches.push({ branch, hits: 0, skipped: true, reason: '无需改写' }); continue; }
|
|
125
|
+
const before = countCommits(repoPath, branch, runGit);
|
|
126
|
+
if (dryRun) {
|
|
127
|
+
report.branches.push({ branch, hits: hits.length, before, dryRun: true, samples: hits.slice(0, 3) });
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const entry = rewriteBranch(repoPath, branch, { runGit, canonical, wrongEmails, timestamp, hits: hits.length, before });
|
|
131
|
+
if (!entry.error && push) {
|
|
132
|
+
entry.push = pre.pushUrl
|
|
133
|
+
? pushRewrittenBranch(repoPath, branch, { runGit, pushUrl: pre.pushUrl, oldSha: entry.oldSha, credEnv })
|
|
134
|
+
: { pushed: false, reason: 'origin 不是 GitHub 地址,无法推送' };
|
|
135
|
+
}
|
|
136
|
+
report.branches.push(entry);
|
|
137
|
+
}
|
|
138
|
+
return report;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 分支提交数(runGit 失败按 0,避免 NaN)。 */
|
|
142
|
+
function countCommits(repoPath, branch, runGit) {
|
|
143
|
+
return Number(String((runGit(['rev-list', '--count', branch], { cwd: repoPath }) || {}).stdout || '0').trim()) || 0;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 仓库级预检:已跟踪改动拒改;取本地分支清单与 origin 推送地址。
|
|
148
|
+
* @returns {{skipped?:boolean, reason?:string, branches?:string[], origin?:string, pushUrl?:string}}
|
|
149
|
+
*/
|
|
150
|
+
function preflightRepo(repoPath, { runGit }) {
|
|
151
|
+
const dirty = runGit(['status', '--porcelain', '--untracked-files=no'], { cwd: repoPath });
|
|
152
|
+
if (dirty && dirty.ok && String(dirty.stdout || '').trim()) {
|
|
153
|
+
return { skipped: true, reason: '有已跟踪文件改动(先提交或还原再改写,避免把未保存的工作卷进重写)' };
|
|
154
|
+
}
|
|
155
|
+
const branches = String((runGit(['for-each-ref', '--format=%(refname:short)', 'refs/heads'], { cwd: repoPath }) || {}).stdout || '')
|
|
156
|
+
.split('\n').filter(Boolean);
|
|
157
|
+
if (!branches.length) return { skipped: true, reason: '没有本地分支' };
|
|
158
|
+
const origin = String((runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }) || {}).stdout || '').trim();
|
|
159
|
+
const parsed = parseGithubRepo(origin);
|
|
160
|
+
return {
|
|
161
|
+
branches,
|
|
162
|
+
origin,
|
|
163
|
+
pushUrl: parsed ? `ssh://git@ssh.github.com:443/${parsed.owner}/${parsed.repo}.git` : '',
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 改写单个分支:备份引用 → filter-branch → 自检(提交数/工作树/身份)。
|
|
169
|
+
* 任一步失败都只在返回值里报错并停止,绝不继续推送。
|
|
170
|
+
* @returns {object} 分支报告(带 error 表示未改写或自检未过)
|
|
171
|
+
*/
|
|
172
|
+
function rewriteBranch(repoPath, branch, { runGit, canonical, wrongEmails, timestamp, hits, before }) {
|
|
173
|
+
const backupRef = `refs/backup/identity-rewrite/${timestamp}/${branch}`;
|
|
174
|
+
const oldSha = String((runGit(['rev-parse', branch], { cwd: repoPath }) || {}).stdout || '').trim();
|
|
175
|
+
if (!(runGit(['update-ref', backupRef, branch], { cwd: repoPath }) || {}).ok) {
|
|
176
|
+
return { branch, hits, error: '备份引用写入失败(已停,不冒险改写)' };
|
|
177
|
+
}
|
|
178
|
+
const fb = runGit([
|
|
179
|
+
'filter-branch', '-f', '--env-filter', buildEnvFilter(canonical.name, canonical.email, wrongEmails),
|
|
180
|
+
'--tag-name-filter', 'cat', '--', branch,
|
|
181
|
+
], { cwd: repoPath, timeoutMs: 1_800_000 });
|
|
182
|
+
if (!fb || !fb.ok) {
|
|
183
|
+
return { branch, hits, backupRef, error: `filter-branch 失败:${String((fb && fb.stderr) || '').slice(-200)}` };
|
|
184
|
+
}
|
|
185
|
+
const after = countCommits(repoPath, branch, runGit);
|
|
186
|
+
const stillWrong = identityHits(repoPath, { runGit, wrongEmails, branch }).length;
|
|
187
|
+
const treeDiff = String((runGit(['diff', '--stat', backupRef, branch], { cwd: repoPath }) || {}).stdout || '').trim();
|
|
188
|
+
const entry = { branch, hits, before, after, backupRef, oldSha, stillWrong, treeChanged: !!treeDiff };
|
|
189
|
+
if (before !== after || stillWrong > 0 || treeDiff) {
|
|
190
|
+
entry.error = `自检未过(提交数 ${before}→${after}/残留身份 ${stillWrong}/树差异 ${treeDiff ? '有' : '无'})——已停,不推送`;
|
|
191
|
+
}
|
|
192
|
+
return entry;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 安全强推单个分支:仅当远端 sha == 改写前本地 sha 时 `--force-with-lease`(远端被别人动过则自动拒绝),
|
|
197
|
+
* 推完再核验远端 sha 与本地一致。
|
|
198
|
+
* @returns {{pushed:boolean, verified?:boolean, remoteSha?:string, reason:string}}
|
|
199
|
+
*/
|
|
200
|
+
function pushRewrittenBranch(repoPath, branch, { runGit, pushUrl, oldSha, credEnv }) {
|
|
201
|
+
const lsRemote = () => String((runGit(['ls-remote', pushUrl, `refs/heads/${branch}`], { cwd: repoPath, env: credEnv, timeoutMs: 60_000 }) || {}).stdout || '').split(/\s+/)[0];
|
|
202
|
+
const remoteSha = lsRemote();
|
|
203
|
+
if (!remoteSha) return { pushed: false, reason: '远端无此分支(不新建,避免误伤)' };
|
|
204
|
+
if (remoteSha !== oldSha) {
|
|
205
|
+
return { pushed: false, reason: `远端 sha(${remoteSha.slice(0, 8)}) ≠ 改写前本地(${oldSha.slice(0, 8)}),跳过推送` };
|
|
206
|
+
}
|
|
207
|
+
const p = runGit(['push', `--force-with-lease=refs/heads/${branch}:${oldSha}`, pushUrl, branch], { cwd: repoPath, env: credEnv, timeoutMs: 300_000 });
|
|
208
|
+
if (!p || !p.ok) return { pushed: false, reason: String((p && p.stderr) || '').slice(-200) };
|
|
209
|
+
const post = lsRemote();
|
|
210
|
+
const newSha = String((runGit(['rev-parse', branch], { cwd: repoPath }) || {}).stdout || '').trim();
|
|
211
|
+
return {
|
|
212
|
+
pushed: true,
|
|
213
|
+
verified: post === newSha,
|
|
214
|
+
remoteSha: post,
|
|
215
|
+
reason: post === newSha ? '' : '推送后远端 sha 与本地不一致',
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* 批量改写(多个仓库)。逐仓调用 rewriteRepoIdentity,聚合成总结。
|
|
221
|
+
* @param {string[]} repoPaths 仓库路径
|
|
222
|
+
* @param {object} opts 同 rewriteRepoIdentity(去掉 repoPath)
|
|
223
|
+
* @returns {{dryRun:boolean, canonical:object, wrongEmails:string[], repos:object[], totals:object}}
|
|
224
|
+
*/
|
|
225
|
+
export function rewriteIdentities(repoPaths = [], opts = {}) {
|
|
226
|
+
const repos = repoPaths.map((p) => rewriteRepoIdentity(p, opts));
|
|
227
|
+
const totals = {
|
|
228
|
+
repos: repos.length,
|
|
229
|
+
branches: repos.reduce((n, r) => n + (r.branches || []).length, 0),
|
|
230
|
+
hits: repos.reduce((n, r) => n + (r.branches || []).reduce((m, b) => m + (b.hits || 0), 0), 0),
|
|
231
|
+
rewritten: repos.reduce((n, r) => n + (r.branches || []).filter((b) => b.after != null).length, 0),
|
|
232
|
+
pushed: repos.reduce((n, r) => n + (r.branches || []).filter((b) => b.push && b.push.pushed && b.push.verified !== false).length, 0),
|
|
233
|
+
skipped: repos.filter((r) => r.skipped).length,
|
|
234
|
+
};
|
|
235
|
+
return { dryRun: opts.dryRun !== false, canonical: opts.canonical, wrongEmails: opts.wrongEmails || [], repos, totals };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* 仓库历史里**遗留的**非规范身份统计(只报告,不改任何东西)。
|
|
240
|
+
*
|
|
241
|
+
* 用途:提交时顺带提醒「以前」留下的身份问题 —— 自动提交只要带正确身份即可,
|
|
242
|
+
* 历史要不要统一由用户决定,所以这里只给出「还有多少条、都是谁」,不做任何改写。
|
|
243
|
+
* @param {string} repoPath 仓库路径
|
|
244
|
+
* @param {{runGit:Function, wrongEmails?:string[], branch?:string}} opts
|
|
245
|
+
* @returns {{count:number, emails:string[]}}
|
|
246
|
+
*/
|
|
247
|
+
export function legacyIdentityReport(repoPath, { runGit, wrongEmails = [], branch = '' } = {}) {
|
|
248
|
+
const hits = identityHits(repoPath, { runGit, wrongEmails, branch });
|
|
249
|
+
const set = new Set((wrongEmails || []).map((s) => s.toLowerCase()));
|
|
250
|
+
const emails = [...new Set(
|
|
251
|
+
hits.flatMap((h) => [h.author, h.committer])
|
|
252
|
+
.map((e) => String(e || '').toLowerCase())
|
|
253
|
+
.filter((e) => set.has(e)),
|
|
254
|
+
)];
|
|
255
|
+
return { count: hits.length, emails };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 「以前还有 N 条非规范身份」的提醒文本(提交返回里带上,让 AI 顺带说明)。
|
|
260
|
+
* @param {{count:number, emails?:string[]}} report legacyIdentityReport 的结果
|
|
261
|
+
* @param {{name:string,email:string}|null} [canonical] 本次使用的规范身份
|
|
262
|
+
* @returns {string} count 为 0 时返回空串(无提醒)
|
|
263
|
+
*/
|
|
264
|
+
export function buildLegacyIdentityHint(report = {}, canonical = null) {
|
|
265
|
+
const count = Number(report.count || 0);
|
|
266
|
+
if (!count) return '';
|
|
267
|
+
const who = canonical && canonical.email ? `${canonical.name} <${canonical.email}>` : '登录账号规范身份';
|
|
268
|
+
const list = (report.emails || []).join('、');
|
|
269
|
+
return `⚠️ 该仓库历史上还有 ${count} 条非规范身份提交${list ? `(${list})` : ''}——`
|
|
270
|
+
+ `本次提交身份已是 ${who};历史要不要一并统一由你决定(可调 git_identity_rewrite 先 dry-run 看会改哪些)。`;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 把改写总结格式化成 AI/用户可读文本(工具返回用)。
|
|
275
|
+
* @param {object} summary rewriteIdentities 的返回
|
|
276
|
+
* @returns {string}
|
|
277
|
+
*/
|
|
278
|
+
export function formatIdentityRewriteReport(summary = {}) {
|
|
279
|
+
const { repos = [], totals = {}, canonical = {}, dryRun } = summary;
|
|
280
|
+
const L = [
|
|
281
|
+
`提交身份改写${dryRun ? '(预演 dryRun,未写入)' : ''}:规范身份 ${canonical.name} <${canonical.email}>;`
|
|
282
|
+
+ `仓库 ${totals.repos}|分支 ${totals.branches}|待改/已改提交 ${totals.hits}|已推分支 ${totals.pushed}|跳过仓库 ${totals.skipped}`,
|
|
283
|
+
];
|
|
284
|
+
for (const r of repos) {
|
|
285
|
+
if (r.skipped) { L.push(`· ${r.name}:跳过(${r.reason})`); continue; }
|
|
286
|
+
const parts = (r.branches || []).map((b) => {
|
|
287
|
+
if (b.hits === 0) return `${b.branch}=无需改`;
|
|
288
|
+
if (b.error) return `${b.branch}=❌${b.error}`;
|
|
289
|
+
if (b.dryRun) return `${b.branch}=待改 ${b.hits} 条`;
|
|
290
|
+
const pushed = b.push ? (b.push.pushed ? (b.push.verified === false ? '(推送后校验不符!)' : '(已推)') : `(未推:${b.push.reason})`) : '';
|
|
291
|
+
return `${b.branch}=已改 ${b.hits} 条${pushed}`;
|
|
292
|
+
});
|
|
293
|
+
L.push(`· ${r.name}:${parts.join(',')}`);
|
|
294
|
+
}
|
|
295
|
+
if (dryRun) L.push('要真正改写并推送:带 dryRun:false(会先建备份引用 refs/backup/identity-rewrite/<日期>/<分支>,自检通过才 force-with-lease 推送)');
|
|
296
|
+
return L.join('\n');
|
|
297
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git-push — 提交身份(author/committer)解析
|
|
3
|
+
*
|
|
4
|
+
* 【为什么单独成文件】提交必须带身份,仓库没配时 git 直接以 "Author identity unknown" 拒提交。
|
|
5
|
+
* 旧实现只兜底一个写死的 `DSH Agent <agent@dsh.local>`,从不问「正在登录的 GitHub 账号是谁」,
|
|
6
|
+
* 也不告诉 AI 该用什么身份 —— 实测后果:本机 8 个仓库里混着 DSH Agent / eightfs@local /
|
|
7
|
+
* v2-clone@local / 小写 noreply 等多种身份(如 dsh-git-push 226 个提交里 21 个是 DSH Agent),
|
|
8
|
+
* AI 每次还得自己猜或手敲 -c user.name=…。
|
|
9
|
+
*
|
|
10
|
+
* 【解析优先级】(本文件是纯函数,可单测;落盘动作在 push.js 里做)
|
|
11
|
+
* ① 仓库已配 `user.name` + `user.email` → **原样尊重**(用户/项目的选择优先,插件不覆盖)
|
|
12
|
+
* ② 只差一部分或都没配 → 用**登录的 GitHub 账号**:name = login,
|
|
13
|
+
* email = `<id>+<login>@users.noreply.github.com`(GitHub 官方 noreply 形式:
|
|
14
|
+
* 不暴露真实邮箱、提交能关联到账号;拿不到数字 id 时退化为 `<login>@users.noreply…`)
|
|
15
|
+
* ③ 账号不可用(未登录 / 离线 / 没探测过)→ 退化 `DSH Agent <agent@dsh.local>`(保证仍能提交)
|
|
16
|
+
*
|
|
17
|
+
* 【落地策略】账号身份会自动写进仓库**局部**配置(只改该仓库 .git/config、不入库、不动全局),
|
|
18
|
+
* 于是 AI 手敲 git、插件提交、用户提交都带同一身份 —— 一次落盘,之后无需每次传 -c。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** 兜底身份:账号不可用时用(保持与历史默认一致,避免行为突变)。 */
|
|
22
|
+
export const FALLBACK_IDENTITY = { name: 'DSH Agent', email: 'agent@dsh.local' };
|
|
23
|
+
|
|
24
|
+
/** 身份来源的可读标签(给 AI/用户看的,判断身份是哪来的)。 */
|
|
25
|
+
export const IDENTITY_SOURCE_LABELS = {
|
|
26
|
+
'repo-config': '仓库已有配置',
|
|
27
|
+
'github-account': 'GitHub 登录账号',
|
|
28
|
+
fallback: '兜底通用身份(账号不可用)',
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* GitHub noreply 邮箱:`<id>+<login>@users.noreply.github.com`(无 id 时省略前缀)。
|
|
33
|
+
* @param {string} login GitHub 登录名
|
|
34
|
+
* @param {string|number} [id] 账号数字 id(/user 响应的 id)
|
|
35
|
+
* @returns {string} 邮箱;login 为空时返回空串
|
|
36
|
+
*/
|
|
37
|
+
export function noreplyEmail(login, id) {
|
|
38
|
+
const name = String(login || '').trim();
|
|
39
|
+
if (!name) return '';
|
|
40
|
+
const num = Number(id);
|
|
41
|
+
return Number.isFinite(num) && num > 0
|
|
42
|
+
? `${num}+${name}@users.noreply.github.com`
|
|
43
|
+
: `${name}@users.noreply.github.com`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 由 GitHub 账号状态得到提交身份(账号不可用时返回 null)。
|
|
48
|
+
* @param {object} account 账号信息 `{ login?, username?, id? }`
|
|
49
|
+
* @returns {{name:string, email:string, source:'github-account'}|null}
|
|
50
|
+
*/
|
|
51
|
+
export function identityFromAccount(account = {}) {
|
|
52
|
+
const login = String(account?.login || account?.username || '').trim();
|
|
53
|
+
if (!login) return null;
|
|
54
|
+
return { name: login, email: noreplyEmail(login, account?.id), source: 'github-account' };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 解析某仓库该用的提交身份(纯函数)。
|
|
59
|
+
* @param {{configName?:string, configEmail?:string, account?:object}} [input]
|
|
60
|
+
* configName/configEmail:仓库 `git config user.name/user.email` 的当前值(可能为空)
|
|
61
|
+
* account:账号信息 `{ login, id }`
|
|
62
|
+
* @returns {{name:string, email:string, source:string, complete:boolean, missing:{name:boolean, email:boolean}}}
|
|
63
|
+
* complete=true 表示 name/email 都已齐(可用仓库配置直接提交);false 表示需在 commit 上补 -c
|
|
64
|
+
*/
|
|
65
|
+
export function resolveCommitIdentity({ configName = '', configEmail = '', account = null } = {}) {
|
|
66
|
+
const name = String(configName || '').trim();
|
|
67
|
+
const email = String(configEmail || '').trim();
|
|
68
|
+
if (name && email) {
|
|
69
|
+
return { name, email, source: 'repo-config', complete: true, missing: { name: false, email: false } };
|
|
70
|
+
}
|
|
71
|
+
const missing = { name: !name, email: !email };
|
|
72
|
+
const fromAccount = identityFromAccount(account || {});
|
|
73
|
+
if (fromAccount) {
|
|
74
|
+
return {
|
|
75
|
+
// 已配置的一侧优先保留(例如仓库只差 email:名字仍用仓库的)
|
|
76
|
+
name: name || fromAccount.name,
|
|
77
|
+
email: email || fromAccount.email,
|
|
78
|
+
source: fromAccount.source,
|
|
79
|
+
complete: false,
|
|
80
|
+
missing,
|
|
81
|
+
accountLogin: fromAccount.name,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
name: name || FALLBACK_IDENTITY.name,
|
|
86
|
+
email: email || FALLBACK_IDENTITY.email,
|
|
87
|
+
source: 'fallback',
|
|
88
|
+
complete: false,
|
|
89
|
+
missing,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 人类/AI 可读的身份行:`EIGHTfs <38984640+EIGHTfs@users.noreply.github.com>`。 */
|
|
94
|
+
export function identityLabel(identity = {}) {
|
|
95
|
+
const name = String(identity.name || '').trim();
|
|
96
|
+
const email = String(identity.email || '').trim();
|
|
97
|
+
return email ? `${name} <${email}>` : name;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 给 AI 看的身份说明(一句话),明确「该用哪个身份、别自己编」。
|
|
102
|
+
* @param {object} identity resolveCommitIdentity 的结果
|
|
103
|
+
* @returns {string}
|
|
104
|
+
*/
|
|
105
|
+
export function identityHintText(identity = {}) {
|
|
106
|
+
const label = identityLabel(identity);
|
|
107
|
+
const src = IDENTITY_SOURCE_LABELS[identity.source] || identity.source || '未知';
|
|
108
|
+
if (identity.source === 'repo-config') return `${label}(来源:${src})`;
|
|
109
|
+
if (identity.source === 'github-account') return `${label}(来源:${src};未配身份的仓库由插件自动写入局部配置)`;
|
|
110
|
+
return `${label}(来源:${src}——账号不可用时才用它,不要手写这个身份)`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 解析仓库该用的身份,并在未配时把账号身份写进仓库**局部**配置(`git config --local`)。
|
|
115
|
+
*
|
|
116
|
+
* 只在 `source === 'github-account'` 时落盘:仓库已配 → 一个字节都不动;
|
|
117
|
+
* 账号不可用 → 只返回兜底身份、不写(避免把 DSH Agent 固化进仓库配置)。
|
|
118
|
+
* git 执行器由参数注入,便于单测用临时仓库跑真实 git。
|
|
119
|
+
*
|
|
120
|
+
* @param {string} repoPath 仓库路径
|
|
121
|
+
* @param {{runGit:Function, account?:object|null}} opts runGit(args,{cwd}) → {ok,stdout,stderr}
|
|
122
|
+
* @returns {{name:string,email:string,source:string,complete:boolean,written:string[],label:string}}
|
|
123
|
+
*/
|
|
124
|
+
export function ensureRepoIdentity(repoPath, { runGit, account = null } = {}) {
|
|
125
|
+
if (typeof runGit !== 'function') throw new TypeError('ensureRepoIdentity 需要注入 runGit');
|
|
126
|
+
const readCfg = (key) => {
|
|
127
|
+
const r = runGit(['config', key], { cwd: repoPath });
|
|
128
|
+
return r && r.ok ? String(r.stdout || '').trim() : '';
|
|
129
|
+
};
|
|
130
|
+
const id = resolveCommitIdentity({
|
|
131
|
+
configName: readCfg('user.name'),
|
|
132
|
+
configEmail: readCfg('user.email'),
|
|
133
|
+
account,
|
|
134
|
+
});
|
|
135
|
+
const written = [];
|
|
136
|
+
if (id.source === 'github-account') {
|
|
137
|
+
// 只补缺的那一侧(仓库已有的一半保持不动)
|
|
138
|
+
if (id.missing.name) {
|
|
139
|
+
const r = runGit(['config', '--local', 'user.name', id.name], { cwd: repoPath });
|
|
140
|
+
if (r && r.ok) written.push(`user.name=${id.name}`);
|
|
141
|
+
}
|
|
142
|
+
if (id.missing.email) {
|
|
143
|
+
const r = runGit(['config', '--local', 'user.email', id.email], { cwd: repoPath });
|
|
144
|
+
if (r && r.ok) written.push(`user.email=${id.email}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const stillMissing = (id.missing.name && !written.some((w) => w.startsWith('user.name=')))
|
|
148
|
+
|| (id.missing.email && !written.some((w) => w.startsWith('user.email=')));
|
|
149
|
+
return { ...id, complete: !stillMissing, written, label: identityLabel(id) };
|
|
150
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git 执行层 · .gitignore
|
|
3
|
+
*
|
|
4
|
+
* 职责:产物/依赖忽略兜底(DEFAULT_IGNORE_PATTERNS)与 .gitignore 补齐。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { isSampleExemptDir } from '../exempt/index.js';
|
|
10
|
+
import { scanSensitiveFiles } from './sensitive.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 基线忽略项(与仓库内容无关,恒定排除)。
|
|
14
|
+
* node_modules 是依赖目录、node_modules.orig 是安装/备份残留副本,
|
|
15
|
+
* 两者都属机器本地产物,不应进入版本库(也避免链接/占位混入插件树)。
|
|
16
|
+
*/
|
|
17
|
+
export const DEFAULT_IGNORE_PATTERNS = ['node_modules/', 'node_modules.orig/'];
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 把基线忽略项 + 自定义忽略追加进 .gitignore(幂等:已存在行不重复写)。
|
|
21
|
+
* 敏感文件扫描只报告(files),不写入 .gitignore、不解除跟踪(用户指令)。
|
|
22
|
+
* @param {string} repoPath 仓库根
|
|
23
|
+
* @param {{customIgnorePatterns?: string|string[]}} [opts]
|
|
24
|
+
* customIgnorePatterns:逗号/换行分隔的 gitignore pattern 或字符串数组(用户自定义忽略)
|
|
25
|
+
* @returns {{added:number, files:string[], baseline:number, custom:number, tracked:string[], unstaged:string[]}}
|
|
26
|
+
* added 追加总行数 / files 敏感文件路径(只报告)/ baseline 基线补入数 / custom 自定义补入数 /
|
|
27
|
+
* tracked 恒空(不再解除跟踪)/ unstaged 恒空
|
|
28
|
+
*/
|
|
29
|
+
export async function ensureGitignore(repoPath, { customIgnorePatterns = '' } = {}) {
|
|
30
|
+
const files = await scanSensitiveFiles(repoPath);
|
|
31
|
+
const giPath = join(repoPath, '.gitignore');
|
|
32
|
+
let existing = '';
|
|
33
|
+
try { existing = existsSync(giPath) ? readFileSync(giPath, 'utf8') : ''; } catch { /* 忽略 */ }
|
|
34
|
+
const lines = existing.split('\n').map((l) => l.trim());
|
|
35
|
+
let added = 0;
|
|
36
|
+
let baseline = 0;
|
|
37
|
+
let custom = 0;
|
|
38
|
+
let sampleExempted = 0;
|
|
39
|
+
const additions = [];
|
|
40
|
+
// 1) 基线忽略项(node_modules / node_modules.orig)
|
|
41
|
+
for (const pat of DEFAULT_IGNORE_PATTERNS) {
|
|
42
|
+
const bare = pat.replace(/\/$/, '');
|
|
43
|
+
if (lines.includes(pat) || lines.includes(bare)) continue;
|
|
44
|
+
additions.push(pat);
|
|
45
|
+
baseline++;
|
|
46
|
+
added++;
|
|
47
|
+
}
|
|
48
|
+
// 2) 扫描出的敏感文件(内容级 + 文件名黑名单)——只报告不动作:不动 .gitignore、不解除跟踪
|
|
49
|
+
//(用户指令:扫描到敏感文件不改动 git 忽略配置,由仓库方自行决定处理)
|
|
50
|
+
for (const hit of files) {
|
|
51
|
+
const rel = hit.path;
|
|
52
|
+
if (isSampleExemptDir(repoPath, rel)) { sampleExempted++; continue; }
|
|
53
|
+
// 已跟踪不解除、未跟踪不追加——敏感文件照常留在工作区,仅经 files 报告
|
|
54
|
+
}
|
|
55
|
+
// 3) 自定义忽略 pattern(幂等追加)
|
|
56
|
+
const customList = (Array.isArray(customIgnorePatterns) ? customIgnorePatterns : String(customIgnorePatterns || '').split(/[\n,]/))
|
|
57
|
+
.map((s) => s.trim()).filter(Boolean);
|
|
58
|
+
for (const line of customList) {
|
|
59
|
+
if (lines.includes(line)) continue;
|
|
60
|
+
additions.push(line);
|
|
61
|
+
custom++;
|
|
62
|
+
added++;
|
|
63
|
+
}
|
|
64
|
+
if (added) {
|
|
65
|
+
const block = `${existing.endsWith('\n') || !existing ? '' : '\n'}${additions.join('\n')}\n`;
|
|
66
|
+
try { writeFileSync(giPath, existing + block, 'utf8'); } catch { /* 写失败不抛 */ }
|
|
67
|
+
}
|
|
68
|
+
return { added, files: files.map((h) => h.path), baseline, custom, tracked: [], unstaged: [], sampleExempted };
|
|
69
|
+
}
|