@pecot/workflow-mcp 5.0.0 → 7.0.0
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/.claude-plugin/plugin.json +1 -1
- package/README.md +27 -22
- package/cli/dist/cli.js +6 -1
- package/cli/dist/commands/board-add.d.ts +3 -0
- package/cli/dist/commands/board-add.js +69 -0
- package/cli/dist/commands/board-judgment.d.ts +69 -0
- package/cli/dist/commands/board-judgment.js +150 -0
- package/cli/dist/commands/board-move.d.ts +3 -0
- package/cli/dist/commands/board-move.js +65 -0
- package/cli/dist/commands/board-readiness.d.ts +34 -0
- package/cli/dist/commands/board-readiness.js +108 -0
- package/cli/dist/commands/board-show.d.ts +3 -0
- package/cli/dist/commands/board-show.js +75 -0
- package/cli/dist/commands/board-sync.d.ts +3 -0
- package/cli/dist/commands/board-sync.js +120 -0
- package/cli/dist/commands/board-view.d.ts +151 -0
- package/cli/dist/commands/board-view.js +293 -0
- package/cli/dist/commands/board.d.ts +3 -0
- package/cli/dist/commands/board.js +12 -0
- package/cli/dist/commands/branch.d.ts +3 -0
- package/cli/dist/commands/branch.js +111 -0
- package/cli/dist/commands/command-binding.js +4 -0
- package/cli/dist/commands/command-definition.d.ts +39 -8
- package/cli/dist/commands/command-definition.js +20 -7
- package/cli/dist/commands/command-help.js +2 -2
- package/cli/dist/commands/command-hint.d.ts +5 -0
- package/cli/dist/commands/command-hint.js +13 -0
- package/cli/dist/commands/command-stop.d.ts +5 -3
- package/cli/dist/commands/command-stop.js +7 -6
- package/cli/dist/commands/failure-kind.d.ts +3 -0
- package/cli/dist/commands/failure-kind.js +35 -0
- package/cli/dist/commands/failure.d.ts +6 -0
- package/cli/dist/commands/failure.js +29 -3
- package/cli/dist/commands/github-client.d.ts +6 -2
- package/cli/dist/commands/github-client.js +13 -3
- package/cli/dist/commands/help.js +8 -13
- package/cli/dist/commands/issue-board.d.ts +61 -0
- package/cli/dist/commands/issue-board.js +85 -1
- package/cli/dist/commands/issue-comment.js +66 -30
- package/cli/dist/commands/issue-create.js +632 -92
- package/cli/dist/commands/issue-dependency.d.ts +3 -0
- package/cli/dist/commands/issue-dependency.js +310 -0
- package/cli/dist/commands/issue-readiness.d.ts +122 -0
- package/cli/dist/commands/issue-readiness.js +253 -0
- package/cli/dist/commands/issue-reopen.d.ts +3 -0
- package/cli/dist/commands/issue-reopen.js +130 -0
- package/cli/dist/commands/issue-shared.d.ts +33 -20
- package/cli/dist/commands/issue-shared.js +84 -76
- package/cli/dist/commands/issue-show.d.ts +3 -0
- package/cli/dist/commands/issue-show.js +239 -0
- package/cli/dist/commands/issue.d.ts +0 -1
- package/cli/dist/commands/issue.js +6 -8
- package/cli/dist/commands/names.d.ts +33 -0
- package/cli/dist/commands/names.js +63 -0
- package/cli/dist/commands/output.d.ts +32 -4
- package/cli/dist/commands/output.js +28 -8
- package/cli/dist/commands/pr-merge.d.ts +3 -0
- package/cli/dist/commands/pr-merge.js +230 -0
- package/cli/dist/commands/pr-reference.d.ts +8 -0
- package/cli/dist/commands/pr-reference.js +30 -0
- package/cli/dist/commands/pr-restack.d.ts +6 -0
- package/cli/dist/commands/pr-restack.js +233 -0
- package/cli/dist/commands/pr-waiting.d.ts +59 -0
- package/cli/dist/commands/pr-waiting.js +143 -0
- package/cli/dist/commands/pr.d.ts +23 -0
- package/cli/dist/commands/pr.js +378 -366
- package/cli/dist/commands/project-sync.d.ts +12 -3
- package/cli/dist/commands/project-sync.js +23 -13
- package/cli/dist/commands/project.d.ts +3 -2
- package/cli/dist/commands/project.js +371 -177
- package/cli/dist/commands/registry.js +15 -10
- package/cli/dist/commands/release.d.ts +2 -2
- package/cli/dist/commands/release.js +118 -130
- package/cli/dist/commands/renamed-commands.d.ts +26 -0
- package/cli/dist/commands/renamed-commands.js +53 -0
- package/cli/dist/commands/repository-match.js +9 -3
- package/cli/dist/commands/session-finish.d.ts +3 -0
- package/cli/dist/commands/session-finish.js +383 -0
- package/cli/dist/commands/session-start.d.ts +3 -0
- package/cli/dist/commands/session-start.js +252 -0
- package/cli/dist/commands/session.d.ts +3 -0
- package/cli/dist/commands/session.js +186 -32
- package/cli/dist/commands/tracker-sync-dependabot.d.ts +7 -0
- package/cli/dist/commands/{dependabot.js → tracker-sync-dependabot.js} +76 -68
- package/cli/dist/commands/tracker-sync-security.d.ts +7 -0
- package/cli/dist/commands/{security.js → tracker-sync-security.js} +71 -64
- package/cli/dist/commands/tracker-sync.d.ts +37 -0
- package/cli/dist/commands/tracker-sync.js +18 -6
- package/cli/dist/commands/tracker.d.ts +3 -0
- package/cli/dist/commands/tracker.js +20 -0
- package/cli/dist/commands/usage-error.d.ts +4 -0
- package/cli/dist/commands/usage-error.js +6 -0
- package/cli/dist/commands/work-target.d.ts +20 -3
- package/cli/dist/commands/work-target.js +49 -6
- package/cli/dist/commands/worktree.js +103 -33
- package/cli/dist/domain/batch-plan.d.ts +73 -0
- package/cli/dist/domain/batch-plan.js +114 -0
- package/cli/dist/domain/blocked-by-change.d.ts +99 -0
- package/cli/dist/domain/blocked-by-change.js +101 -0
- package/cli/dist/domain/board-move.d.ts +90 -0
- package/cli/dist/domain/board-move.js +92 -0
- package/cli/dist/domain/branch-name.js +1 -1
- package/cli/dist/domain/command-hint.d.ts +85 -0
- package/cli/dist/domain/command-hint.js +148 -0
- package/cli/dist/domain/config.d.ts +4 -0
- package/cli/dist/domain/config.js +11 -1
- package/cli/dist/domain/dependabot.js +1 -1
- package/cli/dist/domain/errors.d.ts +5 -0
- package/cli/dist/domain/errors.js +5 -0
- package/cli/dist/domain/format.d.ts +51 -4
- package/cli/dist/domain/format.js +72 -6
- package/cli/dist/domain/frontmatter.d.ts +18 -3
- package/cli/dist/domain/frontmatter.js +38 -12
- package/cli/dist/domain/issue-order.d.ts +55 -0
- package/cli/dist/domain/issue-order.js +65 -0
- package/cli/dist/domain/issue-readout.d.ts +36 -4
- package/cli/dist/domain/pull-request.d.ts +71 -4
- package/cli/dist/domain/pull-request.js +59 -10
- package/cli/dist/domain/readiness.d.ts +44 -0
- package/cli/dist/domain/readiness.js +153 -5
- package/cli/dist/domain/reference-parser.d.ts +3 -1
- package/cli/dist/domain/reference-parser.js +6 -2
- package/cli/dist/domain/release.d.ts +7 -3
- package/cli/dist/domain/release.js +5 -12
- package/cli/dist/domain/repository-policy.d.ts +9 -3
- package/cli/dist/domain/repository-policy.js +8 -7
- package/cli/dist/domain/repository-resolver.js +4 -1
- package/cli/dist/domain/restack.d.ts +62 -0
- package/cli/dist/domain/restack.js +53 -0
- package/cli/dist/domain/security-alerts.js +1 -1
- package/cli/dist/domain/state.d.ts +69 -0
- package/cli/dist/domain/state.js +67 -1
- package/cli/dist/domain/work-start.d.ts +30 -0
- package/cli/dist/domain/work-start.js +42 -0
- package/cli/dist/infra/authored-notes.d.ts +1 -1
- package/cli/dist/infra/authored-notes.js +10 -4
- package/cli/dist/infra/config-store.d.ts +4 -0
- package/cli/dist/infra/config-store.js +13 -0
- package/cli/dist/infra/git.d.ts +76 -0
- package/cli/dist/infra/git.js +123 -1
- package/cli/dist/infra/github/client.d.ts +5 -0
- package/cli/dist/infra/github/client.js +10 -7
- package/cli/dist/infra/github/errors.d.ts +18 -0
- package/cli/dist/infra/github/errors.js +22 -0
- package/cli/dist/infra/github/issues.d.ts +39 -3
- package/cli/dist/infra/github/issues.js +178 -23
- package/cli/dist/infra/github/projects.d.ts +35 -0
- package/cli/dist/infra/github/projects.js +89 -8
- package/cli/dist/infra/github/pulls.d.ts +105 -2
- package/cli/dist/infra/github/pulls.js +172 -5
- package/cli/dist/infra/github/queries.d.ts +15 -4
- package/cli/dist/infra/github/queries.js +203 -40
- package/cli/dist/infra/github/readout.d.ts +5 -1
- package/cli/dist/infra/github/readout.js +11 -33
- package/cli/dist/infra/github/repos.d.ts +18 -0
- package/cli/dist/infra/github/repos.js +31 -0
- package/cli/dist/infra/nx-scope.d.ts +1 -1
- package/cli/dist/infra/nx-scope.js +1 -1
- package/cli/dist/infra/state-store.d.ts +10 -1
- package/cli/dist/infra/state-store.js +14 -2
- package/cli/dist/infra/worktree-links.d.ts +3 -0
- package/cli/dist/infra/worktree-links.js +8 -1
- package/cli/dist/infra/worktree.d.ts +12 -1
- package/cli/dist/infra/worktree.js +40 -23
- package/cli/dist/mcp/result.d.ts +82 -7
- package/cli/dist/mcp/result.js +139 -19
- package/cli/dist/mcp/server.d.ts +2 -2
- package/cli/dist/mcp/server.js +57 -10
- package/cli/templates/comment/plan.md +14 -0
- package/cli/templates/comment/review-findings.md +3 -2
- package/cli/templates/issue/bug.md +13 -4
- package/cli/templates/issue/task-implement.md +13 -6
- package/cli/templates/issue/task.md +13 -4
- package/cli/templates/workflow/pecot-board-sync.yml +84 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/cli/dist/commands/dependabot.d.ts +0 -3
- package/cli/dist/commands/issue-project.d.ts +0 -3
- package/cli/dist/commands/issue-project.js +0 -176
- package/cli/dist/commands/issue-quick.d.ts +0 -3
- package/cli/dist/commands/issue-quick.js +0 -126
- package/cli/dist/commands/issue-read.d.ts +0 -3
- package/cli/dist/commands/issue-read.js +0 -80
- package/cli/dist/commands/project-info.d.ts +0 -48
- package/cli/dist/commands/project-info.js +0 -181
- package/cli/dist/commands/repository.d.ts +0 -5
- package/cli/dist/commands/repository.js +0 -265
- package/cli/dist/commands/security.d.ts +0 -3
package/cli/dist/commands/pr.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/* eslint-disable security/detect-non-literal-fs-filename -- パスは利用者が指定する */
|
|
2
2
|
/* eslint-disable @typescript-eslint/prefer-readonly-parameter-types -- GitHubClient は内部の状態を持つ */
|
|
3
|
-
//
|
|
3
|
+
// pr create・pr show・pr check。cli/commands/pr.py の移植。
|
|
4
4
|
// 途中で抜ける箇所は CommandExit を投げ、defineCommand が終了コードにする。
|
|
5
5
|
import { existsSync, statSync, writeFileSync } from 'node:fs';
|
|
6
6
|
import path from 'node:path';
|
|
@@ -13,44 +13,49 @@ import { FrontmatterError } from '../domain/frontmatter.js';
|
|
|
13
13
|
import { parseRemoteUrl } from '../domain/git-url.js';
|
|
14
14
|
import { isEpicIssue } from '../domain/issue-kind.js';
|
|
15
15
|
import { jsonField } from '../domain/json.js';
|
|
16
|
-
import { appendIssueCloseIfNeeded, collectPreflightWarnings,
|
|
16
|
+
import { appendIssueCloseIfNeeded, collectPreflightWarnings, decidePullRequestBase, describeBaseStop, describePushStatus, formatPreflightWarning, formatPullRequestMarkdown, formatPullRequestWithReviewsMarkdown, isReleasePullRequest, pickLowerPullRequest, validatePullRequestContent } from '../domain/pull-request.js';
|
|
17
17
|
import { parsePythonInteger, pythonStrip } from '../domain/python-format.js';
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import { FLAG_MERGE_SLASH_PENDING, FLAG_PECOT_ACTIVE, FLAG_PECOT_QUICK_MODE, FLAG_PECOT_SESSION_TITLE, FLAG_PR_CREATE_SLASH_PENDING, FLAG_WIP_BRANCH_LINKED } from '../domain/state.js';
|
|
18
|
+
import { splitOwnerRepository } from '../domain/repository-resolver.js';
|
|
19
|
+
import { FLAG_PECOT_ACTIVE, FLAG_PR_CREATE_SLASH_PENDING } from '../domain/state.js';
|
|
21
20
|
import { loadActiveConfig } from '../infra/config-store.js';
|
|
22
21
|
import { parsePullRequestFile } from '../infra/frontmatter-file.js';
|
|
23
|
-
import { gitCurrentBranch,
|
|
24
|
-
import {
|
|
22
|
+
import { gitCurrentBranch, gitRemoteUrl, gitStdout, gitToplevel, primaryRemoteName, remoteBranchHead, runGit } from '../infra/git.js';
|
|
23
|
+
import { TransportFailure } from '../infra/github/client.js';
|
|
24
|
+
import { GitHubAPIError } from '../infra/github/errors.js';
|
|
25
25
|
import { changedFiles, expectedScope, nxProjects, parseTitleScope } from '../infra/nx-scope.js';
|
|
26
26
|
import { isFileNotFound } from '../infra/os-error.js';
|
|
27
27
|
import { outputDirectory, OutputPathReservationError, resolveRealPath, withReservedOutputPath } from '../infra/paths.js';
|
|
28
|
-
import { consumeFlag,
|
|
28
|
+
import { consumeFlag, readBaseRecord, readFlag } from '../infra/state-store.js';
|
|
29
29
|
import { readTemplateSections, templateFile } from '../infra/template-store.js';
|
|
30
30
|
import { readTextFile } from '../infra/text-file.js';
|
|
31
|
-
import {
|
|
31
|
+
import { commandHint, hinted, inputHint, inputNameHint, placeholder } from './command-hint.js';
|
|
32
32
|
import { requireActiveConfigPlain, stopWith } from './command-stop.js';
|
|
33
|
-
import {
|
|
33
|
+
import { kindOfFailure } from './failure.js';
|
|
34
34
|
import { directorySchema } from './directory-option.js';
|
|
35
35
|
import { createGitHubClient } from './github-client.js';
|
|
36
|
-
import { createOutput } from './output.js';
|
|
36
|
+
import { createOutput, DRY_RUN_FIELD } from './output.js';
|
|
37
37
|
import { CommandExit, defineCommand } from './command-definition.js';
|
|
38
|
-
import {
|
|
39
|
-
|
|
38
|
+
import { BOARD_MOVE_JSON, moveJson } from './issue-board.js';
|
|
39
|
+
import { PR_MERGE_COMMAND } from './pr-merge.js';
|
|
40
|
+
import { parseReference, PR_REFERENCE_DESCRIPTION } from './pr-reference.js';
|
|
41
|
+
import { moveWaitingIssues } from './pr-waiting.js';
|
|
42
|
+
export { parseReference, PR_REFERENCE_DESCRIPTION } from './pr-reference.js';
|
|
40
43
|
// 本文の検証の失敗。1(通信・設定・引数)と 2(preflight)と区別する
|
|
41
44
|
const VALIDATION_EXIT_CODE = 3;
|
|
42
45
|
const PREFLIGHT_EXIT_CODE = 2;
|
|
46
|
+
// 下の段の PR が開いておらず、マージもされていない
|
|
47
|
+
const NO_OPEN_BASE_EXIT_CODE = 2;
|
|
43
48
|
// Python の `{e}` に当たる、例外の文
|
|
44
|
-
function reasonOf(error) {
|
|
49
|
+
export function reasonOf(error) {
|
|
45
50
|
return error instanceof Error ? error.message : String(error);
|
|
46
51
|
}
|
|
47
52
|
function templateKindOf(template) {
|
|
48
53
|
return template === 'release' ? 'release' : 'create';
|
|
49
54
|
}
|
|
50
|
-
function isPositive(value) {
|
|
55
|
+
export function isPositive(value) {
|
|
51
56
|
return value !== undefined && value !== 0;
|
|
52
57
|
}
|
|
53
|
-
function primaryRemote(directory) {
|
|
58
|
+
export function primaryRemote(directory) {
|
|
54
59
|
const name = primaryRemoteName(directory);
|
|
55
60
|
if (name === undefined)
|
|
56
61
|
return undefined;
|
|
@@ -66,10 +71,11 @@ function primaryRemote(directory) {
|
|
|
66
71
|
throw error;
|
|
67
72
|
}
|
|
68
73
|
}
|
|
69
|
-
// scope を nx のプロジェクトと比べる対象か。release_type が nx
|
|
70
|
-
|
|
74
|
+
// scope を nx のプロジェクトと比べる対象か。release_type が nx で、base が develop か積んだ base で、remote と作業ツリーが対象に合うときだけ。
|
|
75
|
+
// 下の段を squash でマージした後は、開発ブランチとの差分がその段のファイルも含むので、記録のコミットから比べる
|
|
76
|
+
function nxScopeTarget(config, owner, repository, base, directory, stacked) {
|
|
71
77
|
const configured = findRepository(config, owner, repository);
|
|
72
|
-
if (configured === undefined || effectiveReleaseType(configured) !== 'nx' || (base !== getDevelopBranch(config, owner, repository)))
|
|
78
|
+
if (configured === undefined || effectiveReleaseType(configured) !== 'nx' || (stacked === undefined && base !== getDevelopBranch(config, owner, repository)))
|
|
73
79
|
return undefined;
|
|
74
80
|
const found = primaryRemote(directory);
|
|
75
81
|
const location = found?.location;
|
|
@@ -77,7 +83,11 @@ function nxScopeTarget(config, owner, repository, base, directory) {
|
|
|
77
83
|
if (found === undefined || !isSameRepository)
|
|
78
84
|
return undefined;
|
|
79
85
|
const toplevel = gitToplevel({ cwd: directory });
|
|
80
|
-
|
|
86
|
+
if (toplevel === undefined || !isRegularFile(path.join(toplevel, 'nx.json')))
|
|
87
|
+
return undefined;
|
|
88
|
+
if (stacked === undefined)
|
|
89
|
+
return { toplevel, from: `${found.name}/${base}` };
|
|
90
|
+
return { toplevel, from: 'sha' in stacked ? stacked.sha : `${found.name}/${stacked.branch}` };
|
|
81
91
|
}
|
|
82
92
|
// Python の Path.is_file() と同じく、stat の失敗は「無い」と扱う
|
|
83
93
|
function isRegularFile(file) {
|
|
@@ -88,9 +98,9 @@ function isRegularFile(file) {
|
|
|
88
98
|
return false;
|
|
89
99
|
}
|
|
90
100
|
}
|
|
91
|
-
function expectedTitleScope(target,
|
|
101
|
+
function expectedTitleScope(target, head, out) {
|
|
92
102
|
const projects = nxProjects(target.toplevel);
|
|
93
|
-
const files = projects === undefined ? undefined : changedFiles(target.toplevel,
|
|
103
|
+
const files = projects === undefined ? undefined : changedFiles(target.toplevel, target.from, head);
|
|
94
104
|
if (projects === undefined || files === undefined) {
|
|
95
105
|
out.warning('cannot read nx projects or the diff; skipped the PR title scope check');
|
|
96
106
|
return undefined;
|
|
@@ -101,10 +111,10 @@ function titleScopeErrors(query, out) {
|
|
|
101
111
|
const { config, owner, repository, title, base, head, directory, template, developBranch, releaseBranch } = query;
|
|
102
112
|
if (isReleasePullRequest(template, base, head, developBranch, releaseBranch))
|
|
103
113
|
return [];
|
|
104
|
-
const target = nxScopeTarget(config, owner, repository, base, directory);
|
|
114
|
+
const target = nxScopeTarget(config, owner, repository, base, directory, query.stacked);
|
|
105
115
|
if (target === undefined)
|
|
106
116
|
return [];
|
|
107
|
-
const expected = expectedTitleScope(target,
|
|
117
|
+
const expected = expectedTitleScope(target, head, out);
|
|
108
118
|
if (expected === undefined || expected.length === 0)
|
|
109
119
|
return [];
|
|
110
120
|
const given = parseTitleScope(title);
|
|
@@ -114,13 +124,30 @@ function titleScopeErrors(query, out) {
|
|
|
114
124
|
return [`PR title scope must be ${expected.join(',')} (given: ${shown}; computed from the tags of the changed nx projects)`];
|
|
115
125
|
}
|
|
116
126
|
// pr create
|
|
127
|
+
const PR_CREATE_OUTPUT = z.strictObject({
|
|
128
|
+
url: z.string().optional().describe('URL of the created PR (omitted on dry_run and prepare)'),
|
|
129
|
+
number: z.int().optional().describe('Number of the created PR (omitted on dry_run and prepare, or when the response has none)'),
|
|
130
|
+
head: z.string().optional().describe('Head branch of the PR (omitted on prepare)'),
|
|
131
|
+
base: z.string().optional().describe('Base branch of the PR. On prepare, the base filled into the draft (omitted when it was not filled)'),
|
|
132
|
+
title: z.string().optional().describe('Title of the PR (omitted on prepare)'),
|
|
133
|
+
inReview: z.int().optional().describe('Issue number whose status was set to In Review (omitted when not set)'),
|
|
134
|
+
stack: z.strictObject({
|
|
135
|
+
lower: z.int().describe('PR number of the lower stage the new PR is stacked on'),
|
|
136
|
+
registered: z.boolean().optional().describe('Whether the new PR was registered to the stack (omitted on dry_run)'),
|
|
137
|
+
number: z.int().optional().describe('Stack number (omitted when not registered)'),
|
|
138
|
+
}).optional().describe('Stack of the PR (omitted when the PR is not stacked)'),
|
|
139
|
+
moves: z.array(BOARD_MOVE_JSON).optional().describe('Issues waiting for this PR whose column or Status was written (omitted on dry_run and prepare)'),
|
|
140
|
+
file: z.string().optional().describe('Absolute path of the draft file written on prepare'),
|
|
141
|
+
dryRun: DRY_RUN_FIELD,
|
|
142
|
+
});
|
|
117
143
|
function inReviewOperation(issueNumber) {
|
|
118
144
|
return { verb: 'set', target: `Issue #${String(issueNumber)} status to In Review` };
|
|
119
145
|
}
|
|
146
|
+
// Status を In Review にした Issue の番号を返す。書かなかったら undefined
|
|
120
147
|
async function updateIssueStatusToInReview(config, client, location, headBranch, out) {
|
|
121
148
|
const issueNumber = extractIssueNumberFromBranch(headBranch);
|
|
122
149
|
if (issueNumber === undefined)
|
|
123
|
-
return;
|
|
150
|
+
return undefined;
|
|
124
151
|
const label = `Issue #${String(issueNumber)}`;
|
|
125
152
|
let itemId;
|
|
126
153
|
try {
|
|
@@ -152,21 +179,24 @@ async function updateIssueStatusToInReview(config, client, location, headBranch,
|
|
|
152
179
|
return;
|
|
153
180
|
}
|
|
154
181
|
out.done(inReviewOperation(issueNumber));
|
|
182
|
+
return issueNumber;
|
|
155
183
|
}
|
|
184
|
+
const LINK_PATH = ['project', 'link'];
|
|
185
|
+
const PR_CREATE_PATH = ['pr', 'create'];
|
|
156
186
|
function exitOnUnsetBranch(template, base, head, developBranch, releaseBranch, out) {
|
|
157
187
|
const isRelease = isReleasePullRequest(template, base, head, developBranch, releaseBranch);
|
|
158
188
|
if (isRelease && (releaseBranch === undefined || releaseBranch === '')) {
|
|
159
|
-
stopWith(out,
|
|
189
|
+
stopWith(out, hinted `release_branch is not set\nset it with: ${commandHint(LINK_PATH, { repo: 'owner/repo', release_branch: 'main' })}`, 'repo-setting-missing');
|
|
160
190
|
}
|
|
161
191
|
if (!isRelease && (developBranch === undefined || developBranch === '')) {
|
|
162
|
-
stopWith(out,
|
|
192
|
+
stopWith(out, hinted `develop_branch is not set\nset it with: ${commandHint(LINK_PATH, { repo: 'owner/repo', develop_branch: 'develop' })}`, 'repo-setting-missing');
|
|
163
193
|
}
|
|
164
194
|
}
|
|
165
195
|
function resolveHeadBranch(head, directory, out) {
|
|
166
196
|
if (head !== undefined && head !== '')
|
|
167
197
|
return head;
|
|
168
198
|
const current = gitCurrentBranch(directory);
|
|
169
|
-
return current === undefined || current === '' ? stopWith(out, 'cannot determine the head branch') : current;
|
|
199
|
+
return current === undefined || current === '' ? stopWith(out, 'cannot determine the head branch', 'git-unresolved') : current;
|
|
170
200
|
}
|
|
171
201
|
async function appendCloseUnlessEpic(config, location, body, issueNumber, out) {
|
|
172
202
|
try {
|
|
@@ -187,7 +217,7 @@ function exitOnValidationErrors(errors, out) {
|
|
|
187
217
|
return;
|
|
188
218
|
for (const error of errors)
|
|
189
219
|
out.error(error);
|
|
190
|
-
throw new CommandExit(VALIDATION_EXIT_CODE);
|
|
220
|
+
throw new CommandExit(VALIDATION_EXIT_CODE, 'content-invalid');
|
|
191
221
|
}
|
|
192
222
|
function createOperation(draft) {
|
|
193
223
|
const kind = draft.isDraft ? 'draft PR' : 'PR';
|
|
@@ -224,18 +254,18 @@ function getPushStatus(branch, cwd, remote) {
|
|
|
224
254
|
const behindCount = behind === undefined ? undefined : parsePythonInteger(pythonStrip(behind));
|
|
225
255
|
return aheadCount === undefined || behindCount === undefined ? failed : describePushStatus(remote, branch, aheadCount, behindCount);
|
|
226
256
|
}
|
|
227
|
-
// pr create の早い確認と pr
|
|
228
|
-
function validatePullRequestContext(directory, out) {
|
|
257
|
+
// pr create の早い確認と pr check が共有する前提。満たさなければ終了コード 1
|
|
258
|
+
export function validatePullRequestContext(directory, out) {
|
|
229
259
|
if (gitToplevel({ cwd: directory }) === undefined)
|
|
230
|
-
stopWith(out, 'not a git repository');
|
|
260
|
+
stopWith(out, 'not a git repository', 'git-unresolved');
|
|
231
261
|
const found = primaryRemote(directory);
|
|
232
262
|
if (found === undefined)
|
|
233
|
-
return stopWith(out, 'git remote not found');
|
|
263
|
+
return stopWith(out, 'git remote not found', 'git-unresolved');
|
|
234
264
|
const currentBranch = gitCurrentBranch(directory);
|
|
235
265
|
if (currentBranch === undefined)
|
|
236
|
-
return stopWith(out, 'cannot determine the current branch');
|
|
266
|
+
return stopWith(out, 'cannot determine the current branch', 'git-unresolved');
|
|
237
267
|
if (found.location === undefined)
|
|
238
|
-
return stopWith(out, 'cannot read repository info from the remote URL\ncheck it with: git remote -v');
|
|
268
|
+
return stopWith(out, 'cannot read repository info from the remote URL\ncheck it with: git remote -v', 'git-unresolved');
|
|
239
269
|
return { remoteUrl: found.url, currentBranch, location: found.location, remoteName: found.name };
|
|
240
270
|
}
|
|
241
271
|
function runPreflightChecksOrExit(directory, out) {
|
|
@@ -246,35 +276,166 @@ function runPreflightChecksOrExit(directory, out) {
|
|
|
246
276
|
return;
|
|
247
277
|
out.error('preflight found warnings; fix them before creating a PR');
|
|
248
278
|
printPreflightWarnings(out, warnings);
|
|
249
|
-
throw new CommandExit(PREFLIGHT_EXIT_CODE);
|
|
279
|
+
throw new CommandExit(PREFLIGHT_EXIT_CODE, 'preflight-failed');
|
|
280
|
+
}
|
|
281
|
+
// PR を作った後の処理の失敗は warning にとどめ、URL の出力まで進める
|
|
282
|
+
function isRequestFailure(error) {
|
|
283
|
+
return error instanceof GitHubAPIError || error instanceof TransportFailure;
|
|
284
|
+
}
|
|
285
|
+
function describeRequestFailure(error) {
|
|
286
|
+
return error instanceof GitHubAPIError ? describeApiError(error) : error.message;
|
|
287
|
+
}
|
|
288
|
+
// 1 回の pr create で、クライアントを作るのは要るときの 1 回だけにする
|
|
289
|
+
function lazyClient(config, out) {
|
|
290
|
+
let client;
|
|
291
|
+
return () => {
|
|
292
|
+
client ??= createGitHubClient(out, config.host);
|
|
293
|
+
return client;
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
// 下の段の PR が入っているスタックに足す。無ければ下の段と新しい PR で作る。失敗は warning にとどめる
|
|
297
|
+
async function registerStack(client, location, lower, created, out) {
|
|
298
|
+
const unregistered = { lower, registered: false };
|
|
299
|
+
if (created === undefined) {
|
|
300
|
+
out.warning('could not register stack: the PR creation response has no PR number');
|
|
301
|
+
return unregistered;
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
const stack = await client.getStackOfPullRequest(location.owner, location.repository, lower);
|
|
305
|
+
const top = stack?.pullRequests.at(-1);
|
|
306
|
+
// GitHub は一番上にしか足せないので、同じ下の段に 2 つ目を積んだときは 422 を待たずに知らせる
|
|
307
|
+
if (stack !== undefined && top !== lower) {
|
|
308
|
+
out.warning(`could not register stack: PR #${String(lower)} is not the top of stack #${String(stack.number)} (top: PR #${String(top)}); PR #${String(created)} was not added`);
|
|
309
|
+
return unregistered;
|
|
310
|
+
}
|
|
311
|
+
const registered = stack === undefined
|
|
312
|
+
? await client.createStack(location.owner, location.repository, [lower, created])
|
|
313
|
+
: await client.addToStack(location.owner, location.repository, stack.number, [created]);
|
|
314
|
+
out.done({ verb: 'add', target: `PR #${String(created)} to stack #${String(registered.number)}` });
|
|
315
|
+
return { lower, registered: true, number: registered.number };
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
if (!isRequestFailure(error))
|
|
319
|
+
throw error;
|
|
320
|
+
out.warning(`could not register stack: ${describeRequestFailure(error)}`);
|
|
321
|
+
return unregistered;
|
|
322
|
+
}
|
|
250
323
|
}
|
|
251
|
-
|
|
324
|
+
// moves に、書けた列と札を足していく。例外で止まっても、それまでの分が残る
|
|
325
|
+
async function moveWaitingIssuesSafely(client, config, location, issueNumber, pullRequest, out, moves) {
|
|
326
|
+
try {
|
|
327
|
+
await moveWaitingIssues(out, client, config, { repository: location, issueNumber, pullRequest }, moves);
|
|
328
|
+
}
|
|
329
|
+
catch (error) {
|
|
330
|
+
if (!isRequestFailure(error))
|
|
331
|
+
throw error;
|
|
332
|
+
out.warning(`could not move the Issues waiting for #${String(issueNumber)}: ${describeRequestFailure(error)}`);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
async function submitPullRequest(config, client, directory, draft, stackOn, out) {
|
|
252
336
|
runPreflightChecksOrExit(directory, out);
|
|
253
|
-
const client = createGitHubClient(out, config.host);
|
|
254
337
|
let created;
|
|
255
338
|
try {
|
|
256
|
-
created = await client.createPullRequest(draft.location.owner, draft.location.repository, draft.title, draft.body, draft.head, draft.base, draft.isDraft);
|
|
339
|
+
created = await client().createPullRequest(draft.location.owner, draft.location.repository, draft.title, draft.body, draft.head, draft.base, draft.isDraft);
|
|
257
340
|
}
|
|
258
341
|
catch (error) {
|
|
259
342
|
if (error instanceof GitHubAPIError)
|
|
260
|
-
return stopWith(out, `PR creation failed: ${error.message}
|
|
343
|
+
return stopWith(out, `PR creation failed: ${error.message}`, kindOfFailure(error));
|
|
261
344
|
throw error;
|
|
262
345
|
}
|
|
263
346
|
out.done(createOperation(draft));
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
consumeFlag(FLAG_PR_CREATE_SLASH_PENDING);
|
|
347
|
+
const createdNumber = jsonField(created, 'number');
|
|
348
|
+
const pullRequest = typeof createdNumber === 'number' ? createdNumber : undefined;
|
|
267
349
|
const url = jsonField(created, 'html_url');
|
|
350
|
+
// url は先に渡す。後の処理が例外で止まっても、作った PR を結果から読める
|
|
351
|
+
out.result({ head: draft.head, base: draft.base, title: draft.title, ...pullRequest !== undefined && { number: pullRequest }, ...typeof url === 'string' && { url } });
|
|
352
|
+
const inReview = draft.isRelease ? undefined : await updateIssueStatusToInReview(config, client(), draft.location, draft.head, out);
|
|
353
|
+
if (inReview !== undefined)
|
|
354
|
+
out.result({ inReview });
|
|
355
|
+
if (stackOn !== undefined)
|
|
356
|
+
out.result({ stack: await registerStack(client(), draft.location, stackOn, pullRequest, out) });
|
|
357
|
+
const issueNumber = extractIssueNumberFromBranch(draft.head);
|
|
358
|
+
const moves = [];
|
|
359
|
+
try {
|
|
360
|
+
if (!draft.isRelease && isPositive(issueNumber))
|
|
361
|
+
await moveWaitingIssuesSafely(client(), config, draft.location, issueNumber, pullRequest, out, moves);
|
|
362
|
+
}
|
|
363
|
+
finally {
|
|
364
|
+
out.result({ moves: moves.map(move => moveJson(move)) });
|
|
365
|
+
}
|
|
366
|
+
consumeFlag(FLAG_PR_CREATE_SLASH_PENDING);
|
|
268
367
|
if (typeof url !== 'string')
|
|
269
|
-
return stopWith(out, 'PR was created, but the response has no html_url; find it on GitHub');
|
|
368
|
+
return stopWith(out, 'PR was created, but the response has no html_url; find it on GitHub', 'other');
|
|
270
369
|
out.data(url);
|
|
271
370
|
}
|
|
371
|
+
export function stopOnMalformedRecord(reading, out) {
|
|
372
|
+
if (reading.kind === 'malformed')
|
|
373
|
+
stopWith(out, describeBaseStop({ kind: 'stop', reason: 'malformed', content: reading.content }).join('\n'), 'content-invalid');
|
|
374
|
+
}
|
|
375
|
+
// merge-base --is-ancestor は、祖先でなければ 1、コミットを知らなければ 128 を返す
|
|
376
|
+
const NOT_ANCESTOR = 1;
|
|
377
|
+
// 記録を使うのは、head が今のブランチで、release のテンプレートでないときだけ。形が誤っていれば終了コード 1 で止める。
|
|
378
|
+
// 記録のコミットが head の履歴に無ければ、別のブランチの記録なので止める。開発ブランチ向けに作ると下の段の差分が入りうるため
|
|
379
|
+
function readBaseRecordFor(head, template, directory, out) {
|
|
380
|
+
if (template === 'release' || head !== gitCurrentBranch(directory))
|
|
381
|
+
return undefined;
|
|
382
|
+
const reading = readBaseRecord();
|
|
383
|
+
stopOnMalformedRecord(reading, out);
|
|
384
|
+
if (reading.kind !== 'stacked')
|
|
385
|
+
return reading;
|
|
386
|
+
const { branch, sha } = reading.record;
|
|
387
|
+
const isForeign = runGit(['merge-base', '--is-ancestor', sha, head], { cwd: directory }).exitCode === NOT_ANCESTOR;
|
|
388
|
+
return isForeign
|
|
389
|
+
? stopWith(out, hinted `.pecot-base records ${branch} at ${sha.slice(0, 7)}, which is not in the history of ${head}\nrun pr create on the branch the record was written for, or pass ${inputHint(PR_CREATE_PATH, 'head', head)} to create the PR without the record`, 'git-unresolved')
|
|
390
|
+
: reading;
|
|
391
|
+
}
|
|
392
|
+
// 積んだ記録なら、PR を作るリポで下の段の PR を読み、base を決める
|
|
393
|
+
async function decideBase(input, client, developBranch, out) {
|
|
394
|
+
const { reading, base, location } = input;
|
|
395
|
+
if (reading === undefined)
|
|
396
|
+
return { kind: 'use', base, stackOn: undefined, stackedBase: undefined, isLowerMerged: false };
|
|
397
|
+
if (reading.kind !== 'stacked')
|
|
398
|
+
return decidePullRequestBase({ reading, base, developBranch });
|
|
399
|
+
const { branch } = reading.record;
|
|
400
|
+
try {
|
|
401
|
+
const found = await client().listPullRequestsByHead(location.owner, location.repository, branch);
|
|
402
|
+
return decidePullRequestBase({ reading, base, developBranch, lowerPullRequest: pickLowerPullRequest(found.pullRequests) });
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
if (error instanceof GitHubAPIError)
|
|
406
|
+
return stopWith(out, `cannot read the PR of the base branch ${branch}: ${describeApiError(error)}`, kindOfFailure(error));
|
|
407
|
+
throw error;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
// 下の段の PR が開いているのに開発ブランチを渡したときは、内容の検証の失敗と一緒に出す(終了コード 3)
|
|
411
|
+
function useOrStop(decision, out) {
|
|
412
|
+
if (decision.kind === 'use')
|
|
413
|
+
return { use: decision, errors: [] };
|
|
414
|
+
const lines = describeBaseStop(decision);
|
|
415
|
+
if (decision.reason === 'lower-open')
|
|
416
|
+
return { use: undefined, errors: lines };
|
|
417
|
+
if (decision.reason === 'malformed')
|
|
418
|
+
return stopWith(out, lines.join('\n'), 'content-invalid');
|
|
419
|
+
return stopWith(out, lines.join('\n'), 'pr-state', NO_OPEN_BASE_EXIT_CODE);
|
|
420
|
+
}
|
|
421
|
+
// 下の段がマージ済みなら記録のコミットから、開いていてそのブランチへ作るならそのブランチから、題の scope を比べる
|
|
422
|
+
function stackedScopeOf(reading, use) {
|
|
423
|
+
if (use === undefined || reading?.kind !== 'stacked')
|
|
424
|
+
return undefined;
|
|
425
|
+
if (use.isLowerMerged)
|
|
426
|
+
return { sha: reading.record.sha };
|
|
427
|
+
return use.stackOn === undefined ? undefined : { branch: reading.record.branch };
|
|
428
|
+
}
|
|
272
429
|
// 検証して、dry-run なら計画を出し、そうでなければ投稿する。file と -m の両方がここを通る
|
|
273
430
|
async function validateAndSubmit(input, out) {
|
|
274
|
-
const { config, directory, template, location, title,
|
|
431
|
+
const { config, directory, template, location, title, head } = input;
|
|
432
|
+
const client = lazyClient(config, out);
|
|
275
433
|
const developBranch = getDevelopBranch(config, location.owner, location.repository);
|
|
276
434
|
const releaseBranch = getReleaseBranch(config, location.owner, location.repository);
|
|
277
|
-
exitOnUnsetBranch(template, base, head, developBranch, releaseBranch, out);
|
|
435
|
+
exitOnUnsetBranch(template, input.base, head, developBranch, releaseBranch, out);
|
|
436
|
+
const { use, errors: baseErrors } = useOrStop(await decideBase(input, client, developBranch ?? '', out), out);
|
|
437
|
+
const base = use?.base ?? input.base;
|
|
438
|
+
const stacked = stackedScopeOf(input.reading, use);
|
|
278
439
|
const requiredSections = readTemplateSections(templateFile('pr', templateKindOf(template)));
|
|
279
440
|
const errors = [
|
|
280
441
|
...validatePullRequestContent({
|
|
@@ -287,23 +448,28 @@ async function validateAndSubmit(input, out) {
|
|
|
287
448
|
skipIssueReferenceCheck: input.noIssueRef,
|
|
288
449
|
screenshot: input.screenshot,
|
|
289
450
|
requiredSections,
|
|
451
|
+
stackedBase: use?.stackedBase,
|
|
290
452
|
}),
|
|
291
|
-
...
|
|
453
|
+
...baseErrors,
|
|
454
|
+
...titleScopeErrors({ config, owner: location.owner, repository: location.repository, title, base, head, directory, template, developBranch, releaseBranch, stacked }, out),
|
|
292
455
|
];
|
|
293
456
|
exitOnValidationErrors(errors, out);
|
|
294
457
|
const isRelease = template === 'release';
|
|
295
458
|
const draft = { location, title, body: input.body, head, base, isDraft: input.isDraft, isRelease };
|
|
296
459
|
if (!input.dryRun) {
|
|
297
|
-
await submitPullRequest(config, directory, draft, out);
|
|
460
|
+
await submitPullRequest(config, client, directory, draft, use?.stackOn, out);
|
|
298
461
|
return;
|
|
299
462
|
}
|
|
300
463
|
out.planned(createOperation(draft));
|
|
301
464
|
const issueNumber = extractIssueNumberFromBranch(head);
|
|
302
465
|
if (!isRelease && issueNumber !== undefined)
|
|
303
466
|
out.planned(inReviewOperation(issueNumber));
|
|
467
|
+
if (use?.stackOn !== undefined)
|
|
468
|
+
out.planned({ verb: 'add', target: `the new PR to the stack of PR #${String(use.stackOn)}` });
|
|
469
|
+
out.result({ head, base, title, ...use?.stackOn !== undefined && { stack: { lower: use.stackOn } } });
|
|
304
470
|
}
|
|
305
471
|
function requireRepository(value, out) {
|
|
306
|
-
return splitOwnerRepository(value) ?? stopWith(out, `invalid repository format: ${value} (expected: owner/repo)
|
|
472
|
+
return splitOwnerRepository(value) ?? stopWith(out, `invalid repository format: ${value} (expected: owner/repo)`, 'invalid-input');
|
|
307
473
|
}
|
|
308
474
|
async function createFromFile(input, directory, out) {
|
|
309
475
|
const config = requireActiveConfigPlain(out);
|
|
@@ -313,14 +479,15 @@ async function createFromFile(input, directory, out) {
|
|
|
313
479
|
}
|
|
314
480
|
catch (error) {
|
|
315
481
|
if (error instanceof FrontmatterError)
|
|
316
|
-
return stopWith(out, error.message);
|
|
482
|
+
return stopWith(out, error.message, 'content-invalid');
|
|
317
483
|
throw error;
|
|
318
484
|
}
|
|
319
485
|
const { frontmatter } = parsed;
|
|
320
486
|
if (frontmatter.repository === '' || !frontmatter.repository.includes('/'))
|
|
321
|
-
return stopWith(out, 'repository is required (e.g. owner/repo)');
|
|
487
|
+
return stopWith(out, 'repository is required (e.g. owner/repo)', 'content-invalid');
|
|
322
488
|
const location = requireRepository(frontmatter.repository, out);
|
|
323
489
|
const head = resolveHeadBranch(frontmatter.head, directory, out);
|
|
490
|
+
const reading = readBaseRecordFor(head, input.template, directory, out);
|
|
324
491
|
let body = parsed.body;
|
|
325
492
|
const issueNumber = extractIssueNumberFromBranch(head);
|
|
326
493
|
if (input.template !== 'release' && !input.noIssueRef && isPositive(issueNumber)) {
|
|
@@ -339,6 +506,7 @@ async function createFromFile(input, directory, out) {
|
|
|
339
506
|
isDraft: frontmatter.draft,
|
|
340
507
|
body,
|
|
341
508
|
screenshot: frontmatter.screenshot,
|
|
509
|
+
reading,
|
|
342
510
|
}, out);
|
|
343
511
|
}
|
|
344
512
|
async function createDirect(input, directory, out) {
|
|
@@ -347,13 +515,14 @@ async function createDirect(input, directory, out) {
|
|
|
347
515
|
if (input.repository === undefined || input.repository === '') {
|
|
348
516
|
const [only] = config.repositories;
|
|
349
517
|
if (only === undefined || config.repositories.length !== 1)
|
|
350
|
-
return stopWith(out,
|
|
518
|
+
return stopWith(out, hinted `specify the repository (${inputHint(PR_CREATE_PATH, 'repo', placeholder('owner/repo'))})`, 'invalid-input');
|
|
351
519
|
location = { owner: only.owner, repository: only.name };
|
|
352
520
|
}
|
|
353
521
|
else {
|
|
354
522
|
location = requireRepository(input.repository, out);
|
|
355
523
|
}
|
|
356
524
|
const head = resolveHeadBranch(input.head, directory, out);
|
|
525
|
+
const reading = readBaseRecordFor(head, input.template, directory, out);
|
|
357
526
|
let body = input.message;
|
|
358
527
|
const issueNumber = extractIssueNumberFromBranch(head);
|
|
359
528
|
if (input.template !== 'release' && !input.noIssueRef && isPositive(issueNumber)) {
|
|
@@ -372,15 +541,16 @@ async function createDirect(input, directory, out) {
|
|
|
372
541
|
isDraft: input.isDraft,
|
|
373
542
|
body,
|
|
374
543
|
screenshot: input.screenshot,
|
|
544
|
+
reading,
|
|
375
545
|
}, out);
|
|
376
546
|
}
|
|
377
547
|
// --prepare
|
|
378
|
-
function addScopeHint(content, config, location, base, directory, out) {
|
|
379
|
-
const target = nxScopeTarget(config, location.owner, location.repository, base, directory);
|
|
548
|
+
function addScopeHint(content, config, location, base, directory, stacked, out) {
|
|
549
|
+
const target = nxScopeTarget(config, location.owner, location.repository, base, directory, stacked);
|
|
380
550
|
if (target === undefined)
|
|
381
551
|
return content;
|
|
382
552
|
const head = gitCurrentBranch(directory);
|
|
383
|
-
const expected = head === undefined || head === '' ? undefined : expectedTitleScope(target,
|
|
553
|
+
const expected = head === undefined || head === '' ? undefined : expectedTitleScope(target, head, out);
|
|
384
554
|
if (expected === undefined || expected.length === 0)
|
|
385
555
|
return content;
|
|
386
556
|
const scope = expected.join(',');
|
|
@@ -430,18 +600,24 @@ async function fillClosesInTemplate(content, config, directory, location, out) {
|
|
|
430
600
|
async function prepareTemplate(directory, out, template) {
|
|
431
601
|
const templatePath = templateFile('pr', templateKindOf(template));
|
|
432
602
|
if (!existsSync(templatePath))
|
|
433
|
-
stopWith(out, `template not found: ${templatePath}
|
|
603
|
+
stopWith(out, `template not found: ${templatePath}`, 'other');
|
|
434
604
|
let content = readTextFile(templatePath);
|
|
435
605
|
// release テンプレートは、base をテンプレートの既定(main)のままにする
|
|
436
606
|
if (template !== 'release') {
|
|
607
|
+
// 下の段の PR がマージ済みかは、準備と投稿の間に変わりうるので、ここでは読まずに投稿のときに見る
|
|
608
|
+
const reading = readBaseRecord();
|
|
609
|
+
stopOnMalformedRecord(reading, out);
|
|
610
|
+
const record = reading.kind === 'stacked' ? reading.record : undefined;
|
|
437
611
|
const location = primaryRemote(directory)?.location;
|
|
438
612
|
const config = loadActiveConfig();
|
|
439
613
|
if (location !== undefined) {
|
|
440
614
|
const developBranch = config === undefined ? undefined : getDevelopBranch(config, location.owner, location.repository);
|
|
441
615
|
if (config !== undefined && developBranch !== undefined && developBranch !== '') {
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
616
|
+
const base = record?.branch ?? developBranch;
|
|
617
|
+
content = content.replace(/^base:\s*"[^"]*"/mu, () => `base: "${base}"`);
|
|
618
|
+
out.done({ verb: 'set', target: `base to ${base}` });
|
|
619
|
+
out.result({ base });
|
|
620
|
+
content = addScopeHint(content, config, { owner: location.owner, repository: location.repository }, base, directory, record === undefined ? undefined : { sha: record.sha }, out);
|
|
445
621
|
}
|
|
446
622
|
}
|
|
447
623
|
content = await fillClosesInTemplate(content, config, directory, location, out);
|
|
@@ -450,12 +626,13 @@ async function prepareTemplate(directory, out, template) {
|
|
|
450
626
|
try {
|
|
451
627
|
withReservedOutputPath(outputDirectory(), timestamp => `${prefix}-${timestamp}.md`, (reserved) => {
|
|
452
628
|
writeFileSync(reserved, content, 'utf8');
|
|
629
|
+
out.result({ file: path.resolve(reserved) });
|
|
453
630
|
out.data(reserved);
|
|
454
631
|
});
|
|
455
632
|
}
|
|
456
633
|
catch (error) {
|
|
457
634
|
if (error instanceof OutputPathReservationError)
|
|
458
|
-
return stopWith(out, error.message);
|
|
635
|
+
return stopWith(out, error.message, 'other');
|
|
459
636
|
throw error;
|
|
460
637
|
}
|
|
461
638
|
}
|
|
@@ -477,21 +654,21 @@ async function runCreate(input, io) {
|
|
|
477
654
|
const directory = process.cwd();
|
|
478
655
|
const out = createOutput(input.dry_run, io);
|
|
479
656
|
if (input.template !== 'default' && input.template !== 'release')
|
|
480
|
-
stopWith(out,
|
|
657
|
+
stopWith(out, hinted `${inputNameHint(PR_CREATE_PATH, 'template')} must be 'default' or 'release' (given: ${input.template})`, 'invalid-input');
|
|
481
658
|
if (input.prepare) {
|
|
482
659
|
await prepareTemplate(directory, createOutput(false, io), input.template);
|
|
483
660
|
}
|
|
484
661
|
else if (input.file !== undefined) {
|
|
485
662
|
if (input.screenshot !== undefined)
|
|
486
|
-
stopWith(out, '
|
|
663
|
+
stopWith(out, hinted `${inputNameHint(PR_CREATE_PATH, 'screenshot')} is for ${inputNameHint(PR_CREATE_PATH, 'message')}; write the reason in the \`screenshot\` frontmatter field instead`, 'invalid-input');
|
|
487
664
|
await createFromFile({ file: input.file, template: input.template, noIssueRef: input.no_issue_ref, dryRun: input.dry_run }, directory, out);
|
|
488
665
|
}
|
|
489
666
|
else if (input.message === undefined) {
|
|
490
|
-
stopWith(out,
|
|
667
|
+
stopWith(out, hinted `missing arguments\nusage:\n${commandHint(PR_CREATE_PATH, { prepare: true })}\n${commandHint(PR_CREATE_PATH, { file: placeholder('path') })}\n${commandHint(PR_CREATE_PATH, { message: placeholder('body'), title: placeholder('title'), base: placeholder('base-branch') })}`, 'invalid-input');
|
|
491
668
|
}
|
|
492
669
|
else {
|
|
493
670
|
if (input.title === undefined || input.title === '' || input.base === undefined || input.base === '')
|
|
494
|
-
stopWith(out,
|
|
671
|
+
stopWith(out, hinted `${inputNameHint(PR_CREATE_PATH, 'title')} and ${inputNameHint(PR_CREATE_PATH, 'base')} (base branch) are required with ${inputNameHint(PR_CREATE_PATH, 'message')}`, 'invalid-input');
|
|
495
672
|
await createDirect({
|
|
496
673
|
message: input.message,
|
|
497
674
|
title: input.title,
|
|
@@ -506,35 +683,70 @@ async function runCreate(input, io) {
|
|
|
506
683
|
}, directory, out);
|
|
507
684
|
}
|
|
508
685
|
}
|
|
509
|
-
// pr
|
|
510
|
-
|
|
511
|
-
function resolveBaseRepository(globalRepository) {
|
|
512
|
-
try {
|
|
513
|
-
return resolveRepository(globalRepository, gitRunnerFor(process.cwd())).repository;
|
|
514
|
-
}
|
|
515
|
-
catch (error) {
|
|
516
|
-
if (error instanceof AmbiguousRepositoryError)
|
|
517
|
-
return undefined;
|
|
518
|
-
throw error;
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
function parseReference(reference, globalRepository, out) {
|
|
522
|
-
try {
|
|
523
|
-
const parsed = parsePullRequestReference(reference, resolveBaseRepository(globalRepository), { repositoryFlag: true });
|
|
524
|
-
return { owner: parsed.repository.owner, repository: parsed.repository.repository, number: parsed.number };
|
|
525
|
-
}
|
|
526
|
-
catch (error) {
|
|
527
|
-
if (error instanceof ReferenceParseError)
|
|
528
|
-
return stopWith(out, error.message, USAGE_EXIT_CODE);
|
|
529
|
-
throw error;
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
const ReadInputSchema = z.strictObject({
|
|
686
|
+
// pr show
|
|
687
|
+
const ShowInputSchema = z.strictObject({
|
|
533
688
|
pr_ref: z.string().describe(PR_REFERENCE_DESCRIPTION),
|
|
534
689
|
json: z.boolean().default(false).describe('Output as JSON'),
|
|
535
690
|
reviews: z.boolean().default(false).describe('Include review details (bodies and line comments)'),
|
|
536
691
|
});
|
|
537
|
-
|
|
692
|
+
const ISSUE_LINK_JSON = z.strictObject({
|
|
693
|
+
number: z.int().describe('Issue number'),
|
|
694
|
+
title: z.string().describe('Title of the Issue (empty for referenced_issues)'),
|
|
695
|
+
});
|
|
696
|
+
const REVIEW_JSON = z.strictObject({
|
|
697
|
+
state: z.string().describe('State of the review'),
|
|
698
|
+
author: z.string().nullable().describe('Login of the reviewer (null when deleted)'),
|
|
699
|
+
body: z.string().optional().describe('Body of the review (only with reviews)'),
|
|
700
|
+
submitted_at: z.string().nullable().optional().describe('Submission time (only with reviews)'),
|
|
701
|
+
});
|
|
702
|
+
const REVIEW_COMMENT_JSON = z.strictObject({
|
|
703
|
+
author: z.string().nullable().describe('Login of the author (null when deleted)'),
|
|
704
|
+
body: z.string().describe('Body of the comment'),
|
|
705
|
+
created_at: z.string().nullable().describe('Creation time'),
|
|
706
|
+
});
|
|
707
|
+
const REVIEW_THREAD_JSON = z.strictObject({
|
|
708
|
+
is_resolved: z.boolean().describe('Whether the thread is resolved'),
|
|
709
|
+
path: z.string().nullable().describe('File path of the thread'),
|
|
710
|
+
line: z.int().nullable().describe('Line of the thread'),
|
|
711
|
+
comments: z.array(REVIEW_COMMENT_JSON).describe('Comments in the thread'),
|
|
712
|
+
});
|
|
713
|
+
const PR_SHOW_OUTPUT = z.strictObject({
|
|
714
|
+
number: z.int().describe('PR number'),
|
|
715
|
+
state: z.string().describe('State of the PR (OPEN, CLOSED or MERGED)'),
|
|
716
|
+
title: z.string().describe('Title of the PR'),
|
|
717
|
+
body: z.string().describe('Body of the PR'),
|
|
718
|
+
head_ref: z.string().describe('Head branch'),
|
|
719
|
+
base_ref: z.string().describe('Base branch'),
|
|
720
|
+
is_draft: z.boolean().describe('Whether the PR is a draft'),
|
|
721
|
+
mergeable: z.string().describe('Mergeability (MERGEABLE, CONFLICTING or UNKNOWN)'),
|
|
722
|
+
comments: z.int().describe('Number of comments'),
|
|
723
|
+
closing_issues: z.array(ISSUE_LINK_JSON).describe('Issues the PR closes'),
|
|
724
|
+
referenced_issues: z.array(ISSUE_LINK_JSON).describe('Issues referenced by Refs in the body and not in closing_issues'),
|
|
725
|
+
reviews: z.array(REVIEW_JSON).describe('Reviews'),
|
|
726
|
+
review_threads: z.array(REVIEW_THREAD_JSON).optional().describe('Line comment threads (only with reviews)'),
|
|
727
|
+
});
|
|
728
|
+
/**
|
|
729
|
+
--json の標準出力と MCP の data の中身。キーを並べた順が --json の出力の順になる
|
|
730
|
+
*/
|
|
731
|
+
function pullRequestJson(pr) {
|
|
732
|
+
// 項目を手で並べるので、satisfies で PR の型の項目の過不足を tsc に止めさせる
|
|
733
|
+
const base = {
|
|
734
|
+
number: pr.number,
|
|
735
|
+
state: pr.state,
|
|
736
|
+
title: pr.title,
|
|
737
|
+
body: pr.body,
|
|
738
|
+
head_ref: pr.head_ref,
|
|
739
|
+
base_ref: pr.base_ref,
|
|
740
|
+
is_draft: pr.is_draft,
|
|
741
|
+
mergeable: pr.mergeable,
|
|
742
|
+
comments: pr.comments,
|
|
743
|
+
closing_issues: pr.closing_issues.map(issue => ({ ...issue })),
|
|
744
|
+
referenced_issues: pr.referenced_issues.map(issue => ({ ...issue })),
|
|
745
|
+
reviews: pr.reviews.map(review => ({ ...review })),
|
|
746
|
+
};
|
|
747
|
+
return 'review_threads' in pr ? { ...base, review_threads: pr.review_threads.map(thread => ({ ...thread, comments: thread.comments.map(comment => ({ ...comment })) })) } : base;
|
|
748
|
+
}
|
|
749
|
+
async function runShow(input, io) {
|
|
538
750
|
const out = createOutput(false, io);
|
|
539
751
|
const config = requireActiveConfigPlain(out);
|
|
540
752
|
const { owner, repository, number } = parseReference(input.pr_ref, input.repo, out);
|
|
@@ -542,33 +754,52 @@ async function runRead(input, io) {
|
|
|
542
754
|
const client = createGitHubClient(out, config.host);
|
|
543
755
|
if (input.reviews) {
|
|
544
756
|
const pr = await client.getPullRequestWithReviews(owner, repository, number);
|
|
545
|
-
|
|
757
|
+
const json = pullRequestJson(pr);
|
|
758
|
+
out.result(json);
|
|
759
|
+
out.data(`${input.json ? JSON.stringify(json, undefined, 2) : formatPullRequestWithReviewsMarkdown(pr, owner, repository)}\n`);
|
|
546
760
|
}
|
|
547
761
|
else {
|
|
548
762
|
const pr = await client.getPullRequestSlim(owner, repository, number);
|
|
549
|
-
|
|
763
|
+
const json = pullRequestJson(pr);
|
|
764
|
+
out.result(json);
|
|
765
|
+
out.data(`${input.json ? JSON.stringify(json, undefined, 2) : formatPullRequestMarkdown(pr)}\n`);
|
|
550
766
|
}
|
|
551
767
|
}
|
|
552
768
|
catch (error) {
|
|
553
769
|
if (error instanceof GitHubAPIError)
|
|
554
|
-
return stopWith(out, error.message);
|
|
770
|
+
return stopWith(out, error.message, kindOfFailure(error));
|
|
555
771
|
throw error;
|
|
556
772
|
}
|
|
557
773
|
}
|
|
558
|
-
// pr
|
|
774
|
+
// pr check
|
|
559
775
|
function hasBranch(branch, cwd) {
|
|
560
776
|
return runGit(['rev-parse', '--verify', branch], { cwd }).exitCode === 0;
|
|
561
777
|
}
|
|
778
|
+
// 下の段のブランチがマージで消えた後は、開発ブランチと比べる。追跡参照は fetch --prune まで残るので、
|
|
779
|
+
// remote に尋ね、無いと答えたときだけ消えたとみなす。届かないか時間切れなら追跡参照で決める
|
|
780
|
+
function isOnRemote(branch, cwd, remote, out) {
|
|
781
|
+
const head = remoteBranchHead(cwd, remote, branch);
|
|
782
|
+
if (head.isReachable && head.sha === undefined)
|
|
783
|
+
return false;
|
|
784
|
+
const isTracked = hasBranch(`${remote}/${branch}`, cwd);
|
|
785
|
+
if (!isTracked && head.isReachable)
|
|
786
|
+
out.warning(`base branch ${branch} is on ${remote}, but ${remote}/${branch} is not fetched; compared with the develop branch\nrun: git fetch ${remote} ${branch}`);
|
|
787
|
+
return isTracked;
|
|
788
|
+
}
|
|
562
789
|
function determineBaseBranch(location, cwd, remote, out) {
|
|
563
790
|
const config = loadActiveConfig();
|
|
564
791
|
if (config === undefined)
|
|
565
|
-
return stopWith(out,
|
|
792
|
+
return stopWith(out, hinted `project config not found\nactivate a project with: ${commandHint(['project', 'activate'], { project: placeholder('PROJECT') })}`, 'no-active-project');
|
|
793
|
+
const reading = readBaseRecord();
|
|
794
|
+
stopOnMalformedRecord(reading, out);
|
|
795
|
+
if (reading.kind === 'stacked' && isOnRemote(reading.record.branch, cwd, remote, out))
|
|
796
|
+
return `${remote}/${reading.record.branch}`;
|
|
566
797
|
const developBranch = getDevelopBranch(config, location.owner, location.repository);
|
|
567
798
|
if (developBranch === undefined || developBranch === '') {
|
|
568
|
-
return stopWith(out, `develop_branch is not set for ${location.owner}/${location.repository}\nset it with:
|
|
799
|
+
return stopWith(out, hinted `develop_branch is not set for ${location.owner}/${location.repository}\nset it with: ${commandHint(LINK_PATH, { repo: `${location.owner}/${location.repository}`, develop_branch: 'develop' })}`, 'repo-setting-missing');
|
|
569
800
|
}
|
|
570
801
|
const branchName = `${remote}/${developBranch}`;
|
|
571
|
-
return hasBranch(branchName, cwd) ? branchName : stopWith(out, `branch ${branchName} does not exist\ncheck the remote branches with: git branch -r
|
|
802
|
+
return hasBranch(branchName, cwd) ? branchName : stopWith(out, `branch ${branchName} does not exist\ncheck the remote branches with: git branch -r`, 'git-unresolved');
|
|
572
803
|
}
|
|
573
804
|
function readGitignore(cwd) {
|
|
574
805
|
const root = gitToplevel({ cwd });
|
|
@@ -596,24 +827,41 @@ function readGitExclude(cwd) {
|
|
|
596
827
|
return '(read error)';
|
|
597
828
|
}
|
|
598
829
|
}
|
|
599
|
-
|
|
830
|
+
const PR_CHECK_OUTPUT = z.strictObject({
|
|
831
|
+
remoteUrl: z.string().describe('URL of the primary git remote'),
|
|
832
|
+
currentBranch: z.string().describe('Current branch'),
|
|
833
|
+
pushed: z.boolean().describe('Whether the current branch is pushed and even with its remote branch'),
|
|
834
|
+
pushStatus: z.string().describe('Push status as shown in the Push Status section'),
|
|
835
|
+
baseBranch: z.string().describe('Remote branch compared against (remote/branch): the lower stage when stacked, else the develop branch'),
|
|
836
|
+
gitStatus: z.string().describe('Output of git status'),
|
|
837
|
+
commits: z.string().describe('Commits since the base branch, as shown in the Commits section'),
|
|
838
|
+
diffSummary: z.string().describe('Diff stat against the base branch, as shown in the Diff Summary section'),
|
|
839
|
+
worktree: z.strictObject({
|
|
840
|
+
list: z.string().describe('Output of git worktree list'),
|
|
841
|
+
directoryName: z.string().describe('Name of the current directory'),
|
|
842
|
+
isWorktree: z.boolean().optional().describe('Whether the directory is a linked worktree (omitted when it could not be determined)'),
|
|
843
|
+
}).describe('Worktree information'),
|
|
844
|
+
stashList: z.string().describe('Stash list, as shown in the Stash List section'),
|
|
845
|
+
});
|
|
846
|
+
function readWorktreeInfo(cwd) {
|
|
600
847
|
const listed = gitStdout(['worktree', 'list'], { cwd });
|
|
601
|
-
const
|
|
848
|
+
const list = listed === undefined ? '(git worktree list failed)' : pythonStrip(listed);
|
|
849
|
+
const directoryName = path.basename(cwd);
|
|
602
850
|
const gitDirectory = gitStdout(['rev-parse', '--git-dir'], { cwd });
|
|
603
851
|
const commonDirectory = gitDirectory === undefined ? undefined : gitStdout(['rev-parse', '--git-common-dir'], { cwd });
|
|
604
|
-
if (gitDirectory === undefined || commonDirectory === undefined)
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
return
|
|
852
|
+
if (gitDirectory === undefined || commonDirectory === undefined)
|
|
853
|
+
return { list, directoryName };
|
|
854
|
+
const isWorktree = resolveRealPath(path.resolve(cwd, pythonStrip(gitDirectory))) !== resolveRealPath(path.resolve(cwd, pythonStrip(commonDirectory)));
|
|
855
|
+
return { list, directoryName, isWorktree };
|
|
856
|
+
}
|
|
857
|
+
function formatWorktreeInfo(info) {
|
|
858
|
+
const worktreeText = info.isWorktree === undefined ? '(unknown)' : String(info.isWorktree);
|
|
859
|
+
return [info.list, '', `Current directory name: ${info.directoryName}`, `Is worktree environment: ${worktreeText}`].join('\n');
|
|
612
860
|
}
|
|
613
|
-
const
|
|
861
|
+
const CheckInputSchema = z.strictObject({
|
|
614
862
|
directory: directorySchema,
|
|
615
863
|
});
|
|
616
|
-
function
|
|
864
|
+
function runCheck(input, io) {
|
|
617
865
|
const out = createOutput(false, io);
|
|
618
866
|
const directory = input.directory;
|
|
619
867
|
const context = validatePullRequestContext(directory, out);
|
|
@@ -623,6 +871,11 @@ function runPreflight(input, io) {
|
|
|
623
871
|
const diffSummary = gitStdout(['diff', '--stat', `${baseBranch}...HEAD`], { cwd: directory });
|
|
624
872
|
const push = getPushStatus(context.currentBranch, directory, context.remoteName);
|
|
625
873
|
const stashList = getStashList(directory);
|
|
874
|
+
const commitsText = commits === undefined ? '(git log failed)' : pythonStrip(commits) || '(no commits)';
|
|
875
|
+
const diffText = diffSummary === undefined ? '(git diff failed)' : pythonStrip(diffSummary) || '(no diff)';
|
|
876
|
+
const worktree = readWorktreeInfo(directory);
|
|
877
|
+
// preflight の warning で失敗に終わっても、集めた値を data に残す
|
|
878
|
+
out.result({ remoteUrl: context.remoteUrl, currentBranch: context.currentBranch, pushed: push.isPushed, pushStatus: push.message, baseBranch, gitStatus, commits: commitsText, diffSummary: diffText, worktree, stashList });
|
|
626
879
|
const sections = [
|
|
627
880
|
['=== Git Remote ===', context.remoteUrl],
|
|
628
881
|
['=== Current Branch ===', context.currentBranch],
|
|
@@ -631,9 +884,9 @@ function runPreflight(input, io) {
|
|
|
631
884
|
['=== Git Status ===', gitStatus],
|
|
632
885
|
['=== .gitignore ===', readGitignore(directory)],
|
|
633
886
|
['=== Git Exclude ===', readGitExclude(directory)],
|
|
634
|
-
[`=== Commits (vs ${baseBranch}) ===`,
|
|
635
|
-
[`=== Diff Summary (vs ${baseBranch}) ===`,
|
|
636
|
-
['=== Worktree Info ===',
|
|
887
|
+
[`=== Commits (vs ${baseBranch}) ===`, commitsText],
|
|
888
|
+
[`=== Diff Summary (vs ${baseBranch}) ===`, diffText],
|
|
889
|
+
['=== Worktree Info ===', formatWorktreeInfo(worktree)],
|
|
637
890
|
['=== Stash List ===', stashList],
|
|
638
891
|
];
|
|
639
892
|
for (const [index, [heading, content]] of sections.entries()) {
|
|
@@ -646,244 +899,13 @@ function runPreflight(input, io) {
|
|
|
646
899
|
out.count('preflight warnings', warnings.length);
|
|
647
900
|
printPreflightWarnings(out, warnings);
|
|
648
901
|
if (warnings.length > 0)
|
|
649
|
-
throw new CommandExit(PREFLIGHT_EXIT_CODE);
|
|
650
|
-
}
|
|
651
|
-
async function fetchPullRequestForCleanup(config, location, out) {
|
|
652
|
-
try {
|
|
653
|
-
const client = createGitHubClient(out, config.host);
|
|
654
|
-
return { client, pr: await client.getPullRequestSlim(location.owner, location.repository, location.number) };
|
|
655
|
-
}
|
|
656
|
-
catch (error) {
|
|
657
|
-
if (error instanceof GitHubNotFoundError)
|
|
658
|
-
return stopWith(out, `PR not found: ${location.owner}/${location.repository}/${String(location.number)}`);
|
|
659
|
-
if (error instanceof GitHubAPIError)
|
|
660
|
-
return stopWith(out, error.message);
|
|
661
|
-
throw error;
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
function collectClosingIssueNumbers(pr) {
|
|
665
|
-
const numbers = new Set(pr.closing_issues.map(issue => issue.number));
|
|
666
|
-
for (const number of extractClosingIssueNumbers(pr.body))
|
|
667
|
-
numbers.add(number);
|
|
668
|
-
const branchNumber = extractIssueNumberFromBranch(pr.head_ref);
|
|
669
|
-
if (isPositive(branchNumber))
|
|
670
|
-
numbers.add(branchNumber);
|
|
671
|
-
return numbers;
|
|
672
|
-
}
|
|
673
|
-
// Epic 保護。Issue Type が Epic か、sub-issue を持つ Issue
|
|
674
|
-
async function findEpicProtectedNumbers(client, location, issueNumbers, out) {
|
|
675
|
-
const protectedNumbers = new Set();
|
|
676
|
-
const ordered = [...issueNumbers].toSorted((a, b) => a - b);
|
|
677
|
-
for (const number of ordered) {
|
|
678
|
-
try {
|
|
679
|
-
if (isEpicIssue(await client.getIssueKind(location.owner, location.repository, number)))
|
|
680
|
-
protectedNumbers.add(number);
|
|
681
|
-
}
|
|
682
|
-
catch (error) {
|
|
683
|
-
if (error instanceof GitHubNotFoundError)
|
|
684
|
-
continue;
|
|
685
|
-
if (!(error instanceof GitHubAPIError))
|
|
686
|
-
throw error;
|
|
687
|
-
out.warning(`kind check of Issue #${String(number)} failed: ${error.message}; not protected`);
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
return protectedNumbers;
|
|
691
|
-
}
|
|
692
|
-
async function closeRelatedIssues(context, client, location, closing, epicProtected) {
|
|
693
|
-
const { out, isDryRun } = context;
|
|
694
|
-
const protectedOrdered = [...epicProtected].toSorted((a, b) => a - b);
|
|
695
|
-
const closingOrdered = [...closing].toSorted((a, b) => a - b);
|
|
696
|
-
for (const number of protectedOrdered)
|
|
697
|
-
settle(out, { verb: 'skip', target: `closing Issue #${String(number)} (Epic)` });
|
|
698
|
-
for (const number of closingOrdered) {
|
|
699
|
-
const operation = { verb: 'close', target: `Issue #${String(number)}` };
|
|
700
|
-
out.planned(operation);
|
|
701
|
-
if (isDryRun)
|
|
702
|
-
continue;
|
|
703
|
-
try {
|
|
704
|
-
await client.closeIssue(location.owner, location.repository, number);
|
|
705
|
-
out.done(operation);
|
|
706
|
-
}
|
|
707
|
-
catch (error) {
|
|
708
|
-
if (error instanceof GitHubNotFoundError) {
|
|
709
|
-
out.warning(`Issue #${String(number)} not found; skipped`);
|
|
710
|
-
}
|
|
711
|
-
else if (error instanceof GitHubAPIError) {
|
|
712
|
-
if (isClosedByAnotherRequest(error))
|
|
713
|
-
out.done({ verb: 'unchanged', target: `Issue #${String(number)} (already closed)` });
|
|
714
|
-
else
|
|
715
|
-
out.warning(`closing Issue #${String(number)} failed: ${describeApiError(error)}`);
|
|
716
|
-
}
|
|
717
|
-
else {
|
|
718
|
-
throw error;
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
// head ブランチを消し、続けて wip ブランチを消す。head が無くても wip は試す
|
|
724
|
-
async function deleteMergedBranch(context, client, location, headBranch) {
|
|
725
|
-
const { out, isDryRun } = context;
|
|
726
|
-
const operation = { verb: 'delete', target: `remote branch ${headBranch}` };
|
|
727
|
-
out.planned(operation);
|
|
728
|
-
if (isDryRun)
|
|
729
|
-
return;
|
|
730
|
-
try {
|
|
731
|
-
await client.deleteBranch(location.owner, location.repository, headBranch);
|
|
732
|
-
out.done(operation);
|
|
733
|
-
}
|
|
734
|
-
catch (error) {
|
|
735
|
-
if (!(error instanceof GitHubAPIError))
|
|
736
|
-
throw error;
|
|
737
|
-
if (!isMissingReferenceError(error)) {
|
|
738
|
-
out.warning(`deleting remote branch ${headBranch} failed: ${describeApiError(error)}`);
|
|
739
|
-
return;
|
|
740
|
-
}
|
|
741
|
-
out.done({ verb: 'unchanged', target: `remote branch ${headBranch} (already deleted)` });
|
|
742
|
-
}
|
|
743
|
-
const wipBranch = `wip/${headBranch}`;
|
|
744
|
-
try {
|
|
745
|
-
await client.deleteBranch(location.owner, location.repository, wipBranch);
|
|
746
|
-
out.done({ verb: 'delete', target: `remote branch ${wipBranch}` });
|
|
747
|
-
}
|
|
748
|
-
catch (error) {
|
|
749
|
-
if (!(error instanceof GitHubAPIError))
|
|
750
|
-
throw error;
|
|
751
|
-
if (!isMissingReferenceError(error))
|
|
752
|
-
out.warning(`deleting remote branch ${wipBranch} failed: ${describeApiError(error)}`);
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
// 手元と PR の repository が同じなら主の remote 名。違えば警告を出して undefined
|
|
756
|
-
function sameRepositoryRemote(cwd, location, out) {
|
|
757
|
-
const skipped = 'skipped local cleanup';
|
|
758
|
-
try {
|
|
759
|
-
const found = primaryRemote(cwd);
|
|
760
|
-
if (found === undefined) {
|
|
761
|
-
out.warning(`cannot read the remote URL; ${skipped}`);
|
|
762
|
-
return undefined;
|
|
763
|
-
}
|
|
764
|
-
if (found.location === undefined) {
|
|
765
|
-
out.warning(`cannot read the repository from the remote URL; ${skipped}`);
|
|
766
|
-
return undefined;
|
|
767
|
-
}
|
|
768
|
-
if (found.location.owner !== location.owner || found.location.repository !== location.repository) {
|
|
769
|
-
out.warning(`current repository (${found.location.owner}/${found.location.repository}) differs from the PR's (${location.owner}/${location.repository}); ${skipped}`);
|
|
770
|
-
return undefined;
|
|
771
|
-
}
|
|
772
|
-
return found.name;
|
|
773
|
-
}
|
|
774
|
-
catch {
|
|
775
|
-
out.warning(`cannot determine the repository; ${skipped}`);
|
|
776
|
-
return undefined;
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
// worktree では worktree 名、そうでなければ develop ブランチ
|
|
780
|
-
function resolveCheckoutTarget(cwd, config, location, out) {
|
|
781
|
-
try {
|
|
782
|
-
if (isWorktreeEnvironment(cwd))
|
|
783
|
-
return getCurrentWorktreeName(cwd) ?? 'main';
|
|
784
|
-
const developBranch = getDevelopBranch(config, location.owner, location.repository);
|
|
785
|
-
if (developBranch !== undefined && developBranch !== '')
|
|
786
|
-
return developBranch;
|
|
787
|
-
out.warning('develop_branch is not set; skipped local cleanup');
|
|
788
|
-
return undefined;
|
|
789
|
-
}
|
|
790
|
-
catch {
|
|
791
|
-
out.warning('cannot determine the worktree; skipped local cleanup');
|
|
792
|
-
return undefined;
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
function didRunLocalStep(context, operation, cwd, arguments_, failure) {
|
|
796
|
-
const { out, isDryRun } = context;
|
|
797
|
-
out.planned(operation);
|
|
798
|
-
if (isDryRun)
|
|
799
|
-
return true;
|
|
800
|
-
try {
|
|
801
|
-
runGit(arguments_, { cwd, check: true });
|
|
802
|
-
}
|
|
803
|
-
catch (error) {
|
|
804
|
-
if (!(error instanceof GitCommandError) && !isFileNotFound(error))
|
|
805
|
-
throw error;
|
|
806
|
-
out.warning(`${failure} failed: ${reasonOf(error)}`);
|
|
807
|
-
return false;
|
|
808
|
-
}
|
|
809
|
-
out.done(operation);
|
|
810
|
-
return true;
|
|
811
|
-
}
|
|
812
|
-
function localCleanupAfterMerge(context, headBranch, config, location) {
|
|
813
|
-
const { out } = context;
|
|
814
|
-
const cwd = process.cwd();
|
|
815
|
-
const remote = sameRepositoryRemote(cwd, location, out);
|
|
816
|
-
if (remote === undefined)
|
|
817
|
-
return;
|
|
818
|
-
const currentBranch = gitCurrentBranch(cwd);
|
|
819
|
-
const checkoutTarget = resolveCheckoutTarget(cwd, config, location, out);
|
|
820
|
-
if (checkoutTarget === undefined)
|
|
821
|
-
return;
|
|
822
|
-
const developBranch = getDevelopBranch(config, location.owner, location.repository);
|
|
823
|
-
if (developBranch === undefined || developBranch === '') {
|
|
824
|
-
out.warning('develop_branch is not set; skipped local cleanup');
|
|
825
|
-
return;
|
|
826
|
-
}
|
|
827
|
-
if (currentBranch === checkoutTarget) {
|
|
828
|
-
settle(out, { verb: 'unchanged', target: `current branch ${checkoutTarget}` });
|
|
829
|
-
}
|
|
830
|
-
else if (!didRunLocalStep(context, { verb: 'set', target: `current branch to ${checkoutTarget}` }, cwd, ['checkout', checkoutTarget], `checking out ${checkoutTarget}`)) {
|
|
831
|
-
// checkout が失敗したら、pull と branch -D は別のブランチに当たるので止める
|
|
832
|
-
return;
|
|
833
|
-
}
|
|
834
|
-
didRunLocalStep(context, { verb: 'update', target: `${checkoutTarget} from ${remote}/${developBranch}` }, cwd, ['pull', remote, developBranch], `pulling ${developBranch}`);
|
|
835
|
-
if (headBranch === checkoutTarget) {
|
|
836
|
-
settle(out, { verb: 'skip', target: `deleting local branch ${headBranch} (it is the checkout target)` });
|
|
837
|
-
}
|
|
838
|
-
else {
|
|
839
|
-
didRunLocalStep(context, { verb: 'delete', target: `local branch ${headBranch}` }, cwd, ['branch', '-D', headBranch], `deleting local branch ${headBranch}`);
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
function removeActiveFlags(out) {
|
|
843
|
-
try {
|
|
844
|
-
for (const flag of [FLAG_PECOT_ACTIVE, FLAG_PECOT_SESSION_TITLE, FLAG_PECOT_QUICK_MODE, FLAG_WIP_BRANCH_LINKED])
|
|
845
|
-
removeFlag(flag);
|
|
846
|
-
}
|
|
847
|
-
catch (error) {
|
|
848
|
-
out.warning(`removing flag files failed: ${reasonOf(error)}`);
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
const CleanupInputSchema = z.strictObject({
|
|
852
|
-
pr_ref: z.string().describe(PR_REFERENCE_DESCRIPTION),
|
|
853
|
-
dry_run: z.boolean().default(false).describe('Dry-run (do not actually clean up)'),
|
|
854
|
-
delete_branch: z.boolean().default(false).describe('Delete the branch'),
|
|
855
|
-
skip_local_cleanup: z.boolean().default(false).describe('Skip the local branch switch and deletion'),
|
|
856
|
-
});
|
|
857
|
-
async function runCleanup(input, io) {
|
|
858
|
-
const out = createOutput(input.dry_run, io);
|
|
859
|
-
const context = { out, isDryRun: input.dry_run };
|
|
860
|
-
const config = requireActiveConfigPlain(out);
|
|
861
|
-
const reference = parseReference(input.pr_ref, input.repo, out);
|
|
862
|
-
const location = { owner: reference.owner, repository: reference.repository };
|
|
863
|
-
const { client, pr } = await fetchPullRequestForCleanup(config, reference, out);
|
|
864
|
-
if (pr.state !== 'MERGED')
|
|
865
|
-
stopWith(out, `PR #${String(reference.number)} is not merged yet (state: ${pr.state}); merge it with gh pr merge first`);
|
|
866
|
-
const closing = collectClosingIssueNumbers(pr);
|
|
867
|
-
const epicProtected = await findEpicProtectedNumbers(client, location, closing, out);
|
|
868
|
-
for (const number of epicProtected)
|
|
869
|
-
closing.delete(number);
|
|
870
|
-
out.count('Issues to close', closing.size);
|
|
871
|
-
await closeRelatedIssues(context, client, location, closing, epicProtected);
|
|
872
|
-
if (input.delete_branch)
|
|
873
|
-
await deleteMergedBranch(context, client, location, pr.head_ref);
|
|
874
|
-
if (input.skip_local_cleanup)
|
|
875
|
-
return;
|
|
876
|
-
localCleanupAfterMerge(context, pr.head_ref, config, location);
|
|
877
|
-
if (input.dry_run) {
|
|
878
|
-
return;
|
|
879
|
-
}
|
|
880
|
-
removeActiveFlags(out);
|
|
881
|
-
consumeFlag(FLAG_MERGE_SLASH_PENDING);
|
|
902
|
+
throw new CommandExit(PREFLIGHT_EXIT_CODE, 'preflight-failed');
|
|
882
903
|
}
|
|
883
904
|
const prCreate = defineCommand({
|
|
884
|
-
path:
|
|
905
|
+
path: PR_CREATE_PATH,
|
|
885
906
|
description: 'Create a PR (pull request)',
|
|
886
907
|
input: CreateInputSchema,
|
|
908
|
+
output: PR_CREATE_OUTPUT,
|
|
887
909
|
positional: ['file'],
|
|
888
910
|
shortFlags: { message: '-m', title: '-t', base: '-b', draft: '-d', prepare: '-p', dry_run: '-n', repo: '-r' },
|
|
889
911
|
hasOwnRepo: true,
|
|
@@ -893,41 +915,31 @@ const prCreate = defineCommand({
|
|
|
893
915
|
return 0;
|
|
894
916
|
},
|
|
895
917
|
});
|
|
896
|
-
const
|
|
897
|
-
path: ['pr', '
|
|
918
|
+
const prShow = defineCommand({
|
|
919
|
+
path: ['pr', 'show'],
|
|
898
920
|
description: 'Get PR details efficiently (GraphQL, only the needed fields)',
|
|
899
|
-
input:
|
|
921
|
+
input: ShowInputSchema,
|
|
922
|
+
output: PR_SHOW_OUTPUT,
|
|
900
923
|
positional: ['pr_ref'],
|
|
901
924
|
shortFlags: { json: '-j', reviews: '-r' },
|
|
902
925
|
interactive: false,
|
|
903
926
|
run: async (input, io) => {
|
|
904
|
-
await
|
|
927
|
+
await runShow(input, io);
|
|
905
928
|
return 0;
|
|
906
929
|
},
|
|
907
930
|
});
|
|
908
|
-
const
|
|
909
|
-
path: ['pr', '
|
|
931
|
+
const prCheck = defineCommand({
|
|
932
|
+
path: ['pr', 'check'],
|
|
910
933
|
description: 'Show all the information to check before creating a PR',
|
|
911
|
-
input:
|
|
934
|
+
input: CheckInputSchema,
|
|
935
|
+
output: PR_CHECK_OUTPUT,
|
|
912
936
|
positional: [],
|
|
913
937
|
shortFlags: { directory: '-D' },
|
|
914
938
|
interactive: false,
|
|
915
939
|
run: (input, io) => {
|
|
916
|
-
|
|
940
|
+
runCheck(input, io);
|
|
917
941
|
return Promise.resolve(0);
|
|
918
942
|
},
|
|
919
943
|
});
|
|
920
|
-
const
|
|
921
|
-
path: ['pr', 'cleanup'],
|
|
922
|
-
description: 'Clean up after a merged PR (close related Issues, delete branches, local cleanup)',
|
|
923
|
-
input: CleanupInputSchema,
|
|
924
|
-
positional: ['pr_ref'],
|
|
925
|
-
shortFlags: { dry_run: '-n', delete_branch: '-d' },
|
|
926
|
-
interactive: false,
|
|
927
|
-
run: async (input, io) => {
|
|
928
|
-
await runCleanup(input, io);
|
|
929
|
-
return 0;
|
|
930
|
-
},
|
|
931
|
-
});
|
|
932
|
-
export const PR_COMMANDS = [prCleanup, prCreate, prPreflight, prRead];
|
|
944
|
+
export const PR_COMMANDS = [prCreate, prShow, prCheck, PR_MERGE_COMMAND];
|
|
933
945
|
//# sourceMappingURL=pr.js.map
|