@botiverse/stamp-cli 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -0
- package/lib/errors.mjs +38 -0
- package/lib/locale.mjs +68 -0
- package/lib/main.mjs +121 -15
- package/lib/pr-read.mjs +301 -0
- package/lib/repo-clone.mjs +60 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -6,12 +6,19 @@ admission, atomic 0600 `auth.json`). Future public origin: `stamp.build`.
|
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
8
|
npm i -g @botiverse/stamp-cli
|
|
9
|
+
# One-shot staging use must name the executable because the package has two bins.
|
|
10
|
+
npx --yes --package @botiverse/stamp-cli stamp-staging --help
|
|
9
11
|
stamp login
|
|
10
12
|
stamp key enroll
|
|
11
13
|
stamp identity bind --email agent@example.com
|
|
14
|
+
stamp repo clone org/repo
|
|
12
15
|
git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/my-change
|
|
13
16
|
stamp receipt get <id>
|
|
14
17
|
stamp pr create --receipt <published-id> --repo org/repo --head agent/my-change --sha <exact-sha> --base main --title "My change" --body-file ./pr-body.md
|
|
18
|
+
stamp pr list
|
|
19
|
+
stamp pr view 123 --repo org/repo
|
|
20
|
+
stamp pr diff 123 --repo org/repo
|
|
21
|
+
stamp pr checks 123 --repo org/repo
|
|
15
22
|
```
|
|
16
23
|
|
|
17
24
|
- Agent: `stamp login` (PKCE grant via `raft integration invoke --action agent-login`)
|
|
@@ -43,6 +50,20 @@ expanded to `refs/heads/...`; full refs also work. Use `--body-file -` for stdin
|
|
|
43
50
|
`--body` for inline text. A non-empty description is required. `--json` prints the
|
|
44
51
|
service receipt; a denial exits nonzero with recovery guidance.
|
|
45
52
|
|
|
53
|
+
The read-only PR commands follow the familiar `gh pr` command group while
|
|
54
|
+
reading through Stamp rather than a local GitHub credential:
|
|
55
|
+
|
|
56
|
+
- `stamp pr list` lists every PR that the current Agent created through Stamp.
|
|
57
|
+
Filtering and pagination are intentionally not advertised until the service
|
|
58
|
+
implements them.
|
|
59
|
+
- `stamp pr view`, `stamp pr diff`, and `stamp pr checks` accept a PR URL or a
|
|
60
|
+
number with `--repo OWNER/REPO` (`-R` also works).
|
|
61
|
+
- `stamp pr diff --name-only` prints only paths. `stamp pr checks` exits `8`
|
|
62
|
+
while checks are pending and `1` when a terminal check failed or no checks
|
|
63
|
+
are reported, matching the useful `gh pr checks` automation convention.
|
|
64
|
+
- `--json` returns the service's validated machine envelope. Human-formatted
|
|
65
|
+
output strips terminal control characters from provider-authored text.
|
|
66
|
+
|
|
46
67
|
The Raft manifest exposes only `agent-login`. Key enrollment, identity binding,
|
|
47
68
|
receipt reads, PR creation and subscriptions all use this CLI; the HTTP APIs
|
|
48
69
|
remain available to service clients. `stamp migration-help` maps retired action
|
package/lib/errors.mjs
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
import { t } from "./locale.mjs";
|
|
2
2
|
|
|
3
|
+
const apiRecoveryKeys = new Map([
|
|
4
|
+
["GITHUB_IDENTITY_BINDING_REQUIRED", "apiBindIdentity"],
|
|
5
|
+
["REPOSITORY_NOT_INSTALLED", "apiRepositoryNotInstalled"],
|
|
6
|
+
["PUBLIC_CONTRIBUTION_POLICY_DENIED", "apiContributionDenied"],
|
|
7
|
+
["REPOSITORY_NOT_AUTHORIZED", "apiRepositoryNotAuthorized"],
|
|
8
|
+
["PR_NOT_FOUND", "prReadNotFound"],
|
|
9
|
+
["PR_HEAD_MOVED", "prReadHeadMoved"],
|
|
10
|
+
["PR_DIFF_INCOMPLETE", "prReadDiffIncomplete"],
|
|
11
|
+
["PR_DETAIL_FAILED", "prReadUnavailable"],
|
|
12
|
+
["PR_DIFF_FAILED", "prReadUnavailable"],
|
|
13
|
+
["PR_INBOX_FAILED", "prReadUnavailable"],
|
|
14
|
+
]);
|
|
15
|
+
|
|
3
16
|
/** Stable machine code on `.code`; English catalog text on `.message` for tests. */
|
|
4
17
|
export class AgentError extends Error {
|
|
5
18
|
constructor(code, details = {}) {
|
|
@@ -18,3 +31,28 @@ export function presentError(locale, e) {
|
|
|
18
31
|
if (e instanceof AgentError) return t(locale, e.code, e.details);
|
|
19
32
|
return e.message;
|
|
20
33
|
}
|
|
34
|
+
|
|
35
|
+
function stableErrorCode(value) {
|
|
36
|
+
if (typeof value !== "string") return "";
|
|
37
|
+
const code = value.trim();
|
|
38
|
+
return /^[A-Z0-9_:-]{1,128}$/.test(code) ? code : "";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function boundedSuggestedAction(value) {
|
|
42
|
+
if (typeof value !== "string") return "";
|
|
43
|
+
return value.trim().replace(/[\r\n\t]+/g, " ").slice(0, 512);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// API authorization denials keep the compatibility `error` at the top level and
|
|
47
|
+
// carry the actionable reason in errorCode + suggestedNextAction. Prefer a localized,
|
|
48
|
+
// executable repair for known codes; preserve a bounded server suggestion for future
|
|
49
|
+
// codes so a new denial does not degrade back to an opaque REPOSITORY_NOT_AUTHORIZED.
|
|
50
|
+
export function apiErrorGuidance(locale, body) {
|
|
51
|
+
if (!body || typeof body !== "object") return { code: "", action: "" };
|
|
52
|
+
const code = stableErrorCode(body.errorCode ?? body.error);
|
|
53
|
+
const key = apiRecoveryKeys.get(code);
|
|
54
|
+
return {
|
|
55
|
+
code,
|
|
56
|
+
action: key ? t(locale, key) : boundedSuggestedAction(body.suggestedNextAction),
|
|
57
|
+
};
|
|
58
|
+
}
|
package/lib/locale.mjs
CHANGED
|
@@ -2,6 +2,27 @@
|
|
|
2
2
|
export const messages = {
|
|
3
3
|
en: {
|
|
4
4
|
usagePrCreate: "usage: stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
|
|
5
|
+
usagePrRead: "usage: stamp pr <list|view|diff|checks> [arguments]",
|
|
6
|
+
usagePrList: "usage: stamp pr list",
|
|
7
|
+
usagePrView: "usage: stamp pr view <number|URL> [--repo OWNER/REPO]",
|
|
8
|
+
usagePrDiff: "usage: stamp pr diff <number|URL> [--repo OWNER/REPO] [--name-only]",
|
|
9
|
+
usagePrChecks: "usage: stamp pr checks <number|URL> [--repo OWNER/REPO]",
|
|
10
|
+
prReadInvalidResponse: "Stamp returned an invalid PR read response; retry after checking the service version.",
|
|
11
|
+
prReadCoordinateMismatch: "Stamp returned PR coordinates different from the requested repository or number; refusing to display them.",
|
|
12
|
+
prListEmpty: "No Stamp-created pull requests found.",
|
|
13
|
+
prStatusUnavailable: "status unavailable",
|
|
14
|
+
prCIShort: "CI",
|
|
15
|
+
prAgentShort: "Agent",
|
|
16
|
+
prHeadLabel: "Head",
|
|
17
|
+
prChecksLabel: "Checks",
|
|
18
|
+
prReviewLabel: "Review",
|
|
19
|
+
prDiffUnavailable: "patch unavailable",
|
|
20
|
+
prDiffEmpty: "No changed files reported.",
|
|
21
|
+
prChecksEmpty: "No checks reported.",
|
|
22
|
+
prReadNotFound: "Check the repository and PR number, and confirm this Agent created the PR through Stamp.",
|
|
23
|
+
prReadHeadMoved: "The PR head changed while Stamp read the diff; rerun the command and review the new head.",
|
|
24
|
+
prReadDiffIncomplete: "GitHub did not return the complete PR diff; retry later instead of relying on partial files.",
|
|
25
|
+
prReadUnavailable: "The PR read is temporarily unavailable; retry after checking Stamp service status.",
|
|
5
26
|
prRequired: "Missing {flag}; use stamp receipt get <id> to obtain the published coordinates.",
|
|
6
27
|
prRepository: "--repo must be OWNER/REPO.",
|
|
7
28
|
prSHA: "--sha must be the exact 40-character lowercase published commit SHA.",
|
|
@@ -18,6 +39,10 @@ export const messages = {
|
|
|
18
39
|
prCheckAccess: "Check repository access and the authorized base branch with the repository administrator.",
|
|
19
40
|
prCheckExisting: "Check the existing PR and keep the same receipt, title, body and idempotency key when retrying.",
|
|
20
41
|
prRetry: "Check the receipt and service status, then retry the identical command; its idempotency key stays unchanged.",
|
|
42
|
+
apiBindIdentity: "Bind this agent first with `stamp identity bind --email <agent-email>`, then retry the command.",
|
|
43
|
+
apiRepositoryNotInstalled: "Check OWNER/REPO spelling, or ask a server owner to install the Stamp GitHub App on that repository, then retry.",
|
|
44
|
+
apiContributionDenied: "Ask a server owner to grant this agent an active Write-or-higher repository role, then retry.",
|
|
45
|
+
apiRepositoryNotAuthorized: "Ask a server owner to verify the Stamp GitHub App installation and this agent's identity binding, then retry.",
|
|
21
46
|
|
|
22
47
|
usage: `stamp {version} — Agent Git gateway CLI (future origin stamp.build)
|
|
23
48
|
|
|
@@ -29,6 +54,11 @@ export const messages = {
|
|
|
29
54
|
stamp identity bind --email ADDR bind commit-author email (DCO)
|
|
30
55
|
stamp receipt get <id> gateway acceptance + GitHub publication status
|
|
31
56
|
stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
|
|
57
|
+
stamp pr list
|
|
58
|
+
stamp pr view <number|URL> --repo OWNER/REPO
|
|
59
|
+
stamp pr diff <number|URL> --repo OWNER/REPO [--name-only]
|
|
60
|
+
stamp pr checks <number|URL> --repo OWNER/REPO
|
|
61
|
+
stamp repo clone <repository> [<directory>] [-- <gitflags>...]
|
|
32
62
|
|
|
33
63
|
stamp follow <owner/repo> --kind issue|pull --number N
|
|
34
64
|
stamp unfollow <owner/repo> --kind issue|pull --number N
|
|
@@ -37,9 +67,13 @@ export const messages = {
|
|
|
37
67
|
stamp watch <owner/repo> --event TYPE
|
|
38
68
|
stamp unwatch <owner/repo> --event TYPE
|
|
39
69
|
|
|
70
|
+
git clone ssh://git@ssh.staging.stamp.build:443/org/repo.git
|
|
40
71
|
git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
|
|
41
72
|
|
|
42
73
|
flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE, STAMP_LANG`,
|
|
74
|
+
usageRepoClone: "usage: stamp repo clone <repository> [<directory>] [-- <gitflags>...]",
|
|
75
|
+
cloned: "Cloned {repository} from {url}",
|
|
76
|
+
cloneFailed: "clone of {repository} via the Stamp gateway failed",
|
|
43
77
|
loginHumanIntro: "Not a managed Raft agent. Humans and CI use STAMP_TOKEN:",
|
|
44
78
|
loginHumanBrowser: " browser: {url}/login (reuse the session cookie value as STAMP_TOKEN)",
|
|
45
79
|
loginHumanCI: " CI: a narrowly scoped deploy token",
|
|
@@ -102,6 +136,27 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
102
136
|
},
|
|
103
137
|
"zh-CN": {
|
|
104
138
|
usagePrCreate: "用法:stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
|
|
139
|
+
usagePrRead: "用法:stamp pr <list|view|diff|checks> [参数]",
|
|
140
|
+
usagePrList: "用法:stamp pr list",
|
|
141
|
+
usagePrView: "用法:stamp pr view <编号|URL> [--repo OWNER/REPO]",
|
|
142
|
+
usagePrDiff: "用法:stamp pr diff <编号|URL> [--repo OWNER/REPO] [--name-only]",
|
|
143
|
+
usagePrChecks: "用法:stamp pr checks <编号|URL> [--repo OWNER/REPO]",
|
|
144
|
+
prReadInvalidResponse: "Stamp 返回了无效的 PR 读取响应;请检查服务版本后重试。",
|
|
145
|
+
prReadCoordinateMismatch: "Stamp 返回的 PR 坐标与请求的仓库或编号不一致;已拒绝显示。",
|
|
146
|
+
prListEmpty: "没有找到通过 Stamp 创建的 Pull Request。",
|
|
147
|
+
prStatusUnavailable: "实时状态暂不可用",
|
|
148
|
+
prCIShort: "CI",
|
|
149
|
+
prAgentShort: "Agent",
|
|
150
|
+
prHeadLabel: "Head",
|
|
151
|
+
prChecksLabel: "检查",
|
|
152
|
+
prReviewLabel: "审阅",
|
|
153
|
+
prDiffUnavailable: "patch 不可用",
|
|
154
|
+
prDiffEmpty: "没有变更文件。",
|
|
155
|
+
prChecksEmpty: "没有检查记录。",
|
|
156
|
+
prReadNotFound: "请检查仓库和 PR 编号,并确认该 PR 是此 Agent 通过 Stamp 创建的。",
|
|
157
|
+
prReadHeadMoved: "Stamp 读取 diff 时 PR head 已变化;请重新运行命令并审阅新的 head。",
|
|
158
|
+
prReadDiffIncomplete: "GitHub 未返回完整的 PR diff;请稍后重试,不要依赖部分文件。",
|
|
159
|
+
prReadUnavailable: "PR 读取暂时不可用;请检查 Stamp 服务状态后重试。",
|
|
105
160
|
prRequired: "缺少 {flag};用 stamp receipt get <id> 获取已发表提交的信息。",
|
|
106
161
|
prRepository: "--repo 必须为 OWNER/REPO。",
|
|
107
162
|
prSHA: "--sha 必须是已发表提交的精确 40 位小写 SHA。",
|
|
@@ -118,6 +173,10 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
118
173
|
prCheckAccess: "请与仓库管理员核对仓库权限和允许的目标分支。",
|
|
119
174
|
prCheckExisting: "请检查已有 PR;重试时保持 receipt、标题、正文和幂等键不变。",
|
|
120
175
|
prRetry: "请检查 receipt 和服务状态,再原样重试命令;幂等键会保持不变。",
|
|
176
|
+
apiBindIdentity: "请先运行 `stamp identity bind --email <agent-email>` 绑定此 Agent,再重试命令。",
|
|
177
|
+
apiRepositoryNotInstalled: "请检查 OWNER/REPO 拼写,或请 Server Owner 为该仓库安装 Stamp GitHub App,再重试。",
|
|
178
|
+
apiContributionDenied: "请让 Server Owner 为此 Agent 授予有效的 Write 或更高仓库角色,再重试。",
|
|
179
|
+
apiRepositoryNotAuthorized: "请让 Server Owner 核对 Stamp GitHub App 安装与此 Agent 的身份绑定,再重试。",
|
|
121
180
|
|
|
122
181
|
usage: `stamp {version} — Agent Git 网关 CLI(未来域名 stamp.build)
|
|
123
182
|
|
|
@@ -129,6 +188,11 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
129
188
|
stamp identity bind --email ADDR 绑定提交作者邮箱(DCO)
|
|
130
189
|
stamp receipt get <id> 网关接受与 GitHub 发表状态
|
|
131
190
|
stamp pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
|
|
191
|
+
stamp pr list
|
|
192
|
+
stamp pr view <编号|URL> --repo OWNER/REPO
|
|
193
|
+
stamp pr diff <编号|URL> --repo OWNER/REPO [--name-only]
|
|
194
|
+
stamp pr checks <编号|URL> --repo OWNER/REPO
|
|
195
|
+
stamp repo clone <repository> [<directory>] [-- <gitflags>...]
|
|
132
196
|
|
|
133
197
|
stamp follow <owner/repo> --kind issue|pull --number N
|
|
134
198
|
stamp unfollow <owner/repo> --kind issue|pull --number N
|
|
@@ -137,9 +201,13 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
137
201
|
stamp watch <owner/repo> --event TYPE
|
|
138
202
|
stamp unwatch <owner/repo> --event TYPE
|
|
139
203
|
|
|
204
|
+
git clone ssh://git@ssh.staging.stamp.build:443/org/repo.git
|
|
140
205
|
git push ssh://git@ssh.staging.stamp.build:443/org/repo.git HEAD:refs/heads/agent/…
|
|
141
206
|
|
|
142
207
|
flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、STAMP_SERVICE、STAMP_LANG`,
|
|
208
|
+
usageRepoClone: "用法:stamp repo clone <repository> [<directory>] [-- <gitflags>...]",
|
|
209
|
+
cloned: "已从 {url} 克隆 {repository}",
|
|
210
|
+
cloneFailed: "经 Stamp 网关克隆 {repository} 失败",
|
|
143
211
|
loginHumanIntro: "当前不是受管 Raft Agent。人类和 CI 使用 STAMP_TOKEN:",
|
|
144
212
|
loginHumanBrowser: " 浏览器:{url}/login (把会话 cookie 值设为 STAMP_TOKEN)",
|
|
145
213
|
loginHumanCI: " CI: 由负责人签发的窄范围部署令牌",
|
package/lib/main.mjs
CHANGED
|
@@ -7,7 +7,23 @@ import { makeClient, ApiError } from "./client.mjs";
|
|
|
7
7
|
import { runAgentLogin } from "./agent-login.mjs";
|
|
8
8
|
import { selectLocale, t } from "./locale.mjs";
|
|
9
9
|
import { pullRequestInput, pullRequestRecovery } from "./pull-request.mjs";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
formatPRChecks,
|
|
12
|
+
formatPRDetail,
|
|
13
|
+
formatPRDiff,
|
|
14
|
+
formatPRList,
|
|
15
|
+
parsePRDiffArgs,
|
|
16
|
+
parsePRListArgs,
|
|
17
|
+
parsePRTargetArgs,
|
|
18
|
+
prChecksExitCode,
|
|
19
|
+
prDetailPath,
|
|
20
|
+
prDiffPath,
|
|
21
|
+
validatePRDetail,
|
|
22
|
+
validatePRDiff,
|
|
23
|
+
validatePRListResponse,
|
|
24
|
+
} from "./pr-read.mjs";
|
|
25
|
+
import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone } from "./repo-clone.mjs";
|
|
26
|
+
import { apiErrorGuidance, presentError } from "./errors.mjs";
|
|
11
27
|
|
|
12
28
|
const require = createRequire(import.meta.url);
|
|
13
29
|
const pkg = require("../package.json");
|
|
@@ -27,14 +43,27 @@ function readPublicKey(path) {
|
|
|
27
43
|
|
|
28
44
|
function objectArgs(args, locale) {
|
|
29
45
|
const repository = args.shift();
|
|
30
|
-
const
|
|
46
|
+
const rawKind = takeFlag(args, "kind");
|
|
47
|
+
// Keep the concise user-facing `pull` spelling while sending the gateway's
|
|
48
|
+
// canonical GitHubObjectKind on the wire. Also accept the canonical spelling
|
|
49
|
+
// for scripts that already learned it from a response/event payload.
|
|
50
|
+
const kind = rawKind === "pull" ? "pull_request" : rawKind;
|
|
31
51
|
const number = Number(takeFlag(args, "number"));
|
|
32
|
-
if (!repository || !kind || !Number.isInteger(number) || number <= 0) {
|
|
52
|
+
if (!repository || !["issue", "pull_request"].includes(kind) || !Number.isInteger(number) || number <= 0) {
|
|
33
53
|
throw new Error(t(locale, "usageFollow"));
|
|
34
54
|
}
|
|
35
55
|
return { repository, kind, number };
|
|
36
56
|
}
|
|
37
57
|
|
|
58
|
+
function emitApiGuidance(error, locale, write) {
|
|
59
|
+
const guidance = apiErrorGuidance(locale, error.body);
|
|
60
|
+
if (guidance.code && guidance.code !== error.body?.error) write(`stamp: ${guidance.code}`);
|
|
61
|
+
if (guidance.action) write(`stamp: ${guidance.action}`);
|
|
62
|
+
// A typed code without a known/bounded action is not enough to suppress a
|
|
63
|
+
// command-specific fallback (for example PR head-drift guidance).
|
|
64
|
+
return Boolean(guidance.action);
|
|
65
|
+
}
|
|
66
|
+
|
|
38
67
|
export async function main(argv, opts) {
|
|
39
68
|
const args = [...argv];
|
|
40
69
|
const out = opts.stdout ?? ((s) => console.log(s));
|
|
@@ -139,21 +168,97 @@ export async function main(argv, opts) {
|
|
|
139
168
|
emit(d, () => out(`${d.id} ${d.status} ${d.repository} ${d.targetRef} published=${d.publishedSha ?? "-"}`));
|
|
140
169
|
return exit(0);
|
|
141
170
|
}
|
|
171
|
+
case "repo": {
|
|
172
|
+
if (args.shift() !== "clone") throw new Error(t(locale, "usageRepoClone"));
|
|
173
|
+
const parsed = parseRepoCloneArgs(args);
|
|
174
|
+
if (!parsed) throw new Error(t(locale, "usageRepoClone"));
|
|
175
|
+
const me = await api("GET", "/v1/me");
|
|
176
|
+
const defaultOwner = me?.github?.login;
|
|
177
|
+
const repo = parseRepository(parsed.repository, defaultOwner);
|
|
178
|
+
if (!repo) throw new Error(t(locale, "usageRepoClone"));
|
|
179
|
+
const url = gatewayCloneURL(me.sshHost, me.sshPort, repo.owner, repo.name);
|
|
180
|
+
const git = opts.gitCloneImpl ?? runGitClone;
|
|
181
|
+
const result = await git({
|
|
182
|
+
url,
|
|
183
|
+
directory: parsed.directory,
|
|
184
|
+
gitFlags: parsed.gitFlags,
|
|
185
|
+
env: opts.gitEnv ?? env,
|
|
186
|
+
});
|
|
187
|
+
if (result.code !== 0) {
|
|
188
|
+
if (result.stderr) err(result.stderr.trimEnd());
|
|
189
|
+
throw new Error(t(locale, "cloneFailed", { repository: `${repo.owner}/${repo.name}` }));
|
|
190
|
+
}
|
|
191
|
+
if (result.stderr) err(result.stderr.trimEnd());
|
|
192
|
+
emit(
|
|
193
|
+
{ ok: true, repository: `${repo.owner}/${repo.name}`, url, directory: parsed.directory ?? repo.name },
|
|
194
|
+
() => out(t(locale, "cloned", { repository: `${repo.owner}/${repo.name}`, url })),
|
|
195
|
+
);
|
|
196
|
+
return exit(0);
|
|
197
|
+
}
|
|
142
198
|
case "pr": {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
199
|
+
const sub = args.shift();
|
|
200
|
+
if (sub === "create") {
|
|
201
|
+
const input = pullRequestInput(args);
|
|
202
|
+
try {
|
|
203
|
+
const d = await api("POST", "/v1/pull-requests", input);
|
|
204
|
+
emit(d, () => out(t(locale, d.idempotent ? "prExisting" : "prCreated", { number: d.pullNumber, url: d.url })));
|
|
205
|
+
} catch (e) {
|
|
206
|
+
if (e instanceof ApiError && e.status !== 401) {
|
|
207
|
+
err(`stamp: ${e.message}`);
|
|
208
|
+
if (!emitApiGuidance(e, locale, err)) err(t(locale, pullRequestRecovery(e.body?.error)));
|
|
209
|
+
return exit(1);
|
|
210
|
+
}
|
|
211
|
+
throw e;
|
|
153
212
|
}
|
|
154
|
-
|
|
213
|
+
return exit(0);
|
|
155
214
|
}
|
|
156
|
-
|
|
215
|
+
if (sub === "list" || sub === "ls") {
|
|
216
|
+
const path = parsePRListArgs(args);
|
|
217
|
+
const d = validatePRListResponse(await api("GET", path));
|
|
218
|
+
emit(d, () => {
|
|
219
|
+
const lines = formatPRList(d, {
|
|
220
|
+
statusUnavailable: t(locale, "prStatusUnavailable"),
|
|
221
|
+
ci: t(locale, "prCIShort"),
|
|
222
|
+
agent: t(locale, "prAgentShort"),
|
|
223
|
+
});
|
|
224
|
+
if (lines.length === 0) out(t(locale, "prListEmpty"));
|
|
225
|
+
else for (const line of lines) out(line);
|
|
226
|
+
});
|
|
227
|
+
return exit(0);
|
|
228
|
+
}
|
|
229
|
+
if (sub === "view") {
|
|
230
|
+
const target = parsePRTargetArgs(args, "usagePrView");
|
|
231
|
+
const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
|
|
232
|
+
emit(d, () => {
|
|
233
|
+
for (const line of formatPRDetail(d, {
|
|
234
|
+
head: t(locale, "prHeadLabel"),
|
|
235
|
+
checks: t(locale, "prChecksLabel"),
|
|
236
|
+
review: t(locale, "prReviewLabel"),
|
|
237
|
+
})) out(line);
|
|
238
|
+
});
|
|
239
|
+
return exit(0);
|
|
240
|
+
}
|
|
241
|
+
if (sub === "diff") {
|
|
242
|
+
const target = parsePRDiffArgs(args);
|
|
243
|
+
const d = validatePRDiff(await api("GET", prDiffPath(target)), target);
|
|
244
|
+
emit(d, () => {
|
|
245
|
+
const chunks = formatPRDiff(d, target.nameOnly, t(locale, "prDiffUnavailable"));
|
|
246
|
+
if (chunks.length === 0) out(t(locale, "prDiffEmpty"));
|
|
247
|
+
else out(chunks.join("\n"));
|
|
248
|
+
});
|
|
249
|
+
return exit(0);
|
|
250
|
+
}
|
|
251
|
+
if (sub === "checks") {
|
|
252
|
+
const target = parsePRTargetArgs(args, "usagePrChecks");
|
|
253
|
+
const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
|
|
254
|
+
emit(d.checks, () => {
|
|
255
|
+
const lines = formatPRChecks(d);
|
|
256
|
+
if (lines.length === 0) out(t(locale, "prChecksEmpty"));
|
|
257
|
+
else for (const line of lines) out(line);
|
|
258
|
+
});
|
|
259
|
+
return exit(prChecksExitCode(d));
|
|
260
|
+
}
|
|
261
|
+
throw new Error(t(locale, "usagePrRead"));
|
|
157
262
|
}
|
|
158
263
|
case "follow":
|
|
159
264
|
case "unfollow": {
|
|
@@ -193,6 +298,7 @@ export async function main(argv, opts) {
|
|
|
193
298
|
} catch (e) {
|
|
194
299
|
if (e instanceof ApiError) {
|
|
195
300
|
err(`stamp: ${e.message}`);
|
|
301
|
+
emitApiGuidance(e, locale, err);
|
|
196
302
|
if (e.status === 401) err(auth.mode === "agent" ? t(locale, "sessionRejected") : t(locale, "checkToken"));
|
|
197
303
|
return exit(1);
|
|
198
304
|
}
|
package/lib/pr-read.mjs
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { AgentError } from "./errors.mjs";
|
|
2
|
+
|
|
3
|
+
const consolidatedStatuses = new Set(["OPEN", "DRAFT", "MERGING", "MERGED", "CLOSED"]);
|
|
4
|
+
const ciStatuses = new Set(["passing", "failing", "pending", "none"]);
|
|
5
|
+
const reviewStates = new Set([
|
|
6
|
+
"HAS_ACTIVE_REVIEW",
|
|
7
|
+
"HAS_UNADDRESSED_CHANGES_REQUESTED",
|
|
8
|
+
"IS_FULLY_APPROVED",
|
|
9
|
+
"ONE_OR_MORE_APPROVALS",
|
|
10
|
+
]);
|
|
11
|
+
const terminalPassConclusions = new Set(["success", "neutral", "skipped"]);
|
|
12
|
+
const pendingCheckStates = new Set(["", "expected", "in_progress", "pending", "queued", "requested", "waiting"]);
|
|
13
|
+
|
|
14
|
+
function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
|
|
15
|
+
const matches = [];
|
|
16
|
+
for (let i = 0; i < args.length; i++) {
|
|
17
|
+
if (args[i] === `--${long}` || (short && args[i] === `-${short}`)) {
|
|
18
|
+
matches.push({ index: i, inline: false });
|
|
19
|
+
} else if (args[i].startsWith(`--${long}=`)) {
|
|
20
|
+
matches.push({ index: i, inline: true });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (matches.length === 0) return undefined;
|
|
24
|
+
if (matches.length > 1) throw new AgentError(usageCode);
|
|
25
|
+
const { index, inline } = matches[0];
|
|
26
|
+
if (inline) {
|
|
27
|
+
const value = args[index].slice(long.length + 3);
|
|
28
|
+
if (value === "") throw new AgentError(usageCode);
|
|
29
|
+
args.splice(index, 1);
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
const value = args[index + 1];
|
|
33
|
+
if (value === undefined || value.startsWith("-")) throw new AgentError(usageCode);
|
|
34
|
+
args.splice(index, 2);
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function takeBooleanFlag(args, long) {
|
|
39
|
+
const i = args.indexOf(`--${long}`);
|
|
40
|
+
if (i === -1) return false;
|
|
41
|
+
args.splice(i, 1);
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function strictPositiveInt(value, fallback, maximum = Number.MAX_SAFE_INTEGER) {
|
|
46
|
+
if (value === undefined) return fallback;
|
|
47
|
+
if (!/^[1-9][0-9]*$/.test(value)) return null;
|
|
48
|
+
const parsed = Number(value);
|
|
49
|
+
return Number.isSafeInteger(parsed) && parsed <= maximum ? parsed : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function repositoryParts(value) {
|
|
53
|
+
const match = String(value ?? "").trim().match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);
|
|
54
|
+
if (!match || match[1] === "." || match[1] === ".." || match[2] === "." || match[2] === "..") return null;
|
|
55
|
+
return { owner: match[1], repo: match[2] };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sameRepository(left, right) {
|
|
59
|
+
return String(left).toLowerCase() === String(right).toLowerCase();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function targetFromURL(value) {
|
|
63
|
+
let parsed;
|
|
64
|
+
try { parsed = new URL(value); } catch { return null; }
|
|
65
|
+
if (parsed.protocol !== "https:" || parsed.hostname.toLowerCase() !== "github.com" || parsed.port || parsed.username || parsed.password) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const parts = parsed.pathname.split("/").filter(Boolean);
|
|
69
|
+
const marker = parts[2];
|
|
70
|
+
if (parts.length < 4 || (marker !== "pull" && marker !== "pulls")) return null;
|
|
71
|
+
const repository = repositoryParts(`${parts[0]}/${parts[1]}`);
|
|
72
|
+
const number = strictPositiveInt(parts[3]);
|
|
73
|
+
return repository && number ? { ...repository, number } : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function parsePRListArgs(input) {
|
|
77
|
+
if (input.length !== 0) throw new AgentError("usagePrList");
|
|
78
|
+
return "/v1/pr-inbox";
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function parsePRTargetArgs(input, usageCode = "usagePrRead") {
|
|
82
|
+
const args = [...input];
|
|
83
|
+
const repoFlag = takeNamedFlag(args, "repo", "R", usageCode);
|
|
84
|
+
const target = args.shift();
|
|
85
|
+
if (!target || args.length !== 0) throw new AgentError(usageCode);
|
|
86
|
+
const fromURL = targetFromURL(target);
|
|
87
|
+
if (fromURL) {
|
|
88
|
+
if (repoFlag && (!repositoryParts(repoFlag) || !sameRepository(`${fromURL.owner}/${fromURL.repo}`, repoFlag))) {
|
|
89
|
+
throw new AgentError(usageCode);
|
|
90
|
+
}
|
|
91
|
+
return fromURL;
|
|
92
|
+
}
|
|
93
|
+
const repository = repositoryParts(repoFlag);
|
|
94
|
+
const number = strictPositiveInt(target);
|
|
95
|
+
if (!repository || !number) throw new AgentError(usageCode);
|
|
96
|
+
return { ...repository, number };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function parsePRDiffArgs(input) {
|
|
100
|
+
const args = [...input];
|
|
101
|
+
const nameOnly = takeBooleanFlag(args, "name-only");
|
|
102
|
+
return { ...parsePRTargetArgs(args, "usagePrDiff"), nameOnly };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function prDetailPath(target) {
|
|
106
|
+
return `/v1/repositories/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repo)}/pulls/${target.number}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function prDiffPath(target) {
|
|
110
|
+
return `${prDetailPath(target)}/diff`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function requireObject(value) {
|
|
114
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new AgentError("prReadInvalidResponse");
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function requireString(value) {
|
|
119
|
+
if (typeof value !== "string") throw new AgentError("prReadInvalidResponse");
|
|
120
|
+
return value;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function requireNumber(value) {
|
|
124
|
+
if (!Number.isInteger(value) || value <= 0) throw new AgentError("prReadInvalidResponse");
|
|
125
|
+
return value;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function requireSHA(value) {
|
|
129
|
+
const sha = requireString(value);
|
|
130
|
+
if (!/^[0-9a-f]{40}$/.test(sha)) throw new AgentError("prReadInvalidResponse");
|
|
131
|
+
return sha;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function safeInline(value) {
|
|
135
|
+
return String(value).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]+/g, " ").replace(/\s+/g, " ").trim();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function safeMultiline(value) {
|
|
139
|
+
return String(value)
|
|
140
|
+
.replace(/\r\n?/g, "\n")
|
|
141
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function validatePRListResponse(value) {
|
|
145
|
+
const response = requireObject(value);
|
|
146
|
+
if (!Array.isArray(response.items)) throw new AgentError("prReadInvalidResponse");
|
|
147
|
+
for (const raw of response.items) {
|
|
148
|
+
const item = requireObject(raw);
|
|
149
|
+
if (!repositoryParts(requireString(item.repository))) throw new AgentError("prReadInvalidResponse");
|
|
150
|
+
requireNumber(item.number);
|
|
151
|
+
requireString(item.title);
|
|
152
|
+
requireString(item.url);
|
|
153
|
+
requireString(item.raftAgentId);
|
|
154
|
+
requireSHA(item.headSha);
|
|
155
|
+
if (!Array.isArray(item.reviewStates) || item.reviewStates.some((state) => !reviewStates.has(state))) {
|
|
156
|
+
throw new AgentError("prReadInvalidResponse");
|
|
157
|
+
}
|
|
158
|
+
const status = requireString(item.status);
|
|
159
|
+
const ciStatus = requireString(item.ciStatus);
|
|
160
|
+
if (status === "UNKNOWN") {
|
|
161
|
+
if (ciStatus !== "none" || item.reviewStates.length !== 0) throw new AgentError("prReadInvalidResponse");
|
|
162
|
+
} else {
|
|
163
|
+
if (!consolidatedStatuses.has(status) || !ciStatuses.has(ciStatus)) throw new AgentError("prReadInvalidResponse");
|
|
164
|
+
}
|
|
165
|
+
requireString(item.updatedAt);
|
|
166
|
+
}
|
|
167
|
+
if (response.nextCursor !== null || response.truncated !== false) throw new AgentError("prReadInvalidResponse");
|
|
168
|
+
return response;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function validatePRDetail(value, expected) {
|
|
172
|
+
const detail = requireObject(value);
|
|
173
|
+
requireString(detail.repository);
|
|
174
|
+
requireNumber(detail.number);
|
|
175
|
+
requireString(detail.title);
|
|
176
|
+
requireString(detail.url);
|
|
177
|
+
requireString(detail.author);
|
|
178
|
+
requireSHA(detail.headSha);
|
|
179
|
+
requireSHA(detail.baseSha);
|
|
180
|
+
requireSHA(detail.mergeBaseSha);
|
|
181
|
+
requireString(detail.headRef);
|
|
182
|
+
requireString(detail.baseRef);
|
|
183
|
+
if (!ciStatuses.has(requireString(detail.ciStatus))) throw new AgentError("prReadInvalidResponse");
|
|
184
|
+
requireString(detail.reviewStatus);
|
|
185
|
+
requireString(detail.reviewFreshness);
|
|
186
|
+
if (typeof detail.stale !== "boolean" || typeof detail.invalidated !== "boolean") throw new AgentError("prReadInvalidResponse");
|
|
187
|
+
requireString(detail.updatedAt);
|
|
188
|
+
requireString(detail.body);
|
|
189
|
+
if (!Array.isArray(detail.checks)) throw new AgentError("prReadInvalidResponse");
|
|
190
|
+
for (const raw of detail.checks) {
|
|
191
|
+
const check = requireObject(raw);
|
|
192
|
+
requireString(check.name);
|
|
193
|
+
requireString(check.status);
|
|
194
|
+
requireString(check.conclusion);
|
|
195
|
+
requireString(check.url);
|
|
196
|
+
}
|
|
197
|
+
for (const links of [detail.dependencies, detail.dependents]) {
|
|
198
|
+
if (!Array.isArray(links)) throw new AgentError("prReadInvalidResponse");
|
|
199
|
+
for (const raw of links) {
|
|
200
|
+
const link = requireObject(raw);
|
|
201
|
+
requireNumber(link.number);
|
|
202
|
+
requireString(link.title);
|
|
203
|
+
requireString(link.url);
|
|
204
|
+
requireString(link.reason);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (expected && (!sameRepository(detail.repository, `${expected.owner}/${expected.repo}`) || detail.number !== expected.number)) {
|
|
208
|
+
throw new AgentError("prReadCoordinateMismatch");
|
|
209
|
+
}
|
|
210
|
+
return detail;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function validatePRDiff(value, expected) {
|
|
214
|
+
const response = requireObject(value);
|
|
215
|
+
requireString(response.repository);
|
|
216
|
+
requireNumber(response.number);
|
|
217
|
+
requireSHA(response.baseSha);
|
|
218
|
+
requireSHA(response.headSha);
|
|
219
|
+
if (expected && (!sameRepository(response.repository, `${expected.owner}/${expected.repo}`) || response.number !== expected.number)) {
|
|
220
|
+
throw new AgentError("prReadCoordinateMismatch");
|
|
221
|
+
}
|
|
222
|
+
if (!Array.isArray(response.files)) throw new AgentError("prReadInvalidResponse");
|
|
223
|
+
for (const raw of response.files) {
|
|
224
|
+
const file = requireObject(raw);
|
|
225
|
+
requireString(file.path);
|
|
226
|
+
requireString(file.status);
|
|
227
|
+
if (!Number.isInteger(file.additions) || file.additions < 0 || !Number.isInteger(file.deletions) || file.deletions < 0) {
|
|
228
|
+
throw new AgentError("prReadInvalidResponse");
|
|
229
|
+
}
|
|
230
|
+
if (file.patch !== null && file.patch !== undefined && typeof file.patch !== "string") {
|
|
231
|
+
throw new AgentError("prReadInvalidResponse");
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return response;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export function formatPRList(response, labels = {}) {
|
|
238
|
+
return response.items.map((item) => [
|
|
239
|
+
safeInline(item.repository),
|
|
240
|
+
`#${item.number}`,
|
|
241
|
+
safeInline(item.status === "UNKNOWN" ? (labels.statusUnavailable ?? item.status) : item.status),
|
|
242
|
+
`${labels.ci ?? "CI"}:${safeInline(item.ciStatus)}`,
|
|
243
|
+
`${labels.agent ?? "Agent"}:${safeInline(item.raftAgentId)}`,
|
|
244
|
+
safeInline(item.title),
|
|
245
|
+
safeInline(item.updatedAt),
|
|
246
|
+
].join("\t"));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export function formatPRDetail(detail, labels) {
|
|
250
|
+
const lines = [
|
|
251
|
+
`${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
|
|
252
|
+
`${labels.head}: ${safeInline(detail.headSha)}`,
|
|
253
|
+
`${labels.checks}: ${safeInline(detail.ciStatus)}`,
|
|
254
|
+
`${labels.review}: ${safeInline(detail.reviewStatus)}`,
|
|
255
|
+
safeInline(detail.url),
|
|
256
|
+
];
|
|
257
|
+
if (typeof detail.body === "string" && detail.body !== "") lines.push("", safeMultiline(detail.body));
|
|
258
|
+
return lines;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function formatPRDiff(response, nameOnly, unavailableLabel) {
|
|
262
|
+
if (nameOnly) return response.files.map((file) => safeInline(file.path));
|
|
263
|
+
return response.files.map((file) => {
|
|
264
|
+
const summary = `${safeInline(file.path)}\t${safeInline(file.status)}\t+${file.additions}\t-${file.deletions}`;
|
|
265
|
+
if (typeof file.patch === "string" && file.patch !== "") return `${summary}\n${safeMultiline(file.patch)}`;
|
|
266
|
+
return `${summary}\t${unavailableLabel}`;
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function formatPRChecks(detail) {
|
|
271
|
+
return detail.checks.map((check) => [check.name, check.status, check.conclusion || "-", check.url].map(safeInline).join("\t"));
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function prChecksExitCode(detail) {
|
|
275
|
+
// Match `gh pr checks`: an empty check set is not evidence that CI passed.
|
|
276
|
+
// Keep it non-zero so automation cannot treat an unconfigured or unavailable
|
|
277
|
+
// check suite as a green pull request.
|
|
278
|
+
if (detail.checks.length === 0) return 1;
|
|
279
|
+
let pending = false;
|
|
280
|
+
for (const check of detail.checks) {
|
|
281
|
+
const status = check.status.toLowerCase();
|
|
282
|
+
const conclusion = check.conclusion.toLowerCase();
|
|
283
|
+
if (pendingCheckStates.has(status)) {
|
|
284
|
+
pending = true;
|
|
285
|
+
} else if (status === "completed") {
|
|
286
|
+
if (conclusion === "") pending = true;
|
|
287
|
+
else if (!terminalPassConclusions.has(conclusion)) return 1;
|
|
288
|
+
} else if (status === "success") {
|
|
289
|
+
// The server projects legacy commit statuses as the same state in both
|
|
290
|
+
// fields. An inconsistent payload must not let `status=success` mask a
|
|
291
|
+
// failing conclusion.
|
|
292
|
+
if (conclusion !== "success") return 1;
|
|
293
|
+
} else {
|
|
294
|
+
// Legacy commit statuses use status=success|failure|error instead of a
|
|
295
|
+
// check-run's completed + conclusion pair. Unknown terminal values fail
|
|
296
|
+
// closed rather than silently reporting a green PR.
|
|
297
|
+
return 1;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return pending ? 8 : 0;
|
|
301
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
export function parseRepoCloneArgs(args) {
|
|
4
|
+
const dash = args.indexOf("--");
|
|
5
|
+
const gitFlags = dash === -1 ? [] : args.slice(dash + 1);
|
|
6
|
+
const rest = dash === -1 ? args : args.slice(0, dash);
|
|
7
|
+
const repository = rest[0];
|
|
8
|
+
const directory = rest[1];
|
|
9
|
+
if (!repository || rest.length > 2) {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
return { repository, directory, gitFlags };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function parseRepository(input, defaultOwner) {
|
|
16
|
+
const raw = String(input ?? "").trim();
|
|
17
|
+
if (!raw) return null;
|
|
18
|
+
let value = raw.replace(/\.git$/i, "");
|
|
19
|
+
const github = value.match(
|
|
20
|
+
/^(?:https?:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+)\/([^/]+)\/?$/i,
|
|
21
|
+
);
|
|
22
|
+
if (github) {
|
|
23
|
+
return { owner: github[1], name: github[2] };
|
|
24
|
+
}
|
|
25
|
+
if (!value.includes("://") && !value.includes("@") && value.includes("/")) {
|
|
26
|
+
const parts = value.split("/").filter(Boolean);
|
|
27
|
+
if (parts.length === 2) {
|
|
28
|
+
return { owner: parts[0], name: parts[1] };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (!value.includes("/") && !value.includes(":") && defaultOwner) {
|
|
32
|
+
return { owner: defaultOwner, name: value };
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function gatewayCloneURL(host, port, owner, name) {
|
|
38
|
+
const hostname = String(host ?? "").trim();
|
|
39
|
+
const parsedPort = Number(port);
|
|
40
|
+
const sshPort = Number.isInteger(parsedPort) && parsedPort > 0 ? parsedPort : 22;
|
|
41
|
+
const authority = hostname.includes(":") ? `[${hostname}]:${sshPort}` : `${hostname}:${sshPort}`;
|
|
42
|
+
return `ssh://git@${authority}/${owner}/${name}.git`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function runGitClone({ url, directory, gitFlags, env, spawnImpl = spawn }) {
|
|
46
|
+
const args = ["clone", ...(gitFlags ?? []), url];
|
|
47
|
+
if (directory) args.push(directory);
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const child = spawnImpl("git", args, {
|
|
50
|
+
env: env ?? process.env,
|
|
51
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
52
|
+
});
|
|
53
|
+
let stdout = "";
|
|
54
|
+
let stderr = "";
|
|
55
|
+
child.stdout?.on("data", (b) => { stdout += b; });
|
|
56
|
+
child.stderr?.on("data", (b) => { stderr += b; });
|
|
57
|
+
child.on("error", reject);
|
|
58
|
+
child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
|
|
59
|
+
});
|
|
60
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botiverse/stamp-cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "CLI for Stamp — Agent Git gateway in the Raft loop (bin stamp; future origin stamp.build)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
},
|
|
24
24
|
"repository": {
|
|
25
25
|
"type": "git",
|
|
26
|
-
"url": "git+https://github.com/botiverse/
|
|
26
|
+
"url": "git+https://github.com/botiverse/stamp.git"
|
|
27
27
|
},
|
|
28
28
|
"publishConfig": {
|
|
29
29
|
"access": "public"
|