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
package/lib/git/push.js
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git 执行层 · 提交推送编排
|
|
3
|
+
*
|
|
4
|
+
* 职责:commitAndPush 总流程(敏感扫描 → .gitignore → add/commit → 推送到选定通道
|
|
5
|
+
* → 推送后增强),以及推送成功后的收尾(打标签、跟踪引用更新)。
|
|
6
|
+
* 具体通道实现在 transport.js,本模块只做编排与前置检查。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync } from 'node:fs';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { autoTagDSHProject, ensureAuxSshRemote, readPkgVersion, updateRemoteTrackingRef } from './post-push.js';
|
|
12
|
+
import { loadRequirements } from './config.js';
|
|
13
|
+
import { resolveSshKeys } from './credentials.js';
|
|
14
|
+
import { runGit } from './exec.js';
|
|
15
|
+
import { buildWrappedGitEnv } from './wrapped-git.js';
|
|
16
|
+
import { buildCommitMessage } from './commit-message.js';
|
|
17
|
+
// 推送失败诊断:把「原文事实」与「推断」分开,避免把探针失败误读成「仓库不存在/推送未落地」
|
|
18
|
+
import { classifyPushFailure } from './push-diagnose.js';
|
|
19
|
+
import { ensureGitignore } from './ignore.js';
|
|
20
|
+
import { scanSensitiveFiles } from './sensitive.js';
|
|
21
|
+
import { ensureRepoIdentity } from './identity.js';
|
|
22
|
+
import { buildLegacyIdentityHint, legacyIdentityReport, wrongIdentityEmails } from './identity-rewrite.js';
|
|
23
|
+
import { readAccountStatus } from './account-status.js';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 解析本仓库该用的提交身份,并在「仓库未配身份」时把**账号身份**写进仓库局部配置。
|
|
27
|
+
*
|
|
28
|
+
* 策略:仓库已配 → 尊重;未配 → 用登录的 GitHub 账号身份
|
|
29
|
+
* (`EIGHTfs <38984640+EIGHTfs@users.noreply.github.com>`)并 `git config --local` 落盘 ——
|
|
30
|
+
* 这样 AI 手敲 git / 插件提交 / 用户提交都带同一身份,不用每次传 -c,也不会再有 DSH Agent 提交。
|
|
31
|
+
* 只写仓库局部配置(该仓库 .git/config,不入库、不动全局)。
|
|
32
|
+
*
|
|
33
|
+
* @param {string} repoPath 仓库路径
|
|
34
|
+
* @returns {{name:string,email:string,source:string,complete:boolean,written:string[],label:string}}
|
|
35
|
+
* complete=true:仓库配置已齐(可直接 commit);false:需在 commit 上补 `-c user.name/email`
|
|
36
|
+
*/
|
|
37
|
+
function resolveRepoIdentity(repoPath) {
|
|
38
|
+
const st = readAccountStatus();
|
|
39
|
+
const account = st?.token?.valid
|
|
40
|
+
? { login: st.token.login || st.username || '', id: st.token.id || '' }
|
|
41
|
+
: null;
|
|
42
|
+
return ensureRepoIdentity(repoPath, { runGit, account });
|
|
43
|
+
}
|
|
44
|
+
import { fetchRemoteHeads, dispatchPush, liveRemoteHead } from './transport.js';
|
|
45
|
+
// 推送后「远端 sha 硬校验」用(假成功防线:远端空仓/未落地时必须判失败,见 enhanceAfterPushSuccess)
|
|
46
|
+
import { githubFetch } from './api.js';
|
|
47
|
+
import { resolveRepoVisibility } from './visibility.js';
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 统一提交推送:预检 → 敏感文件 .gitignore → add → commit → push。
|
|
51
|
+
* @param {{repoPath, message, push, dryRun, token, customIgnorePatterns}} opts
|
|
52
|
+
* message:字符串(原样透传)|数组(元素为字符串,或 {what,type?,scope?,why?,verify?,refs?})|
|
|
53
|
+
* {subject?, items:[...]}(显式标题)——仅 what 必填,由 lib/git/commit-message.js 组装
|
|
54
|
+
* customIgnorePatterns:逗号/换行分隔的 gitignore pattern,追加进 .gitignore(幂等)
|
|
55
|
+
* @returns {{ok, steps: string[], commitSha?, pushed?, push?, remoteHeads?, error?}}
|
|
56
|
+
*/
|
|
57
|
+
export async function commitAndPush({ repoPath = '', message = '', push = true, dryRun = false, token = '', customIgnorePatterns = '', requirementsConfirmed = false, force = false, pushMethod = 'ssh', pushGate = false, pushConfirmed = false, paths = '' } = {}) {
|
|
58
|
+
const steps = [];
|
|
59
|
+
if (!repoPath || !existsSync(join(repoPath, '.git'))) return { ok: false, steps: ['预检'], error: `非 git 仓库: ${repoPath || '(空)'}` };
|
|
60
|
+
// message 支持三种形态(字符串 / 数组 / {subject,items}):在预检处**单点**组装成规范提交信息,
|
|
61
|
+
// 后续流程(add / commit -m / 回执)只用 built.message —— 避免多处各自解析导致行为分叉。
|
|
62
|
+
// 字符串形态原样透传(既有调用方行为不变);数组/对象形态由 lib/git/commit-message.js 组装。
|
|
63
|
+
const built = buildCommitMessage(message);
|
|
64
|
+
if (!built.ok) return { ok: false, steps: ['预检'], error: built.error };
|
|
65
|
+
const commitMessage = built.message;
|
|
66
|
+
// D13 开发者要求门禁(commitPushPreflight 语义):要求清单存在且未核对 → 拦截。
|
|
67
|
+
// 清单来源:credentialsDir()/requirements.json(外挂)→ PLUGIN_ROOT/lib/user-requirements.json(内置)。
|
|
68
|
+
const userReqs = loadRequirements();
|
|
69
|
+
if (userReqs.found && userReqs.items?.length && !requirementsConfirmed) {
|
|
70
|
+
return {
|
|
71
|
+
ok: false,
|
|
72
|
+
blocked: true,
|
|
73
|
+
code: 'USER_REQUIREMENTS',
|
|
74
|
+
steps: ['预检'],
|
|
75
|
+
error: '开发者特殊要求未核对:AI 需先逐条核对要求全部达标,再带 requirementsConfirmed:true 重新调用',
|
|
76
|
+
requirements: userReqs,
|
|
77
|
+
repo: repoPath,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
// D14 detached HEAD 防护(commitPushPreflight 语义):HEAD 处于 detached 状态时拒绝提交,
|
|
81
|
+
// 避免在无分支的游离 HEAD 上 commit 后无法推送(v1: 'HEAD 处于 detached 状态,请先 checkout 分支')
|
|
82
|
+
// ⚠ 必须区分「git 调用失败」与「真的是游离 HEAD」:此前只看 stdout,git 因 PATH 缺 git /
|
|
83
|
+
// 不信任目录等原因失败时空 stdout 会被误报成 detached HEAD,把排查带偏(2026-10-03 实测)。
|
|
84
|
+
const cur = runGit(['branch', '--show-current'], { cwd: repoPath });
|
|
85
|
+
if (!cur.ok) return { ok: false, steps: ['预检'], error: `git 调用失败:${cur.stderr}` };
|
|
86
|
+
const curBranch = cur.stdout;
|
|
87
|
+
if (!curBranch) return { ok: false, steps: ['预检'], error: 'HEAD 处于 detached 状态,请先 checkout 分支' };
|
|
88
|
+
if (dryRun) return { ok: true, dryRun: true, steps: ['预检', 'commit', push ? 'push' : 'skip-push'] };
|
|
89
|
+
// ── 「零改动就不写 .gitignore、不提交」(前置判定)──
|
|
90
|
+
// 为什么必须前置:仓库没有 .gitignore 时,ensureGitignore 会**新建/追加** .gitignore,
|
|
91
|
+
// 于是「本来干净的仓」被自己写脏 ⇒ 凭空多出一个只含 .gitignore 的提交 ✗
|
|
92
|
+
// (修复前实测:steps = ["敏感文件 .gitignore", ".gitignore(+2条)", "add", "commit"],
|
|
93
|
+
// 用户只调了一次「推一下」,远端就多了一个提交)。
|
|
94
|
+
// 用 paths 精确 add 时只按这些路径判定(否则会被别处的改动误判)。
|
|
95
|
+
const pathList = String(paths || '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
96
|
+
const preStatus = runGit(['status', '--porcelain', ...(pathList.length ? ['--', ...pathList] : [])], { cwd: repoPath });
|
|
97
|
+
let cleanSkipCommit = false;
|
|
98
|
+
if (preStatus.ok && !preStatus.stdout.trim()) {
|
|
99
|
+
cleanSkipCommit = true;
|
|
100
|
+
steps.push('clean-worktree');
|
|
101
|
+
if (!push) {
|
|
102
|
+
// 文案口径:工作区没有改动是**正常成功路径**(不是失败)——明确写出来,
|
|
103
|
+
// 否则 AI 会以为「没东西可提交 ⇒ 这次调用会报错」,宁可绕开插件自己手敲 git。
|
|
104
|
+
return { ok: true, steps, committed: false, message: '无变更:工作区无改动,无需提交(正常,不是错误)', push: { pushed: false, reason: '无变更(正常,非错误)' } };
|
|
105
|
+
}
|
|
106
|
+
// 工作区干净但本地领先远端(已手动 commit 未 push)时不能直接跳过——
|
|
107
|
+
// pushViaApi 用本地 HEAD 推送,领先提交照常可推;仅当「无变更 && 无领先」才真正跳过。
|
|
108
|
+
const ahead = curBranch ? runGit(['rev-list', '--count', `origin/${curBranch}..HEAD`], { cwd: repoPath }) : { ok: false };
|
|
109
|
+
const aheadCount = ahead.ok ? Number(ahead.stdout || 0) : 0;
|
|
110
|
+
if (ahead.ok && aheadCount > 0) steps.push('clean-领先跳过 commit,直接推');
|
|
111
|
+
}
|
|
112
|
+
// 有改动才写 .gitignore / add / commit
|
|
113
|
+
if (!cleanSkipCommit) {
|
|
114
|
+
steps.push('敏感文件 .gitignore');
|
|
115
|
+
// 私有库豁免:GitHub 可见性 = private → 只扫描报告不写 .gitignore、不解除跟踪
|
|
116
|
+
// (私有库敏感字段入库风险由仓库自身可见性兜底);探测失败/非 GitHub origin 保守不豁免。
|
|
117
|
+
// 可见性判定**统一走 lib/git/visibility.js**(与审计门禁同一收口,避免两处口径漂移)。
|
|
118
|
+
const vis = await resolveRepoVisibility(repoPath, token);
|
|
119
|
+
const privateExempt = vis.visibility === 'private';
|
|
120
|
+
const visReason = privateExempt ? `private(${vis.owner}/${vis.repo})` : '';
|
|
121
|
+
const gi = privateExempt
|
|
122
|
+
? { added: 0, files: (await scanSensitiveFiles(repoPath)).map((h) => h.path), baseline: 0, custom: 0, tracked: [], unstaged: [], skipped: 'private-repo-exempt' }
|
|
123
|
+
: await ensureGitignore(repoPath, { customIgnorePatterns });
|
|
124
|
+
// 敏感文件只报告不动作(用户指令:扫描到不改动 git 忽略,由仓库方自行处理)
|
|
125
|
+
if (gi.files.length) steps.push(`sensitive-scan(${gi.files.length}文件, 只报告)`);
|
|
126
|
+
else if (gi?.added > 0) steps.push(`.gitignore(+${gi.added}条)`);
|
|
127
|
+
if (privateExempt) steps.push(`private-exempt(${visReason})`);
|
|
128
|
+
steps.push('add');
|
|
129
|
+
// 支持**精确 add 路径**(paths 逗号分隔,相对 repoPath)——只在有他人未提交
|
|
130
|
+
// 改动 / 不想全量暂存时用:`git add <path...>` 只暂存指定文件,替代默认 `git add -A`
|
|
131
|
+
// (add -A 会把无关文件一并扫入提交,bench-template 等共享工作区场景实测踩坑)。
|
|
132
|
+
const add = pathList.length
|
|
133
|
+
? runGit(['add', ...pathList], { cwd: repoPath })
|
|
134
|
+
: runGit(['add', '-A'], { cwd: repoPath });
|
|
135
|
+
if (!add.ok) return { ok: false, steps, error: `git add 失败: ${add.stderr}` };
|
|
136
|
+
const status = runGit(['status', '--porcelain'], { cwd: repoPath });
|
|
137
|
+
// 二次判定:若改动**只**来自被 .gitignore 覆盖的敏感文件(add 后已无可提交内容),
|
|
138
|
+
// 同样按「零改动」处理——绝不因为自动写 .gitignore 而凭空产生提交。
|
|
139
|
+
if (!status.stdout.trim()) {
|
|
140
|
+
cleanSkipCommit = true;
|
|
141
|
+
steps.push('clean-worktree');
|
|
142
|
+
if (!push) {
|
|
143
|
+
return { ok: true, steps, committed: false, message: '无变更:工作区无改动,无需提交(正常,不是错误)', push: { pushed: false, reason: '无变更(正常,非错误)' } };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
// 提交身份:仓库已配则用;未配则用登录账号身份并写入仓库局部配置(见 resolveRepoIdentity)。
|
|
148
|
+
const identity = resolveRepoIdentity(repoPath);
|
|
149
|
+
// 提交时顺带提醒「以前」:该仓库历史里还有多少条非规范身份提交(只报告,绝不改历史)
|
|
150
|
+
const legacyIdentity = (() => {
|
|
151
|
+
try {
|
|
152
|
+
const st = readAccountStatus();
|
|
153
|
+
const account = st?.token?.valid ? { login: st.token.login || st.username || '' } : null;
|
|
154
|
+
const rep = legacyIdentityReport(repoPath, { runGit, wrongEmails: wrongIdentityEmails({ account }) });
|
|
155
|
+
return { count: rep.count, emails: rep.emails, hint: buildLegacyIdentityHint(rep, identity) };
|
|
156
|
+
} catch {
|
|
157
|
+
return null; // 提醒是附加信息,算不出来不影响提交
|
|
158
|
+
}
|
|
159
|
+
})();
|
|
160
|
+
steps.push('commit');
|
|
161
|
+
if (!cleanSkipCommit) {
|
|
162
|
+
// 身份写盘失败等极端情况才退回命令行 -c(双保险,避免 "Author identity unknown")
|
|
163
|
+
const identityArgs = identity.complete
|
|
164
|
+
? []
|
|
165
|
+
: ['-c', `user.name=${identity.name}`, '-c', `user.email=${identity.email}`];
|
|
166
|
+
const commit = runGit([...identityArgs, 'commit', '-m', commitMessage], { cwd: repoPath });
|
|
167
|
+
if (!commit.ok) {
|
|
168
|
+
if (/nothing to commit|no changes added/i.test(commit.stderr)) {
|
|
169
|
+
// 同上:git 自己回「nothing to commit」也只是「没东西可提交」,属于成功跳过
|
|
170
|
+
return { ok: true, steps, committed: false, message: '无变更:工作区无改动,无需提交(正常,不是错误)', push: { pushed: false, reason: '无变更(正常,非错误)' } };
|
|
171
|
+
}
|
|
172
|
+
return { ok: false, steps, error: `git commit 失败: ${commit.stderr}` };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const commitSha = runGit(['rev-parse', 'HEAD'], { cwd: repoPath }).stdout;
|
|
176
|
+
if (!push) return { ok: true, steps: [...steps, 'skip-push'], commitSha, pushed: false, committed: !cleanSkipCommit, identity, legacyIdentity };
|
|
177
|
+
// 推送门禁(类似会话指挥家写操作拦截)——开启后 push 必须带 pushConfirmed:true
|
|
178
|
+
// (显式放行标记),否则**拦截推送步骤**(commit 已落本地,push 被挡、不产生远端变更)。
|
|
179
|
+
if (pushGate && !pushConfirmed) {
|
|
180
|
+
return {
|
|
181
|
+
ok: false,
|
|
182
|
+
blocked: true,
|
|
183
|
+
code: 'PUSH_GATE',
|
|
184
|
+
steps: [...steps, 'push-gate'],
|
|
185
|
+
commitSha,
|
|
186
|
+
error: '推送门禁已开启:push 需显式放行(带 pushConfirmed:true 重新调用,可沿用本次 commit,不重复提交)。',
|
|
187
|
+
pushGate: true,
|
|
188
|
+
push: { pushed: false, reason: 'push-gate' },
|
|
189
|
+
identity,
|
|
190
|
+
legacyIdentity,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
steps.push('push');
|
|
194
|
+
// 通道由 dispatchPush 单点决策(默认 SSH:推本地 HEAD、远端 sha 与本地一致;无密钥才回落 API)。
|
|
195
|
+
// ⚠️ dispatchPush 是 async:必须 await(旧 bug:同步调用导致 pr.ok 恒 undefined,推送从未成功)
|
|
196
|
+
const pr = await dispatchPush({ repoPath, token, force, pushMethod });
|
|
197
|
+
if (pr.ok) {
|
|
198
|
+
// D24:pr.pushed=false(内容级短路「远端已是最新」)→ 如实 pushed:false(commitPushDoPush 语义)
|
|
199
|
+
// committed 必须如实带上:cleanSkipCommit 时本次**没有产生新提交**。
|
|
200
|
+
// 此前这条路径缺 committed 字段,job 输出就兜底成「已提交,未推送」——与实际相反 ✗(实测复现)
|
|
201
|
+
if (!pr.pushed) return { ok: true, steps, commitSha, committed: !cleanSkipCommit, pushed: false, push: pr, identity, legacyIdentity };
|
|
202
|
+
// 推送后增强对两条通道一视同仁:remote-tracking ref + aux remote + autoTag + remote heads。
|
|
203
|
+
// 原先只有 API 分支做这些,SSH 分支只拉 heads → 走 SSH 时本地 origin/<branch> 引用不更新,
|
|
204
|
+
// 下次 ahead/behind 判断就会错位。
|
|
205
|
+
steps.push(`pushed-via-${pr.method || 'unknown'}`);
|
|
206
|
+
const enhanced = await enhanceAfterPushSuccess({ repoPath, pr, token, steps, commitSha });
|
|
207
|
+
// 假成功防线(用户实测事故):远端为空仓时推送动作不报错,但提交根本没上去。
|
|
208
|
+
// verified===false 表示「API 查到了远端分支,但 sha 与本地提交不一致 / 查不到该分支」
|
|
209
|
+
// ⇒ 必须返回 ok:false,让调用方与用户看到真实状态,而不是「commit+push done」。
|
|
210
|
+
// verified===null(校验自身失败,如网络/权限)不算失败,但把原因带在 push.verifyError 里。
|
|
211
|
+
if (enhanced.push?.verified === false) {
|
|
212
|
+
steps.push('push-verify-failed');
|
|
213
|
+
return {
|
|
214
|
+
ok: false, steps, commitSha, pushed: false,
|
|
215
|
+
error: `推送未落地:${enhanced.push.verifyError || '远端 sha 与本地不一致'}`,
|
|
216
|
+
push: enhanced.push,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
// committed 如实带上:cleanSkipCommit 时推的是**此前已提交的领先内容**,本次没有新提交
|
|
220
|
+
return { ok: true, steps, commitSha, committed: !cleanSkipCommit, pushed: true, push: enhanced.push, autoTag: enhanced.autoTag, ...(enhanced.heads ? { remoteHeads: enhanced.heads } : {}), identity, legacyIdentity };
|
|
221
|
+
}
|
|
222
|
+
// 失败回执附结构化诊断(分类 + 置信度 + 下一步)
|
|
223
|
+
const dg = pr.diagnosis || classifyPushFailure(String(pr.reason || ''), { method: pr.method });
|
|
224
|
+
return {
|
|
225
|
+
ok: false, steps, commitSha,
|
|
226
|
+
error: `推送失败(${pr.method || '通道'}):${pr.reason}|诊断 ${dg.code}(${dg.confidence === 'low' ? '推断,置信度低' : '依据充分'}):${dg.inference}|下一步:${dg.nextSteps[0] || ''}`,
|
|
227
|
+
diagnosis: dg,
|
|
228
|
+
identity, legacyIdentity,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* 把远端的提交对象取回本地,并让 refs/remotes/origin/<branch> 指向**远端真实 sha**。
|
|
234
|
+
*
|
|
235
|
+
* 为什么需要:API 通道在远端新建的提交,本地没有该对象,`update-ref` 直接写远端 sha 会报
|
|
236
|
+
* `nonexistent object`,于是旧实现改写成「本地 HEAD sha 代理」——推送内容虽等价,但一旦本地
|
|
237
|
+
* 与远端已经分叉,这个代理会让 `git status` / ahead-behind 谎报 0/0,把分叉的仓库显示成同步。
|
|
238
|
+
* 先 fetch 把对象取回,引用才是真的;取不到时由调用方退回代理写法并如实标注。
|
|
239
|
+
* fetch 用 `+` 前缀更新 remote-tracking 引用:远端跟踪引用的语义就是「镜像远端」,
|
|
240
|
+
* 分叉时也必须能更新(否则 fetch 本身会因非快进而被拒)。
|
|
241
|
+
* @returns {Promise<string>} 远端真实 sha(失败返回 '')
|
|
242
|
+
*/
|
|
243
|
+
async function fetchRemoteBranchRef(repoPath, branch, owner, repo) {
|
|
244
|
+
if (!owner || !repo || !branch) return '';
|
|
245
|
+
const keys = resolveSshKeys();
|
|
246
|
+
if (!keys.length) return '';
|
|
247
|
+
const known = join('/tmp', `dsh-git-push-known-hosts-${process.pid}`);
|
|
248
|
+
const url = `ssh://git@ssh.github.com:443/${owner}/${repo}.git`;
|
|
249
|
+
for (const { keyPath } of keys) {
|
|
250
|
+
const sshCmd = `ssh -i "${keyPath}" -p 443 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="${known}" -o BatchMode=yes`;
|
|
251
|
+
const r = runGit(['fetch', '--no-tags', url, `+refs/heads/${branch}:refs/remotes/origin/${branch}`],
|
|
252
|
+
{ cwd: repoPath, env: { GIT_SSH_COMMAND: sshCmd } });
|
|
253
|
+
if (r.ok) return runGit(['rev-parse', `refs/remotes/origin/${branch}`], { cwd: repoPath }).stdout;
|
|
254
|
+
}
|
|
255
|
+
return '';
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* API 推送成功后的增强(D15):更新 remote-tracking ref +
|
|
260
|
+
* 确保辅助 SSH remote + dsh- 项目自动打 tag + 拉取远端 heads。三者失败不阻断推送成功,
|
|
261
|
+
* 结果记入 push.remoteRef / push.auxRemote / autoTag。
|
|
262
|
+
* @returns {Promise<{push, autoTag, heads?}>}
|
|
263
|
+
*/
|
|
264
|
+
async function enhanceAfterPushSuccess({ repoPath, pr, token, steps, commitSha }) {
|
|
265
|
+
const pushSlot = pr;
|
|
266
|
+
const branchRef = pr.branch;
|
|
267
|
+
const localHead = runGit(['rev-parse', 'HEAD'], { cwd: repoPath }).stdout;
|
|
268
|
+
let refTarget = localHead || pr.commitSha;
|
|
269
|
+
let refNote = '';
|
|
270
|
+
// SSH 通道推的就是本地对象,localHead 即远端 sha;API 通道要先取回真实对象再写引用。
|
|
271
|
+
if (pr.method === 'api') {
|
|
272
|
+
try {
|
|
273
|
+
const realSha = await fetchRemoteBranchRef(repoPath, branchRef, pr.owner, pr.repo);
|
|
274
|
+
if (realSha) refTarget = realSha;
|
|
275
|
+
else refNote = `(代理 sha:远端提交本地无对象且取回失败,远端实际 ${String(pr.commitSha || '').slice(0, 7)})`;
|
|
276
|
+
} catch (e) {
|
|
277
|
+
refNote = `(代理 sha:取回远端对象异常 ${String(e?.message || e).slice(0, 60)})`;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
pushSlot.remoteRef = updateRemoteTrackingRef(repoPath, branchRef, refTarget) + refNote;
|
|
281
|
+
try {
|
|
282
|
+
ensureAuxSshRemote(repoPath, pr.owner, pr.repo, { push: pushSlot });
|
|
283
|
+
} catch (e) {
|
|
284
|
+
pushSlot.auxRemote = `ensure-aux-remote 异常: ${e?.message || e}`;
|
|
285
|
+
}
|
|
286
|
+
let autoTag = null;
|
|
287
|
+
try {
|
|
288
|
+
autoTag = await autoTagDSHProject({ repoPath, version: readPkgVersion(repoPath), commitSha: pr.commitSha, owner: pr.owner, repo: pr.repo, token: pr.token || token });
|
|
289
|
+
} catch (e) {
|
|
290
|
+
autoTag = { ok: false, skipped: 'auto-tag-error', error: String(e?.message || e) };
|
|
291
|
+
}
|
|
292
|
+
const heads = await fetchRemoteHeads({ owner: pr.owner, repo: pr.repo, branch: pr.branch, token: pr.token || token }).catch(() => null);
|
|
293
|
+
// 推送成功后的**硬校验**:远端该分支的 sha 必须等于本次提交 sha。
|
|
294
|
+
// 事故(用户实测):远端仓库为空(API 409 Conflict)时插件仍回「commit+push done」——
|
|
295
|
+
// 成功判定只看「推送动作有没有报错」,没看「远端到底有没有这个提交」,属**假成功**。
|
|
296
|
+
// 这里用 API 查远端 branch 的真实 sha:查不到(空仓/404)或与本地不一致 ⇒ 明确判失败,
|
|
297
|
+
// 并把远端实际状态带回,避免用户以为已入库。
|
|
298
|
+
let verified = null;
|
|
299
|
+
let verifyError = '';
|
|
300
|
+
const pushedSha = String(pr.commitSha || commitSha || '');
|
|
301
|
+
// 独立复核通道:`git ls-remote`(走凭据、不经 API 限流与缓存)。
|
|
302
|
+
// 为什么必须有:判「未落地」是**否定性结论**,而 API 探针会因限流/鉴权/分支名差异给出 403/404——
|
|
303
|
+
// 实测两次误报(一次 403、一次 404),现场推送其实都已成功。否定性结论必须两条通道一致才可下。
|
|
304
|
+
/**
|
|
305
|
+
* 独立复核探针:`git ls-remote`(走凭据、不经 API 限流与缓存)。
|
|
306
|
+
*
|
|
307
|
+
* ⚠️ 必须返回**三态**,不能把「探针失败」与「成功但为空」都压成空串 ——
|
|
308
|
+
* 旧实现正是如此,于是「两路都查不到」被当成「两路一致认定未落地」✗。
|
|
309
|
+
* 用户实测误报原文:「推送未落地:远端查不到分支 main——两条通道一致:API HTTP 404,
|
|
310
|
+
* ls-remote 无该分支;远端可能是空仓库」——而真实成因是**凭据/权限**,不是「未落地」✗。
|
|
311
|
+
*
|
|
312
|
+
* · ok=false ⇒ 探针**失明**(无凭据 / 网络 / 权限)⇒ 不构成任何结论
|
|
313
|
+
* · ok=true, sha='' ⇒ 探针**确实读到仓库**且远端**没有该分支** ⇒ 可作否定证据(空仓/新分支未建)
|
|
314
|
+
* · ok=true, sha=<sha> ⇒ 远端该分支的真实 sha(可正可负比对)
|
|
315
|
+
*/
|
|
316
|
+
const lsRemoteProbe = () => {
|
|
317
|
+
try {
|
|
318
|
+
// ⚠️ 必须带**凭据 env**:私有库上不带凭据的 ls-remote 会静默返回空(HTTPS 下等同 404)——
|
|
319
|
+
// 那会让「第二路证据」失明。故这一路必须复用插件自己的凭据装配(SSH 私钥 / HTTPS askpass):
|
|
320
|
+
// exec.js 的 runGit 是裸 git,只有 wrapped-git.js 的 buildWrappedGitEnv 会注入凭据。
|
|
321
|
+
const out = runGit(['ls-remote', 'origin', branchRef], { cwd: repoPath, env: buildWrappedGitEnv({ workspaceRoot: repoPath }) });
|
|
322
|
+
if (!out || out.ok !== true) {
|
|
323
|
+
return { ok: false, sha: '', err: String(out?.stderr || 'ls-remote 调用失败').trim().slice(0, 200) };
|
|
324
|
+
}
|
|
325
|
+
const line = String(out.stdout || '').split('\n').find((l) => l.trim());
|
|
326
|
+
return { ok: true, sha: line ? line.trim().split(/\s+/)[0] : '' };
|
|
327
|
+
} catch (e) {
|
|
328
|
+
return { ok: false, sha: '', err: String(e?.message || e).slice(0, 200) };
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
/** 兼容旧调用点:只取 sha(空串 = 没取到;**不区分**「失败」与「取到但为空」) */
|
|
332
|
+
const lsRemoteSha = () => lsRemoteProbe().sha;
|
|
333
|
+
try {
|
|
334
|
+
const br = await githubFetch(`/repos/${pr.owner}/${pr.repo}/branches/${encodeURIComponent(branchRef)}`,
|
|
335
|
+
{ token: pr.token || token, method: 'GET' });
|
|
336
|
+
const remoteSha = String(br?.json?.commit?.sha || '');
|
|
337
|
+
// 比对对象是**本次推送所报的 sha**(pr.commitSha):API 通道会在远端新建提交对象,
|
|
338
|
+
// 其 sha 与本地 HEAD 本来就不同(设计如此,见 fetchRemoteBranchRef 注释),
|
|
339
|
+
// 拿本地 HEAD 比对会永远失败。SSH 通道下 pr.commitSha 即本地提交 sha。
|
|
340
|
+
if (remoteSha && (!pushedSha || remoteSha === pushedSha)) {
|
|
341
|
+
verified = true;
|
|
342
|
+
} else if (remoteSha) {
|
|
343
|
+
// API 说「远端有这个分支、但 sha 与本次不符」——**不能据此判失败**:
|
|
344
|
+
// 实测 GitHub 分支接口会返回**滞后值**(推送已成功、ls-remote 已更新,API 仍回上一版 sha ⇒ 假失败)。
|
|
345
|
+
// 故任何"失败"结论都必须两路一致:先 ls-remote 复核,再决定。
|
|
346
|
+
const gitSha = lsRemoteSha();
|
|
347
|
+
if (gitSha && pushedSha && gitSha === pushedSha) {
|
|
348
|
+
verified = true;
|
|
349
|
+
pushSlot.verifyNote = `API 分支接口返回滞后 sha ${remoteSha.slice(0, 7)},ls-remote 复核为 ${gitSha.slice(0, 7)}(与本次一致)——判定为已落地`;
|
|
350
|
+
} else if (gitSha) {
|
|
351
|
+
verified = false;
|
|
352
|
+
verifyError = `远端 ${branchRef} 的 sha:API ${remoteSha.slice(0, 7)} / ls-remote ${gitSha.slice(0, 7)},两者均 ≠ 本次推送的 ${pushedSha.slice(0, 7)}——推送未落地(两路都取到具体 sha,证据充分)`;
|
|
353
|
+
} else {
|
|
354
|
+
// 只有 API 一路有值、ls-remote 没取到 ⇒ **不足以**下否定结论(API 分支接口实测会返回滞后 sha)
|
|
355
|
+
verified = null;
|
|
356
|
+
verifyError = `未能核验远端 ${branchRef}:API 报 sha ${remoteSha.slice(0, 7)}(≠ 本次 ${pushedSha.slice(0, 7)}),但 ls-remote 探针未取到(可能无凭据/网络/限流,或索引延迟)——**不据此判「未落地」**`;
|
|
357
|
+
}
|
|
358
|
+
} else {
|
|
359
|
+
// API 没给 sha:**不据此判失败**(403/404 都可能是探针问题)⇒ 用 ls-remote 三态探针复核。
|
|
360
|
+
const probe = lsRemoteProbe();
|
|
361
|
+
const gitSha = probe.sha;
|
|
362
|
+
if (gitSha && (!pushedSha || gitSha === pushedSha)) {
|
|
363
|
+
verified = true;
|
|
364
|
+
} else if (gitSha) {
|
|
365
|
+
verified = false;
|
|
366
|
+
verifyError = `远端 ${branchRef} 的 sha ${gitSha.slice(0, 7)} ≠ 本次推送的 ${pushedSha.slice(0, 7)}——推送未落地(API HTTP ${br?.status};ls-remote 取到具体 sha,证据充分)`;
|
|
367
|
+
} else if (probe.ok) {
|
|
368
|
+
// 探针**成功返回且为空** ⇒ 确实读到仓库、远端没有该分支 ⇒ 这是**可用的否定证据**(空仓/新分支未建)
|
|
369
|
+
verified = false;
|
|
370
|
+
verifyError = `远端没有分支 ${branchRef}——推送未落地(ls-remote 带凭据成功返回为空;API HTTP ${br?.status})`;
|
|
371
|
+
} else {
|
|
372
|
+
// 关键修复:探针**本身失败**(无凭据/网络/权限)⇒ 只能报「未核验」,**不许**判「未落地」
|
|
373
|
+
// (用户实测误报:旧实现把这里判成失败,输出「远端查不到分支 main(两条通道一致…远端可能是空仓库)」)
|
|
374
|
+
verified = null;
|
|
375
|
+
const dg = classifyPushFailure(String(probe.err || ''), { httpStatus: br?.status });
|
|
376
|
+
verifyError = `未能核验远端 ${branchRef}:API HTTP ${br?.status},ls-remote 探针失败(分类 ${dg.code}:${dg.inference})——推送动作未报错,但结果未经核对;**这不构成「未落地」的证据**|下一步:${dg.nextSteps[0] || ''}`;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
} catch (e) {
|
|
380
|
+
// API 抛异常:仍以 ls-remote 复核,避免把「探针坏了」当成「没推上去」
|
|
381
|
+
const gitSha = lsRemoteSha();
|
|
382
|
+
if (gitSha && (!pushedSha || gitSha === pushedSha)) {
|
|
383
|
+
verified = true;
|
|
384
|
+
pushSlot.verifyNote = `API 校验异常(${String(e?.message || e).slice(0, 60)}),已用 ls-remote 复核为一致`;
|
|
385
|
+
} else if (gitSha) {
|
|
386
|
+
verified = false;
|
|
387
|
+
verifyError = `远端 ${branchRef} 的 sha ${gitSha.slice(0, 7)} ≠ 本次推送的 ${pushedSha.slice(0, 7)}——推送未落地`;
|
|
388
|
+
} else if (lsRemoteProbe().ok) {
|
|
389
|
+
// 探针成功返回且为空 ⇒ 确实没有该分支 ⇒ 可用作否定证据
|
|
390
|
+
verified = false;
|
|
391
|
+
verifyError = `远端没有分支 ${branchRef}——推送未落地(ls-remote 带凭据成功返回为空;API 异常:${String(e?.message || e).slice(0, 60)})`;
|
|
392
|
+
} else {
|
|
393
|
+
// 探针也失明 ⇒ 只报未核验(**不判失败**)
|
|
394
|
+
verifyError = `未能核验远端 ${branchRef}:API 异常(${String(e?.message || e).slice(0, 60)})且 ls-remote 探针失败——推送动作已完成,但结果未经核对;**不据此判「未落地」**`;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
pushSlot.verified = verified;
|
|
398
|
+
if (verifyError) pushSlot.verifyError = verifyError;
|
|
399
|
+
return { push: pushSlot, autoTag, heads };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/* ───────────────────────── 提交推送 ───────────────────────── */
|
|
403
|
+
|
|
404
|
+
/** README 检查提示(提交前核对 README 是否同步)。 */
|
|
405
|
+
export function readmeCheckHint(repoPath) {
|
|
406
|
+
const hasReadme = ['README.md', 'readme.md', 'README', 'readme'].some((n) => existsSync(join(repoPath, n)));
|
|
407
|
+
return hasReadme
|
|
408
|
+
? { needed: true, hasReadme: true, hint: '提交前核对 README:功能表/版本记录/用法与本次改动一致,过时先改 README 再提交' }
|
|
409
|
+
: { needed: true, hasReadme: false, hint: '仓库无 README,提交前先补(可用脚本 `node scripts/readme-gen.mjs <repo> [--write README.md]` 生成,或按 docs/ 文档模板写)' };
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* 手动推送当前分支(账号卡片「本地仓库领先 → 手动 push」入口)。
|
|
414
|
+
* 前置校验:是 git 仓库 + 工作树干净(changed=0)+ 有上游跟踪 + 领先远端(ahead>0),
|
|
415
|
+
* 全过才调 dispatchPush(走配置的推送通道,默认 ssh)。
|
|
416
|
+
* @param {{repoPath?:string, pushMethod?:string}} opts
|
|
417
|
+
* @returns {{ok:boolean, branch?, ahead?, behind?, changed?, pushed?, push?, error?}}
|
|
418
|
+
*/
|
|
419
|
+
export async function pushCurrentBranch({ repoPath = '', pushMethod = 'ssh' } = {}) {
|
|
420
|
+
if (!repoPath || !existsSync(join(repoPath, '.git'))) return { ok: false, error: `非 git 仓库: ${repoPath || '(空)'}` };
|
|
421
|
+
const branch = runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repoPath }).stdout.trim() || '';
|
|
422
|
+
const status = runGit(['status', '--porcelain'], { cwd: repoPath }).stdout;
|
|
423
|
+
const changed = status ? status.split('\n').filter(Boolean).length : 0;
|
|
424
|
+
const up = runGit(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], { cwd: repoPath });
|
|
425
|
+
const upstream = up.ok && up.stdout.trim() ? up.stdout.trim() : '';
|
|
426
|
+
const originUrl = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout.trim();
|
|
427
|
+
// 放宽「必须已 -u 建立上游」——无 @{u} 但有远端同样可推
|
|
428
|
+
// (dispatchPush 走 `git push <远端> HEAD:refs/heads/<分支>`,不依赖上游跟踪)。
|
|
429
|
+
// 领先比较基准 = @{u},否则 origin/<当前分支>;本地无该 ref(未 fetch 过)时
|
|
430
|
+
// ls-remote 一次性对比远端同名分支(单仓库单次网络);远端无同名分支 = 首次推送创建。
|
|
431
|
+
const base = upstream || (originUrl ? `origin/${branch}` : '');
|
|
432
|
+
let ahead = 0, behind = 0, remoteMissing = false, compareFailed = false;
|
|
433
|
+
// 优先 live ls-remote:origin 是 https 时本地 fetch 常失败,origin/<branch> 缓存过期
|
|
434
|
+
// 会把「远端已前走」显示成「领先 N」,点 push 才报分叉。
|
|
435
|
+
const live = originUrl ? liveRemoteHead({ repoPath, branch }) : { ok: false, sha: '' };
|
|
436
|
+
if (live.ok && live.sha) {
|
|
437
|
+
const rcLive = runGit(['rev-list', '--left-right', '--count', `HEAD...${live.sha}`], { cwd: repoPath });
|
|
438
|
+
if (rcLive.ok) {
|
|
439
|
+
const parts = (rcLive.stdout || '').trim().split(/\s+/).map(Number);
|
|
440
|
+
ahead = Number(parts[0]) || 0;
|
|
441
|
+
behind = Number(parts[1]) || 0;
|
|
442
|
+
} else {
|
|
443
|
+
// 远端 sha 本地没有 → 远端有本地未知提交(缓存过期 / 未 fetch)
|
|
444
|
+
return {
|
|
445
|
+
ok: false, ahead, behind, changed,
|
|
446
|
+
error: `远端已有本地没有的提交 ${(live.sha || '').slice(0, 7)}(本地 origin/${branch} 缓存过期)。请先 fetch 整合再推,或确认后 force。`,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
} else if (base) {
|
|
450
|
+
const rc = runGit(['rev-list', '--left-right', '--count', `HEAD...${base}`], { cwd: repoPath });
|
|
451
|
+
if (rc.ok) {
|
|
452
|
+
const parts = (rc.stdout || '').trim().split(/\s+/).map(Number);
|
|
453
|
+
ahead = Number(parts[0]) || 0;
|
|
454
|
+
behind = Number(parts[1]) || 0;
|
|
455
|
+
} else {
|
|
456
|
+
compareFailed = true;
|
|
457
|
+
}
|
|
458
|
+
} else compareFailed = true;
|
|
459
|
+
if (live.ok && !live.sha) remoteMissing = true;
|
|
460
|
+
// 修正:「工作树未提交改动」不再是 push 的拦截条件——git push 推的是**已提交**
|
|
461
|
+
// 内容,工作树脏不脏不影响本次推送(新改动仍留在本地,下次提交再推)。原实现
|
|
462
|
+
// `if (changed > 0) return 先提交再推送` 把「有领先提交但工作树也脏」的仓库拦死;
|
|
463
|
+
// 真正决定可推与否的是下方 ahead>0(有未推送的提交)。
|
|
464
|
+
if (!originUrl) return { ok: false, ahead, behind, changed, error: '仓库无远端 origin,无法推送' };
|
|
465
|
+
if (compareFailed) return { ok: false, ahead, behind, changed, error: '无法确认远端状态(本地未 fetch 且 ls-remote 失败)——请先 git fetch 或检查网络' };
|
|
466
|
+
if (ahead <= 0) return { ok: false, ahead, behind, changed, error: '当前分支未领先远端(没有可推送的新提交)' };
|
|
467
|
+
if (behind > 0) return { ok: false, ahead, behind, changed, error: `本地与远端分叉(本地领先 ${ahead},远端领先 ${behind})——先 pull 合并远端提交再推送` };
|
|
468
|
+
const push = await dispatchPush({ repoPath, branch, pushMethod });
|
|
469
|
+
return { ok: push.ok === true, branch, ahead, behind, changed, pushed: push.pushed, push, error: push.error || push.reason };
|
|
470
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub remote 自动判定与修正(推送前调用)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要:推送链路此前**到处假设 `origin`**(`remote get-url origin` / `push origin`),
|
|
5
|
+
* 一旦 ① `origin` 不存在、② `origin` 指向别人的仓库、③ 用了本机不通的 URL 形态
|
|
6
|
+
* (如 `git@github.com:owner/repo.git` 走 22 端口),推送就会失败或推错地方。
|
|
7
|
+
* 本模块给出统一判定:**归属对(owner/repo 与目标一致)+ 本机可用形态(ssh:443 优先)+ 名字稳定**,
|
|
8
|
+
* 必要时自动 `remote set-url` / `remote add`,并在回执里说明做了什么(dryRun 只报告不写盘)。
|
|
9
|
+
*
|
|
10
|
+
* 判定口径(都是可复核的事实,不猜网络):
|
|
11
|
+
* · 归属:remote URL 解析出的 owner/repo 必须与目标一致;
|
|
12
|
+
* · 形态:优先 `ssh://git@ssh.github.com:443/<owner>/<repo>.git`(本机实测可用通道),
|
|
13
|
+
* 其次保留既有形态(如 https —— 带 token 的 https 也能推,取决于 pushMethod);
|
|
14
|
+
* · 名字:同分候选按 `origin` > `github-ssh` > 其它 取名,避免每次推送换名字。
|
|
15
|
+
*/
|
|
16
|
+
import { runGit } from './exec.js';
|
|
17
|
+
|
|
18
|
+
/** GitHub URL 解析(兼容 https / git@ / ssh:443 / 裸域名四种写法)。 */
|
|
19
|
+
const GH_RE = /^(?:https?:\/\/|ssh:\/\/)?(?:[^@/\s]+@)?(?:ssh\.)?github\.com(?::\d+)?[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i;
|
|
20
|
+
|
|
21
|
+
/** 解析 GitHub remote URL ⇒ { owner, repo, form };非 GitHub 返回 null。 */
|
|
22
|
+
export function parseGithubUrl(url = '') {
|
|
23
|
+
const s = String(url || '').trim();
|
|
24
|
+
const m = s.match(GH_RE);
|
|
25
|
+
if (!m) return null;
|
|
26
|
+
const ssh443 = /^ssh:\/\/[^/]*ssh\.github\.com:443\//i.test(s);
|
|
27
|
+
const https = /^https?:\/\//i.test(s);
|
|
28
|
+
const scp = /^[^/]+@(?:ssh\.)?github\.com:/i.test(s);
|
|
29
|
+
return { owner: m[1], repo: m[2], form: ssh443 ? 'ssh443' : (https ? 'https' : (scp ? 'scp' : 'other')) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 本机推荐形态(实测通道):ssh.github.com:443。 */
|
|
33
|
+
export function ssh443Url(owner, repo) {
|
|
34
|
+
return `ssh://git@ssh.github.com:443/${owner}/${repo}.git`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** https 形态(API/token 通道用)。 */
|
|
38
|
+
export function httpsUrl(owner, repo) {
|
|
39
|
+
return `https://github.com/${owner}/${repo}.git`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 列出全部 remote:{ name: { fetch, push } }。 */
|
|
43
|
+
export function listRemotes(repoPath = '') {
|
|
44
|
+
const r = runGit(['remote', '-v'], { cwd: repoPath });
|
|
45
|
+
const out = r && r.ok ? String(r.stdout || '') : '';
|
|
46
|
+
const map = {};
|
|
47
|
+
for (const line of out.split('\n')) {
|
|
48
|
+
const m = line.match(/^(\S+)\s+(\S+)\s+\((fetch|push)\)\s*$/);
|
|
49
|
+
if (!m) continue;
|
|
50
|
+
map[m[1]] = map[m[1]] || {};
|
|
51
|
+
map[m[1]][m[3]] = m[2];
|
|
52
|
+
}
|
|
53
|
+
return map;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 候选 remote 评分:归属对 + 形态可用 + 名字稳定(分数越大越优先)。 */
|
|
57
|
+
export function scoreRemote(cand = {}, { owner = '', repo = '', preferSsh443 = true } = {}) {
|
|
58
|
+
let score = 0;
|
|
59
|
+
const reasons = [];
|
|
60
|
+
const hasTarget = !!(owner && repo);
|
|
61
|
+
const sameOwner = owner && String(cand.owner).toLowerCase() === String(owner).toLowerCase();
|
|
62
|
+
const sameRepo = repo && String(cand.repo).toLowerCase() === String(repo).toLowerCase();
|
|
63
|
+
if (!hasTarget) {
|
|
64
|
+
// 未提供目标 owner/repo(如"就着现有 remote 推")⇒ 不判归属,只按形态与名字择优
|
|
65
|
+
reasons.push('未提供目标归属 ⇒ 只按形态/名字择优');
|
|
66
|
+
} else if (sameOwner && sameRepo) {
|
|
67
|
+
score += 100; reasons.push('归属一致(+100)');
|
|
68
|
+
} else {
|
|
69
|
+
score -= 100; reasons.push(`归属不一致(${cand.owner}/${cand.repo})`);
|
|
70
|
+
}
|
|
71
|
+
if (preferSsh443) {
|
|
72
|
+
if (cand.form === 'ssh443') { score += 30; reasons.push('形态 ssh:443(+30)'); }
|
|
73
|
+
else if (cand.form === 'scp') { score -= 20; reasons.push('形态 scp:22(本机不通)(-20)'); }
|
|
74
|
+
else { score += 5; reasons.push(`形态 ${cand.form}(+5)`); }
|
|
75
|
+
}
|
|
76
|
+
const nameScore = cand.name === 'origin' ? 10 : cand.name === 'github-ssh' ? 8 : 0;
|
|
77
|
+
score += nameScore;
|
|
78
|
+
if (nameScore) reasons.push(`名字 ${cand.name}(+${nameScore})`);
|
|
79
|
+
return { score, reasons };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 判定「正确的 GitHub remote」并(按需)修正。
|
|
84
|
+
* @param {object} o { repoPath, owner, repo, preferSsh443=true, dryRun=false }
|
|
85
|
+
* @returns {{ok:boolean, remote?:string, url?:string, action?:'keep'|'fixed'|'added', reasons:string[], candidates:Array}}
|
|
86
|
+
*/
|
|
87
|
+
export function resolveGithubRemote({ repoPath = '', owner = '', repo = '', preferSsh443 = true, dryRun = false } = {}) {
|
|
88
|
+
const remotes = listRemotes(repoPath);
|
|
89
|
+
const candidates = Object.entries(remotes)
|
|
90
|
+
.map(([name, u]) => {
|
|
91
|
+
const url = u.push || u.fetch || '';
|
|
92
|
+
const p = parseGithubUrl(url);
|
|
93
|
+
return p ? { name, url, ...p } : null;
|
|
94
|
+
})
|
|
95
|
+
.filter(Boolean);
|
|
96
|
+
if (!candidates.length) {
|
|
97
|
+
if (!(owner && repo)) {
|
|
98
|
+
return { ok: false, action: 'none', reasons: ['没有 GitHub remote,且未提供 owner/repo ⇒ 无法判定'], candidates: [] };
|
|
99
|
+
}
|
|
100
|
+
const url = preferSsh443 ? ssh443Url(owner, repo) : httpsUrl(owner, repo);
|
|
101
|
+
// 不覆盖「已有但归属不符」的 origin——那可能是别人的仓库/别的项目(不做静默改址)
|
|
102
|
+
// 本分支里 candidates 为空 ⇒ 既有 origin 一定是非 GitHub 形态(如内网 gitlab)⇒ 一律视为「不是我们的」
|
|
103
|
+
const originIsForeign = !!remotes['origin'];
|
|
104
|
+
const name = (!remotes['origin'] || originIsForeign) ? 'github-ssh' : 'origin';
|
|
105
|
+
const existed = !!remotes[name];
|
|
106
|
+
if (!dryRun) {
|
|
107
|
+
if (existed) runGit(['remote', 'set-url', name, url], { cwd: repoPath });
|
|
108
|
+
else runGit(['remote', 'add', name, url], { cwd: repoPath });
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
ok: true, remote: name, url, action: existed ? 'fixed' : 'added',
|
|
112
|
+
reasons: [`缺少指向 ${owner}/${repo} 的 remote ⇒ ${existed ? 'set-url' : 'add'} ${name} → ${url}${dryRun ? '(dryRun 未写盘)' : ''}${originIsForeign ? ';origin 归属不符,未改动它' : ''}`],
|
|
113
|
+
candidates,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const scored = candidates
|
|
117
|
+
.map((c) => ({ ...c, ...scoreRemote(c, { owner, repo, preferSsh443 }) }))
|
|
118
|
+
.sort((a, b) => (b.score - a.score) || (a.name === 'origin' ? -1 : 1));
|
|
119
|
+
const best = scored[0];
|
|
120
|
+
// 「有 remote,但没有一个属于目标仓库」必须与「完全没有 remote」同样处理:
|
|
121
|
+
// 新建/修正专用 github-ssh,**绝不覆盖别人的 remote**(此前漏了这一支,会把 origin 指向别人的仓库 ✗)。
|
|
122
|
+
const ours = (owner && repo) ? scored.filter((c) => c.score >= 100) : scored;
|
|
123
|
+
if (!ours.length) {
|
|
124
|
+
const url = preferSsh443 ? ssh443Url(owner, repo) : httpsUrl(owner, repo);
|
|
125
|
+
const name = 'github-ssh'; // origin 已属于别人/别的项目 ⇒ 不动它
|
|
126
|
+
const existed = !!remotes[name];
|
|
127
|
+
if (!dryRun) {
|
|
128
|
+
if (existed) runGit(['remote', 'set-url', name, url], { cwd: repoPath });
|
|
129
|
+
else runGit(['remote', 'add', name, url], { cwd: repoPath });
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
ok: true, remote: name, url, action: existed ? 'fixed' : 'added',
|
|
133
|
+
reasons: [`没有指向 ${owner}/${repo} 的 remote(现有 ${best.name} → ${best.url} 归属不符)⇒ ${existed ? 'set-url' : 'add'} ${name} → ${url}${dryRun ? '(dryRun 未写盘)' : ''};未改动其它 remote`],
|
|
134
|
+
candidates: scored,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const hit = ours[0];
|
|
138
|
+
const reasons = [`命中 ${hit.name} → ${hit.url}(评分 ${hit.score}:${hit.reasons.join(' ')})`];
|
|
139
|
+
const needUrl = preferSsh443 && hit.form !== 'ssh443' && owner && repo ? ssh443Url(hit.owner, hit.repo) : '';
|
|
140
|
+
if (needUrl && needUrl !== hit.url) {
|
|
141
|
+
if (!dryRun) runGit(['remote', 'set-url', hit.name, needUrl], { cwd: repoPath });
|
|
142
|
+
reasons.push(`形态不推荐(${hit.form})⇒ set-url ${hit.name} → ${needUrl}${dryRun ? '(dryRun 未写盘)' : ''}`);
|
|
143
|
+
return { ok: true, remote: hit.name, url: needUrl, action: 'fixed', reasons, candidates: scored };
|
|
144
|
+
}
|
|
145
|
+
return { ok: true, remote: hit.name, url: hit.url, action: 'keep', reasons, candidates: scored };
|
|
146
|
+
}
|