dsh-git-push 2.15.3 → 2.16.1
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/lib/app/command-registry.js +1 -0
- package/lib/app/tool-call.js +18 -2
- package/lib/git/index.js +2 -2
- package/lib/git/init-compat.js +45 -1
- package/lib/git/remote.js +51 -16
- package/lib/git/transport.js +36 -0
- package/lib/npm/local-registry.js +25 -1
- package/lib/npm/publish.js +9 -3
- package/lib/npm/smoke.js +51 -0
- package/lib/self/index.js +1 -1
- package/package.json +1 -1
|
@@ -93,6 +93,7 @@ export const TOOL_REGISTRY = [
|
|
|
93
93
|
params: [
|
|
94
94
|
{ flag: 'repo', type: 'string', positional: 0, required: true, desc: '本地 git 仓库绝对路径' },
|
|
95
95
|
{ flag: 'visibility', type: 'string', enum: ['public', 'private'], default: 'private', desc: '可见性' },
|
|
96
|
+
{ flag: 'pushInitial', type: 'boolean', desc: '建仓后做首次推送(本地无提交时先本地提交,再走 Git Data API 上传;CIFS 上不需 git remote add)' },
|
|
96
97
|
{ flag: 'dryRun', type: 'boolean', desc: '只探测预演' },
|
|
97
98
|
],
|
|
98
99
|
},
|
package/lib/app/tool-call.js
CHANGED
|
@@ -18,6 +18,7 @@ import { auditWithScope, auditFull, summarize, isBlockerFinding } from '../audit
|
|
|
18
18
|
import { formatAnalysisCoverageLine } from '../audit/analysis-coverage.js';
|
|
19
19
|
import { scoreQuality } from '../score/index.js';
|
|
20
20
|
import {
|
|
21
|
+
pushInitialContent,
|
|
21
22
|
cloneViaApi, previewClone, resolveMaxCloneFileMB, ensureRemoteRepo, setVisibility, renameRepo, maintainRepoIndex, updateRepoIndex, resolveToken, commitAndPush,
|
|
22
23
|
scanReposAsync, scanRepos, checkGithubAccount, formatGithubAccountBlock, generateSshKey, persistSshPub,
|
|
23
24
|
refreshAccountStatus,
|
|
@@ -597,9 +598,24 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
|
|
|
597
598
|
}
|
|
598
599
|
case 'npm_publish':
|
|
599
600
|
return callNpmPublishJob(args, jobs, exec, log, env, cfg);
|
|
600
|
-
case 'git_remote_create':
|
|
601
|
+
case 'git_remote_create': {
|
|
601
602
|
if (!args.repo) return { ok: false, error: MSG_REPO_REQUIRED };
|
|
602
|
-
|
|
603
|
+
const created = await ensureRemoteRepo({ repoPath: args.repo, visibility: args.visibility || 'private', dryRun: args.dryRun === true });
|
|
604
|
+
// 可选:建仓后做「首次推送」——本地还没提交就先提交,再走 Git Data API 上传。
|
|
605
|
+
// CIFS 上这一整条链不依赖 `git remote add/config`(那些会 chmod 失败),
|
|
606
|
+
// 只有 add/commit 两次本地写,实测在 smb2 挂载上可用。
|
|
607
|
+
if (args.pushInitial === true && created.ok && created.dryRun !== true) {
|
|
608
|
+
const push = await pushInitialContent({ repoPath: args.repo, branch: args.branch || '', token: '' });
|
|
609
|
+
return {
|
|
610
|
+
...created,
|
|
611
|
+
initialPush: {
|
|
612
|
+
ok: push.ok === true, pushed: push.pushed === true, committed: push.committed === true,
|
|
613
|
+
reason: push.reason || '', remoteSha: push.remoteSha || push.commitSha || '',
|
|
614
|
+
},
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
return created;
|
|
618
|
+
}
|
|
603
619
|
case 'git_identity_rewrite':
|
|
604
620
|
// 提交身份历史改写:默认 dryRun 只报告,真改写要先 dryRun:false/write,推送要 push:true
|
|
605
621
|
return callIdentityRewrite(args, env, cfg);
|
package/lib/git/index.js
CHANGED
|
@@ -28,10 +28,10 @@ export { GH_API, githubFetch, parseGithubOwnerRepo, isBadCredentials, detectRepo
|
|
|
28
28
|
export { resolveRepoVisibility } from './visibility.js';
|
|
29
29
|
export { scanSensitiveFiles } from './sensitive.js';
|
|
30
30
|
export { DEFAULT_IGNORE_PATTERNS, ensureGitignore } from './ignore.js';
|
|
31
|
-
export { fetchRemoteHeads, dispatchPush, pushViaSsh, pushViaApi, sshReason, isNonFastForward, liveRemoteHead, liveRemoteHeadAsync } from './transport.js';
|
|
31
|
+
export { fetchRemoteHeads, dispatchPush, pushViaSsh, pushViaApi, pushInitialContent, sshReason, isNonFastForward, liveRemoteHead, liveRemoteHeadAsync } from './transport.js';
|
|
32
32
|
export { readmeCheckHint, commitAndPush, pushCurrentBranch } from './push.js';
|
|
33
33
|
export { cloneViaApi, previewClone, resolveMaxCloneFileMB, isPartialCloneDir } from './clone.js';
|
|
34
|
-
export { ensureRemoteRepo, setVisibility } from './remote.js';
|
|
34
|
+
export { ensureRemoteRepo, setVisibility, prepareLocalRepoForRemote } from './remote.js';
|
|
35
35
|
export { renameRepo } from './rename.js';
|
|
36
36
|
export { scanRepos, scanReposAsync, collectRepoPaths, describeRepo, describeRepoAsync, maskRemoteUrl } from './repos.js';
|
|
37
37
|
export { browseDir } from './browse.js';
|
package/lib/git/init-compat.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* 因此降级路径 = 手写 `.git/{HEAD,config}` + 空 `objects/refs/info` 目录,绕开 git 的
|
|
23
23
|
* config 写入流程;config 里预先写死 `filemode = false`。
|
|
24
24
|
*/
|
|
25
|
-
import { existsSync, mkdirSync, writeFileSync, chmodSync, rmSync } from 'node:fs';
|
|
25
|
+
import { existsSync, mkdirSync, writeFileSync, chmodSync, rmSync, realpathSync } from 'node:fs';
|
|
26
26
|
import { join } from 'node:path';
|
|
27
27
|
import { runGit } from './exec.js';
|
|
28
28
|
|
|
@@ -112,6 +112,50 @@ export function initRepoCompat(dir, { branch = 'master', remoteUrl = '', chmodOk
|
|
|
112
112
|
}
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
+
/**
|
|
116
|
+
* 现有 .git 是否**真的可用**(不是"目录存在"就算)。
|
|
117
|
+
*
|
|
118
|
+
* 为什么必须实测:CIFS/SMB 上 `git init` 会在写 config 时 chmod 失败而**半途退出**——
|
|
119
|
+
* 留下 `.git/{config,description,hooks,info}` 却**没有 HEAD/objects/refs**。
|
|
120
|
+
* 此时 `existsSync('.git')` 为真,但 `git remote add` 直接报「not a git repository」。
|
|
121
|
+
* 历史实现正是拿 existsSync 当判据,于是「建仓成功、origin 没设上」还报成功。
|
|
122
|
+
*/
|
|
123
|
+
export function isUsableRepo(dir) {
|
|
124
|
+
const r = runGit(['rev-parse', '--git-dir'], { cwd: dir });
|
|
125
|
+
if (!r || !r.ok) return false;
|
|
126
|
+
// 必须确认「这个目录本身」就是仓库根:git 会向上层目录找仓库,
|
|
127
|
+
// 若目标目录位于某个父仓库内部(如插件里的临时目录),
|
|
128
|
+
// `rev-parse --git-dir` 同样成功 —— 会把它误判成"已有仓库"从而跳过初始化(实测踩过)。
|
|
129
|
+
const top = runGit(['rev-parse', '--show-toplevel'], { cwd: dir });
|
|
130
|
+
if (!top || !top.ok) return false;
|
|
131
|
+
const real = (p) => { try { return realpathSync.native(p); } catch { return p; } };
|
|
132
|
+
return real(String(top.stdout || '').trim() || dir) === real(dir);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 确保目录里有一个**可用**的本地 git 仓库(CIFS 安全)。
|
|
137
|
+
*
|
|
138
|
+
* 三种情形:
|
|
139
|
+
* · 已可用 → action:'keep'(不动它,避免覆盖用户既有配置)
|
|
140
|
+
* · 有残缺 .git(半途而废)→ action:'repair'(走 initRepoCompat 补全/重写)
|
|
141
|
+
* · 没有 .git → action:'create'
|
|
142
|
+
*
|
|
143
|
+
* @param {string} dir 工作树目录
|
|
144
|
+
* @param {{branch?:string, remoteUrl?:string, remoteName?:string, chmodOk?:boolean,
|
|
145
|
+
* gitInit?:Function}} [opts]
|
|
146
|
+
* remoteUrl 给出时,降级路径会把 remote 段一并写进 config —— 因为 `git remote add`
|
|
147
|
+
* 同样是写 config,在 CIFS 上一样会 chmod 失败(实测)。
|
|
148
|
+
* @returns {{ok:boolean, action:'keep'|'repair'|'create'|'failed', via:string, filemode:?boolean, stderr?:string}}
|
|
149
|
+
*/
|
|
150
|
+
export function ensureUsableLocalRepo(dir, { branch = 'master', remoteUrl = '', remoteName = 'origin', chmodOk, gitInit } = {}) {
|
|
151
|
+
const exec = typeof gitInit === 'function' ? gitInit : (args, opts) => runGit(args, opts);
|
|
152
|
+
if (isUsableRepo(dir)) return { ok: true, action: 'keep', via: 'existing', filemode: null };
|
|
153
|
+
const hadPartial = hasGitDir(dir);
|
|
154
|
+
const r = initRepoCompat(dir, { branch, remoteUrl, remoteName, chmodOk, gitInit: exec });
|
|
155
|
+
if (!r.ok) return { ok: false, action: 'failed', via: r.via, filemode: r.filemode, stderr: r.stderr };
|
|
156
|
+
return { ok: true, action: hadPartial ? 'repair' : 'create', via: r.via, filemode: r.filemode };
|
|
157
|
+
}
|
|
158
|
+
|
|
115
159
|
/** .git 目录是否已存在(续跑判断:已 init 过就不再重复写)。 */
|
|
116
160
|
export function hasGitDir(dir) {
|
|
117
161
|
return existsSync(join(dir, '.git'));
|
package/lib/git/remote.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { existsSync } from 'node:fs';
|
|
8
8
|
import { basename, join } from 'node:path';
|
|
9
9
|
import { githubFetch } from './api.js';
|
|
10
|
+
import { ensureUsableLocalRepo } from './init-compat.js';
|
|
10
11
|
import { resolveToken } from './credentials.js';
|
|
11
12
|
import { runGit } from './exec.js';
|
|
12
13
|
|
|
@@ -34,19 +35,43 @@ function isApiFormOrigin(url) {
|
|
|
34
35
|
* —— 这样用旧版建过仓的仓库不用手工修。
|
|
35
36
|
* @returns {{action:'add'|'repair'|'keep', url:string, from?:string}}
|
|
36
37
|
*/
|
|
37
|
-
|
|
38
|
+
/**
|
|
39
|
+
* 确保「本地仓库可用 + origin 指向该 GitHub 仓库」,两者都按实际情况回报。
|
|
40
|
+
*
|
|
41
|
+
* 历史缺陷(CIFS 上必现):老实现只判 `existsSync('.git')` 就调 `git remote add`。
|
|
42
|
+
* CIFS/SMB 上 `git init` 会在写 config 时 chmod 失败而半途退出 —— 留下没有 HEAD/objects
|
|
43
|
+
* 的残缺 `.git`;于是 `remote add` 报「not a git repository」,而函数**仍返回 action:'add'**,
|
|
44
|
+
* 调用方据此报「建仓成功」,用户以为好了、其实本地根本不能用。
|
|
45
|
+
*
|
|
46
|
+
* 现在:先 ensureUsableLocalRepo(CIFS 安全 init,与 clone 用的同一套),再校验 origin;
|
|
47
|
+
* 任何一步失败都带 error 返回,不再谎报。
|
|
48
|
+
* @returns {{ok:boolean, action:'create'|'repair'|'keep'|'add'|'failed',
|
|
49
|
+
* url:string, localRepo:object, error?:string}}
|
|
50
|
+
*/
|
|
51
|
+
export function prepareLocalRepoForRemote(repoPath, ownerName, name, { branch = 'main' } = {}) {
|
|
38
52
|
const gitUrl = `${GH_WEB}/${ownerName}/${name}`;
|
|
53
|
+
const local = ensureUsableLocalRepo(repoPath, { branch, remoteUrl: gitUrl });
|
|
54
|
+
if (!local.ok) {
|
|
55
|
+
return { ok: false, action: 'failed', url: gitUrl, localRepo: local, error: `本地仓库不可用:${local.stderr || '初始化失败'}` };
|
|
56
|
+
}
|
|
39
57
|
const cur = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath });
|
|
40
58
|
if (!cur.ok) {
|
|
41
|
-
runGit(['remote', 'add', 'origin', gitUrl], { cwd: repoPath });
|
|
42
|
-
return {
|
|
59
|
+
const add = runGit(['remote', 'add', 'origin', gitUrl], { cwd: repoPath });
|
|
60
|
+
return {
|
|
61
|
+
ok: !!add.ok, action: add.ok ? 'add' : 'failed', url: gitUrl, localRepo: local,
|
|
62
|
+
...(add.ok ? {} : { error: `设置 origin 失败:${String(add.stderr || '').slice(0, 200)}` }),
|
|
63
|
+
};
|
|
43
64
|
}
|
|
44
65
|
const existing = String(cur.stdout || cur.stderr || '').trim();
|
|
45
66
|
if (isApiFormOrigin(existing)) {
|
|
46
|
-
runGit(['remote', 'set-url', 'origin', gitUrl], { cwd: repoPath });
|
|
47
|
-
return {
|
|
67
|
+
const set = runGit(['remote', 'set-url', 'origin', gitUrl], { cwd: repoPath });
|
|
68
|
+
return {
|
|
69
|
+
// 动作名沿用既有语义 'repair'(把 API 形态 origin 修回 git 形态)——测试与外部消费方都按这个名字判断
|
|
70
|
+
ok: !!set.ok, action: set.ok ? 'repair' : 'failed', url: gitUrl, localRepo: local, from: existing,
|
|
71
|
+
...(set.ok ? {} : { error: `修正 origin 失败:${String(set.stderr || '').slice(0, 200)}` }),
|
|
72
|
+
};
|
|
48
73
|
}
|
|
49
|
-
return { action: 'keep', url: existing };
|
|
74
|
+
return { ok: true, action: 'keep', url: existing, localRepo: local };
|
|
50
75
|
}
|
|
51
76
|
|
|
52
77
|
/** 建仓(POST /user/repos)并设置 origin。dryRun 只探测不创建。 */
|
|
@@ -82,20 +107,30 @@ export async function ensureRemoteRepo({ repoPath = '', owner = '', visibility =
|
|
|
82
107
|
if (exists.status === 200) {
|
|
83
108
|
// 仓库已存在也要**确保 origin 可用**(原来这里直接 return,不碰 origin ⇒ 本地缺 origin 或
|
|
84
109
|
// 是旧版写下的 API 形态时会一直坏着)。
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
110
|
+
// 已存在也要确保本地可用 + origin 正确(原实现只要 existsSync('.git') 就往下走,CIFS 上会静默失败)
|
|
111
|
+
const prep = repoPath ? prepareLocalRepoForRemote(repoPath, ownerName, name) : null;
|
|
112
|
+
return {
|
|
113
|
+
ok: true, exists: true, owner: ownerName, name, visibility: vis, reason: '已存在同名仓库',
|
|
114
|
+
origin: `${GH_WEB}/${ownerName}/${name}`,
|
|
115
|
+
originAction: prep ? prep.action : 'skip',
|
|
116
|
+
originOk: prep ? prep.ok : false,
|
|
117
|
+
localRepo: prep ? prep.localRepo : null,
|
|
118
|
+
...(prep && !prep.ok ? { warning: prep.error } : {}),
|
|
119
|
+
};
|
|
90
120
|
}
|
|
91
121
|
if (dryRun) return { ok: true, dryRun: true, wouldCreate: true, owner: ownerName, name, visibility: vis };
|
|
92
122
|
const created = await githubFetch('/user/repos', { token: tok, method: 'POST', body: { name, private: vis === 'private' } });
|
|
93
123
|
if (created.status !== 201) return { ok: false, error: created.json?.message || created.error || `创建失败: HTTP ${created.status}` };
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
124
|
+
// 建仓后:确保本地仓库可用(CIFS 安全 init)+ origin 指向它;失败如实回报
|
|
125
|
+
const prep = repoPath ? prepareLocalRepoForRemote(repoPath, ownerName, name) : null;
|
|
126
|
+
return {
|
|
127
|
+
ok: true, created: true, owner: ownerName, name, visibility: vis,
|
|
128
|
+
origin: prep ? prep.url : `${GH_WEB}/${ownerName}/${name}`,
|
|
129
|
+
originAction: prep ? prep.action : 'skip',
|
|
130
|
+
originOk: prep ? prep.ok : false,
|
|
131
|
+
localRepo: prep ? prep.localRepo : null,
|
|
132
|
+
...(prep && !prep.ok ? { warning: prep.error } : {}),
|
|
133
|
+
};
|
|
99
134
|
}
|
|
100
135
|
|
|
101
136
|
/** 从本地仓库 origin remote 解析 owner/repo(支持 api.github.com/repos/、github.com、ssh:// 三格式)。 */
|
package/lib/git/transport.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
import { join } from 'node:path';
|
|
15
15
|
import { githubFetch, isBadCredentials, parseGithubOwnerRepo } from './api.js';
|
|
16
16
|
import { resolveSshKey, resolveSshKeys, resolveToken } from './credentials.js';
|
|
17
|
+
import { resolveCommitIdentity } from './identity.js';
|
|
17
18
|
import { gitRaw, runGit, runGitAsync } from './exec.js';
|
|
18
19
|
// 「推送到 GitHub 时自动指定正确的 remote」:归属 + 本机可用形态(ssh:443)+ 名字优先级统一判定
|
|
19
20
|
import { resolveGithubRemote, parseGithubUrl } from './remote-resolve.js';
|
|
@@ -299,6 +300,41 @@ async function apiOrFallback(api, repoPath, branch, res) {
|
|
|
299
300
|
* token 401 → pushViaSsh 回退。
|
|
300
301
|
* @returns {{ok, pushed, method?, commitSha?, reason?, branchAdjusted?}}
|
|
301
302
|
*/
|
|
303
|
+
/**
|
|
304
|
+
* 首次推送:**本地还没有提交时**先做一次本地提交,再走 Git Data API 上传。
|
|
305
|
+
*
|
|
306
|
+
* 为什么需要:`pushViaApi` 以本地提交为输入(rev-parse HEAD / ls-tree / cat-file),
|
|
307
|
+
* 新建的仓库一个提交都没有 ⇒ 直接调它只会得到「本地无提交」。
|
|
308
|
+
* 而 CIFS/SMB 上恰好「本地提交」这件事需要 CIFS 安全 init 才能成立(见 init-compat.js)。
|
|
309
|
+
*
|
|
310
|
+
* 身份:优先用仓库已配置的 user.name/email;缺失时按 `-c` 临时给出(**不写 config**,
|
|
311
|
+
* 因为写 config 在 CIFS 上会 chmod 失败)。
|
|
312
|
+
* @returns {Promise<object>} pushViaApi 的返回,附加 committed 字段说明本次是否新做了提交
|
|
313
|
+
*/
|
|
314
|
+
export async function pushInitialContent({
|
|
315
|
+
repoPath = '', branch = '', token = '', message = 'init: 初始提交(dsh-git-push)', remote = '',
|
|
316
|
+
} = {}) {
|
|
317
|
+
const head = runGit(['rev-parse', 'HEAD'], { cwd: repoPath });
|
|
318
|
+
let committed = false;
|
|
319
|
+
if (!head.ok || !String(head.stdout || '').trim()) {
|
|
320
|
+
const readCfg = (key) => {
|
|
321
|
+
const r = runGit(['config', key], { cwd: repoPath });
|
|
322
|
+
return r && r.ok ? String(r.stdout || '').trim() : '';
|
|
323
|
+
};
|
|
324
|
+
const ident = resolveCommitIdentity({ configName: readCfg('user.name'), configEmail: readCfg('user.email') });
|
|
325
|
+
const idArgs = ident.complete ? [] : ['-c', `user.name=${ident.name}`, '-c', `user.email=${ident.email}`];
|
|
326
|
+
const add = runGit(['add', '-A'], { cwd: repoPath });
|
|
327
|
+
if (!add.ok) return { ok: false, pushed: false, committed: false, reason: `git add 失败:${String(add.stderr || '').slice(0, 300)}` };
|
|
328
|
+
const commit = runGit([...idArgs, 'commit', '-m', message], { cwd: repoPath });
|
|
329
|
+
if (!commit.ok && !/nothing to commit|no changes added/i.test(String(commit.stderr || ''))) {
|
|
330
|
+
return { ok: false, pushed: false, committed: false, reason: `git commit 失败:${String(commit.stderr || '').slice(0, 300)}` };
|
|
331
|
+
}
|
|
332
|
+
committed = !!commit.ok;
|
|
333
|
+
}
|
|
334
|
+
const r = await pushViaApi({ repoPath, branch, token, remote });
|
|
335
|
+
return { ...r, committed };
|
|
336
|
+
}
|
|
337
|
+
|
|
302
338
|
export async function pushViaApi({ repoPath = '', branch = '', token = '', force = false, remote = '' } = {}) {
|
|
303
339
|
const rr = resolveGithubRemote({ repoPath });
|
|
304
340
|
const origin = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout;
|
|
@@ -171,7 +171,9 @@ export async function startLocalRegistry({ storeDir, port = 0 } = {}) {
|
|
|
171
171
|
* @param {{dir:string, tag?:string, packageName?:string, entrySpecs?:string[], timeoutMs?:number}} o
|
|
172
172
|
* @returns {Promise<{ok:boolean, steps:object[], failures:string[], packument?:object}>}
|
|
173
173
|
*/
|
|
174
|
-
export async function runLocalPreview({
|
|
174
|
+
export async function runLocalPreview({
|
|
175
|
+
dir, tag = 'beta', packageName = '', entrySpecs = [], bins = [], expectedVersion = '', timeoutMs = 300000,
|
|
176
|
+
} = {}) {
|
|
175
177
|
const steps = [];
|
|
176
178
|
const failures = [];
|
|
177
179
|
const reg = await startLocalRegistry();
|
|
@@ -201,12 +203,34 @@ export async function runLocalPreview({ dir, tag = 'beta', packageName = '', ent
|
|
|
201
203
|
steps.push({ step: 'install', ok: inst.code === 0 });
|
|
202
204
|
if (inst.code !== 0) { failures.push(`npm install(本地 registry)失败:${(inst.err || inst.out).slice(-400)}`); return { ok: false, steps, failures }; }
|
|
203
205
|
|
|
206
|
+
// ① 库入口:按 exports/main 逐个 import
|
|
204
207
|
if (entrySpecs.length) {
|
|
205
208
|
const script = `for (const s of ${JSON.stringify(entrySpecs)}) { await import(s); }\nconsole.log('ok');\n`;
|
|
206
209
|
const probe = await run(process.execPath, ['--input-type=module', '-e', script], { cwd: consumer, env, timeoutMs });
|
|
207
210
|
steps.push({ step: 'import', ok: probe.code === 0, specs: entrySpecs });
|
|
208
211
|
if (probe.code !== 0) failures.push(`从本地 registry 安装后加载失败:${(probe.err || '').slice(0, 400)}`);
|
|
209
212
|
}
|
|
213
|
+
// ② bin 入口:**真跑一次**(纯 CLI 包唯一有效的验证方式)。
|
|
214
|
+
// 为什么不能只 import:纯 CLI 包没有库入口,import 必然失败;而它的真实用法是 `npx <命令>`。
|
|
215
|
+
// 真跑 bin 还能抓到 import 永远测不到的故障:bin 判据用了字面路径、而 npm 装的是符号链接,
|
|
216
|
+
// 导致执行静默 exit 0 且零输出(历史事故形态)。
|
|
217
|
+
for (const b of bins) {
|
|
218
|
+
const binPath = join(consumer, 'node_modules', name, b.path);
|
|
219
|
+
const ver = await run(process.execPath, [binPath, '--version'], { cwd: consumer, env, timeoutMs: 60000 });
|
|
220
|
+
const verOut = `${ver.out || ''}${ver.err || ''}`.trim();
|
|
221
|
+
const verOk = ver.code === 0 && (!expectedVersion || verOut.includes(expectedVersion));
|
|
222
|
+
steps.push({ step: 'bin-version', ok: verOk, bin: b.command, output: verOut.slice(0, 120) });
|
|
223
|
+
if (!verOk) {
|
|
224
|
+
failures.push(`bin「${b.command} --version」未通过(退出码 ${ver.code}${expectedVersion ? `,期望输出含 ${expectedVersion}` : ''}):${verOut.slice(0, 300) || '(无输出)'}`);
|
|
225
|
+
}
|
|
226
|
+
const help = await run(process.execPath, [binPath, '--help'], { cwd: consumer, env, timeoutMs: 60000 });
|
|
227
|
+
steps.push({ step: 'bin-help', ok: help.code === 0, bin: b.command, code: help.code });
|
|
228
|
+
if (help.code !== 0) failures.push(`bin「${b.command} --help」退出码 ${help.code}(应为 0)`);
|
|
229
|
+
}
|
|
230
|
+
// ③ 既无库入口也无 bin:如实说「无可验证入口」,而不是含糊的「加载失败」
|
|
231
|
+
if (!entrySpecs.length && !bins.length) {
|
|
232
|
+
failures.push('该包既没有库入口(main/exports)也没有 bin——没有任何可验证入口,无法判断安装后是否可用');
|
|
233
|
+
}
|
|
210
234
|
return { ok: failures.length === 0, steps, failures, packument: { name, distTags: doc['dist-tags'], versions: Object.keys(doc.versions || {}) } };
|
|
211
235
|
} catch (e) {
|
|
212
236
|
failures.push(`本地彩排异常:${String(e?.message || e).slice(0, 300)}`);
|
package/lib/npm/publish.js
CHANGED
|
@@ -13,7 +13,7 @@ import { join } from 'node:path';
|
|
|
13
13
|
import { credentialsDir, readNpmToken } from '../core/credentials.js';
|
|
14
14
|
import { DEFAULT_REGISTRY, NPM_TIMEOUT_MS, normalizeRegistry, runNpm } from './registry.js';
|
|
15
15
|
import { npmArgs, writeNpmrc } from './npmrc.js';
|
|
16
|
-
import { smokeTestPackage, entrySpecsOf, isBrowserEntry } from './smoke.js';
|
|
16
|
+
import { smokeTestPackage, entrySpecsOf, isBrowserEntry, classifyPackageForm } from './smoke.js';
|
|
17
17
|
import { runLocalPreview } from './local-registry.js';
|
|
18
18
|
|
|
19
19
|
export const PUBLISH_LOG_FILE = 'npm-publish.log';
|
|
@@ -172,11 +172,17 @@ export async function publishPackage({
|
|
|
172
172
|
let preview = null;
|
|
173
173
|
if (localPreview) {
|
|
174
174
|
const pkgForPreview = JSON.parse(readFileSync(join(info.dir, 'package.json'), 'utf8'));
|
|
175
|
-
|
|
175
|
+
// 按**包的真实形态**决定验证方式:库包验 import,纯 CLI 包验 bin(真跑 --version/--help)。
|
|
176
|
+
// 历史实现一律 import,把 bin-only 的 CLI 包误判成「安装后加载失败」。
|
|
177
|
+
const form = classifyPackageForm(pkgForPreview);
|
|
178
|
+
const specs = form.entrySpecs.filter((sp) => {
|
|
176
179
|
const key = sp === pkgForPreview.name ? '.' : `./${sp.slice(String(pkgForPreview.name).length + 1)}`;
|
|
177
180
|
return !isBrowserEntry(key);
|
|
178
181
|
});
|
|
179
|
-
preview = await runLocalPreview({
|
|
182
|
+
preview = await runLocalPreview({
|
|
183
|
+
dir: info.dir, tag: tg, packageName: info.name,
|
|
184
|
+
entrySpecs: specs, bins: form.bins, expectedVersion: info.version, timeoutMs,
|
|
185
|
+
});
|
|
180
186
|
if (!preview.ok) {
|
|
181
187
|
return {
|
|
182
188
|
ok: false, blocked: 'local-preview-failed', name: info.name, version: info.version,
|
package/lib/npm/smoke.js
CHANGED
|
@@ -36,9 +36,44 @@ export function isBrowserEntry(key) {
|
|
|
36
36
|
return /(^|\/)client(\/|\.js)?(\/|$)|browser/i.test(String(key).replace(/^\.\//, ''));
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
/** 从 package.json 取「可执行的 bin 入口」(bin 可能是字符串或对象)。 */
|
|
40
|
+
export function binEntriesOf(pkg, packageName = '') {
|
|
41
|
+
const bin = pkg?.bin;
|
|
42
|
+
const name = String(packageName || pkg?.name || '');
|
|
43
|
+
const list = [];
|
|
44
|
+
if (typeof bin === 'string' && bin.trim()) list.push({ command: name, path: bin.trim() });
|
|
45
|
+
else if (bin && typeof bin === 'object') {
|
|
46
|
+
for (const [cmd, rel] of Object.entries(bin)) {
|
|
47
|
+
if (typeof rel === 'string' && rel.trim()) list.push({ command: cmd, path: rel.trim() });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return list;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 判断包的**真实形态**,据此选择验证方式。
|
|
55
|
+
*
|
|
56
|
+
* 为什么必须分形态:纯 CLI 服务包(只有 `bin`,没有 `main`/`exports`)设计上就没有库入口,
|
|
57
|
+
* 对它 `import('<包名>')` 必然失败——但包本身完全正常(真实用法是 `npx <命令>`)。
|
|
58
|
+
* 历史实现一律用 import 探测公开面,于是把这类包误判成「安装后加载失败」,
|
|
59
|
+
* 报错还会让调用方以为包坏了。
|
|
60
|
+
* @returns {{kind:'library'|'cli'|'both'|'none', entrySpecs:string[], bins:Array<{command:string,path:string}>}}
|
|
61
|
+
*/
|
|
62
|
+
export function classifyPackageForm(pkg) {
|
|
63
|
+
const name = String(pkg?.name || '');
|
|
64
|
+
const bins = binEntriesOf(pkg, name);
|
|
65
|
+
const hasLib = Boolean(pkg?.exports) || Boolean(pkg?.main);
|
|
66
|
+
const entrySpecs = hasLib && name ? entrySpecsOf(pkg) : [];
|
|
67
|
+
const kind = hasLib && bins.length ? 'both' : hasLib ? 'library' : bins.length ? 'cli' : 'none';
|
|
68
|
+
return { kind, entrySpecs, bins };
|
|
69
|
+
}
|
|
70
|
+
|
|
39
71
|
export function entrySpecsOf(pkg) {
|
|
40
72
|
const name = String(pkg?.name || '');
|
|
41
73
|
if (!name) return [];
|
|
74
|
+
// 没有 main/exports 的包(纯 CLI)**没有库入口**:返回空数组,让调用方走 bin 验证。
|
|
75
|
+
// 历史实现无条件返回 [name],对 bin-only 包 import 必然失败(Cannot find package .../index.js)。
|
|
76
|
+
if (!pkg.exports && !pkg.main) return [];
|
|
42
77
|
const exp = pkg.exports;
|
|
43
78
|
if (typeof exp === 'string') return [name];
|
|
44
79
|
if (exp && typeof exp === 'object') {
|
|
@@ -135,6 +170,22 @@ export async function smokeTestPackage({ dir = '', workspaceRoot = '', registry
|
|
|
135
170
|
failures.push(`加载探针执行失败:${String(e.message || e).slice(0, 300)}`);
|
|
136
171
|
return { ok: false, steps, failures, tgz: tgzName, bytes };
|
|
137
172
|
}
|
|
173
|
+
// bin 入口:装完真跑一次(纯 CLI 包没有库入口,import 测不到;见 classifyPackageForm 说明)
|
|
174
|
+
const bins = binEntriesOf(pkg, name);
|
|
175
|
+
for (const b of bins) {
|
|
176
|
+
try {
|
|
177
|
+
const { execFileSync } = await import('node:child_process');
|
|
178
|
+
const out = String(execFileSync(process.execPath, [join(consumer, 'node_modules', name, b.path), '--version'], {
|
|
179
|
+
cwd: consumer, encoding: 'utf8', timeout: 60000, stdio: ['ignore', 'pipe', 'pipe'],
|
|
180
|
+
})).trim();
|
|
181
|
+
const ok = !version || out.includes(version);
|
|
182
|
+
steps.push({ step: 'bin-version', bin: b.command, ok, output: out.slice(0, 120) });
|
|
183
|
+
if (!ok) failures.push(`bin「${b.command} --version」输出未包含版本 ${version}:${out.slice(0, 200)}`);
|
|
184
|
+
} catch (e) {
|
|
185
|
+
steps.push({ step: 'bin-version', bin: b.command, ok: false });
|
|
186
|
+
failures.push(`bin「${b.command} --version」执行失败:${String(e?.message || e).slice(0, 200)}`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
138
189
|
for (const it of parsed.entries || []) {
|
|
139
190
|
if (it.ok) steps.push({ step: 'import', spec: it.spec, ok: true });
|
|
140
191
|
else { steps.push({ step: 'import', spec: it.spec, ok: false }); failures.push(`公开面 import 失败:${it.spec} → ${it.error}`); }
|
package/lib/self/index.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
export const VERSION = '2.
|
|
12
|
+
export const VERSION = '2.16.1'; // 2.16.1:发布前彩排/冒烟按**包形态**验证(纯 CLI 包不再被判死)。历史实现一律 import('<包名>') 探测公开面:只有 bin、没有 main/exports 的纯 CLI 包必然报「Cannot find package .../index.js」,把好包误判成坏包、报错还写「加载失败」。现改为 classifyPackageForm 判形态:有库入口→import;只有 bin→**真跑** bin --version(断言输出含版本)与 --help(断言退出码 0);两者皆无→明确报「没有任何可验证入口」。真跑 bin 还能抓到 import 测不到的故障(bin 判据用字面路径、npm 装的是符号链接 → 执行静默 exit 0 零输出)。历史:2.16.0 建仓 CIFS 安全初始化。
|
|
13
13
|
// 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
|
|
14
14
|
// 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
|
|
15
15
|
// 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
|