@pecot/workflow-mcp 0.0.0-stage → 6.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.
Files changed (287) hide show
  1. package/.claude-plugin/plugin.json +8 -0
  2. package/LICENSE +21 -0
  3. package/README.md +184 -2
  4. package/bin/pecot-workflow-mcp.mjs +10 -0
  5. package/cli/dist/cli.d.ts +26 -0
  6. package/cli/dist/cli.js +227 -0
  7. package/cli/dist/commands/board-add.d.ts +3 -0
  8. package/cli/dist/commands/board-add.js +59 -0
  9. package/cli/dist/commands/board-judgment.d.ts +60 -0
  10. package/cli/dist/commands/board-judgment.js +144 -0
  11. package/cli/dist/commands/board-move.d.ts +3 -0
  12. package/cli/dist/commands/board-move.js +57 -0
  13. package/cli/dist/commands/board-readiness.d.ts +34 -0
  14. package/cli/dist/commands/board-readiness.js +108 -0
  15. package/cli/dist/commands/board-show.d.ts +3 -0
  16. package/cli/dist/commands/board-show.js +72 -0
  17. package/cli/dist/commands/board-sync.d.ts +3 -0
  18. package/cli/dist/commands/board-sync.js +111 -0
  19. package/cli/dist/commands/board-view.d.ts +62 -0
  20. package/cli/dist/commands/board-view.js +191 -0
  21. package/cli/dist/commands/board.d.ts +3 -0
  22. package/cli/dist/commands/board.js +12 -0
  23. package/cli/dist/commands/branch.d.ts +3 -0
  24. package/cli/dist/commands/branch.js +100 -0
  25. package/cli/dist/commands/cell-table.d.ts +3 -0
  26. package/cli/dist/commands/cell-table.js +495 -0
  27. package/cli/dist/commands/command-binding.d.ts +26 -0
  28. package/cli/dist/commands/command-binding.js +270 -0
  29. package/cli/dist/commands/command-definition.d.ts +150 -0
  30. package/cli/dist/commands/command-definition.js +105 -0
  31. package/cli/dist/commands/command-help.d.ts +8 -0
  32. package/cli/dist/commands/command-help.js +173 -0
  33. package/cli/dist/commands/command-hint.d.ts +5 -0
  34. package/cli/dist/commands/command-hint.js +13 -0
  35. package/cli/dist/commands/command-stop.d.ts +21 -0
  36. package/cli/dist/commands/command-stop.js +31 -0
  37. package/cli/dist/commands/directory-option.d.ts +7 -0
  38. package/cli/dist/commands/directory-option.js +48 -0
  39. package/cli/dist/commands/failure-kind.d.ts +3 -0
  40. package/cli/dist/commands/failure-kind.js +34 -0
  41. package/cli/dist/commands/failure.d.ts +19 -0
  42. package/cli/dist/commands/failure.js +59 -0
  43. package/cli/dist/commands/fuzzy.d.ts +7 -0
  44. package/cli/dist/commands/fuzzy.js +79 -0
  45. package/cli/dist/commands/github-client.d.ts +16 -0
  46. package/cli/dist/commands/github-client.js +33 -0
  47. package/cli/dist/commands/global-options.d.ts +25 -0
  48. package/cli/dist/commands/global-options.js +83 -0
  49. package/cli/dist/commands/help-layout.d.ts +40 -0
  50. package/cli/dist/commands/help-layout.js +117 -0
  51. package/cli/dist/commands/help.d.ts +8 -0
  52. package/cli/dist/commands/help.js +50 -0
  53. package/cli/dist/commands/input-schema.d.ts +14 -0
  54. package/cli/dist/commands/input-schema.js +56 -0
  55. package/cli/dist/commands/issue-board.d.ts +71 -0
  56. package/cli/dist/commands/issue-board.js +122 -0
  57. package/cli/dist/commands/issue-comment.d.ts +3 -0
  58. package/cli/dist/commands/issue-comment.js +215 -0
  59. package/cli/dist/commands/issue-create.d.ts +3 -0
  60. package/cli/dist/commands/issue-create.js +786 -0
  61. package/cli/dist/commands/issue-dependency.d.ts +3 -0
  62. package/cli/dist/commands/issue-dependency.js +282 -0
  63. package/cli/dist/commands/issue-readiness.d.ts +94 -0
  64. package/cli/dist/commands/issue-readiness.js +218 -0
  65. package/cli/dist/commands/issue-reopen.d.ts +3 -0
  66. package/cli/dist/commands/issue-reopen.js +115 -0
  67. package/cli/dist/commands/issue-shared.d.ts +172 -0
  68. package/cli/dist/commands/issue-shared.js +426 -0
  69. package/cli/dist/commands/issue-show.d.ts +3 -0
  70. package/cli/dist/commands/issue-show.js +169 -0
  71. package/cli/dist/commands/issue.d.ts +3 -0
  72. package/cli/dist/commands/issue.js +13 -0
  73. package/cli/dist/commands/names.d.ts +42 -0
  74. package/cli/dist/commands/names.js +78 -0
  75. package/cli/dist/commands/output.d.ts +90 -0
  76. package/cli/dist/commands/output.js +194 -0
  77. package/cli/dist/commands/pr-waiting.d.ts +20 -0
  78. package/cli/dist/commands/pr-waiting.js +106 -0
  79. package/cli/dist/commands/pr.d.ts +22 -0
  80. package/cli/dist/commands/pr.js +852 -0
  81. package/cli/dist/commands/project-sync.d.ts +92 -0
  82. package/cli/dist/commands/project-sync.js +282 -0
  83. package/cli/dist/commands/project.d.ts +6 -0
  84. package/cli/dist/commands/project.js +714 -0
  85. package/cli/dist/commands/registry.d.ts +6 -0
  86. package/cli/dist/commands/registry.js +30 -0
  87. package/cli/dist/commands/release.d.ts +10 -0
  88. package/cli/dist/commands/release.js +353 -0
  89. package/cli/dist/commands/renamed-commands.d.ts +26 -0
  90. package/cli/dist/commands/renamed-commands.js +53 -0
  91. package/cli/dist/commands/repository-display.d.ts +3 -0
  92. package/cli/dist/commands/repository-display.js +7 -0
  93. package/cli/dist/commands/repository-match.d.ts +14 -0
  94. package/cli/dist/commands/repository-match.js +34 -0
  95. package/cli/dist/commands/rich-panel.d.ts +22 -0
  96. package/cli/dist/commands/rich-panel.js +295 -0
  97. package/cli/dist/commands/session-finish.d.ts +3 -0
  98. package/cli/dist/commands/session-finish.js +267 -0
  99. package/cli/dist/commands/session-start.d.ts +3 -0
  100. package/cli/dist/commands/session-start.js +236 -0
  101. package/cli/dist/commands/session.d.ts +6 -0
  102. package/cli/dist/commands/session.js +214 -0
  103. package/cli/dist/commands/tracker-sync-dependabot.d.ts +7 -0
  104. package/cli/dist/commands/tracker-sync-dependabot.js +156 -0
  105. package/cli/dist/commands/tracker-sync-security.d.ts +7 -0
  106. package/cli/dist/commands/tracker-sync-security.js +153 -0
  107. package/cli/dist/commands/tracker-sync.d.ts +65 -0
  108. package/cli/dist/commands/tracker-sync.js +50 -0
  109. package/cli/dist/commands/tracker.d.ts +3 -0
  110. package/cli/dist/commands/tracker.js +18 -0
  111. package/cli/dist/commands/usage-error.d.ts +51 -0
  112. package/cli/dist/commands/usage-error.js +78 -0
  113. package/cli/dist/commands/value-types.d.ts +46 -0
  114. package/cli/dist/commands/value-types.js +94 -0
  115. package/cli/dist/commands/work-target.d.ts +22 -0
  116. package/cli/dist/commands/work-target.js +82 -0
  117. package/cli/dist/commands/worktree.d.ts +3 -0
  118. package/cli/dist/commands/worktree.js +339 -0
  119. package/cli/dist/domain/api-error-detail.d.ts +10 -0
  120. package/cli/dist/domain/api-error-detail.js +25 -0
  121. package/cli/dist/domain/batch-plan.d.ts +73 -0
  122. package/cli/dist/domain/batch-plan.js +114 -0
  123. package/cli/dist/domain/blocked-by-change.d.ts +99 -0
  124. package/cli/dist/domain/blocked-by-change.js +101 -0
  125. package/cli/dist/domain/board-move.d.ts +90 -0
  126. package/cli/dist/domain/board-move.js +92 -0
  127. package/cli/dist/domain/branch-name.d.ts +5 -0
  128. package/cli/dist/domain/branch-name.js +10 -0
  129. package/cli/dist/domain/changelog.d.ts +43 -0
  130. package/cli/dist/domain/changelog.js +107 -0
  131. package/cli/dist/domain/command-hint.d.ts +85 -0
  132. package/cli/dist/domain/command-hint.js +148 -0
  133. package/cli/dist/domain/config.d.ts +219 -0
  134. package/cli/dist/domain/config.js +310 -0
  135. package/cli/dist/domain/dependabot-pull-requests.d.ts +82 -0
  136. package/cli/dist/domain/dependabot-pull-requests.js +338 -0
  137. package/cli/dist/domain/dependabot-source.d.ts +51 -0
  138. package/cli/dist/domain/dependabot-source.js +4 -0
  139. package/cli/dist/domain/dependabot.d.ts +47 -0
  140. package/cli/dist/domain/dependabot.js +88 -0
  141. package/cli/dist/domain/errors.d.ts +24 -0
  142. package/cli/dist/domain/errors.js +36 -0
  143. package/cli/dist/domain/field-options.d.ts +31 -0
  144. package/cli/dist/domain/field-options.js +44 -0
  145. package/cli/dist/domain/format.d.ts +94 -0
  146. package/cli/dist/domain/format.js +234 -0
  147. package/cli/dist/domain/frontmatter.d.ts +137 -0
  148. package/cli/dist/domain/frontmatter.js +290 -0
  149. package/cli/dist/domain/git-runner.d.ts +10 -0
  150. package/cli/dist/domain/git-runner.js +4 -0
  151. package/cli/dist/domain/git-url.d.ts +17 -0
  152. package/cli/dist/domain/git-url.js +30 -0
  153. package/cli/dist/domain/issue-kind.d.ts +16 -0
  154. package/cli/dist/domain/issue-kind.js +16 -0
  155. package/cli/dist/domain/issue-order.d.ts +55 -0
  156. package/cli/dist/domain/issue-order.js +65 -0
  157. package/cli/dist/domain/issue-readout.d.ts +143 -0
  158. package/cli/dist/domain/issue-readout.js +4 -0
  159. package/cli/dist/domain/json-null.d.ts +2 -0
  160. package/cli/dist/domain/json-null.js +5 -0
  161. package/cli/dist/domain/json.d.ts +21 -0
  162. package/cli/dist/domain/json.js +47 -0
  163. package/cli/dist/domain/prerequisites.d.ts +32 -0
  164. package/cli/dist/domain/prerequisites.js +192 -0
  165. package/cli/dist/domain/pull-request.d.ts +201 -0
  166. package/cli/dist/domain/pull-request.js +281 -0
  167. package/cli/dist/domain/python-format.d.ts +105 -0
  168. package/cli/dist/domain/python-format.js +304 -0
  169. package/cli/dist/domain/readiness.d.ts +199 -0
  170. package/cli/dist/domain/readiness.js +391 -0
  171. package/cli/dist/domain/reference-parser.d.ts +51 -0
  172. package/cli/dist/domain/reference-parser.js +123 -0
  173. package/cli/dist/domain/release.d.ts +53 -0
  174. package/cli/dist/domain/release.js +65 -0
  175. package/cli/dist/domain/repository-policy.d.ts +38 -0
  176. package/cli/dist/domain/repository-policy.js +66 -0
  177. package/cli/dist/domain/repository-resolver.d.ts +57 -0
  178. package/cli/dist/domain/repository-resolver.js +122 -0
  179. package/cli/dist/domain/sections.d.ts +69 -0
  180. package/cli/dist/domain/sections.js +514 -0
  181. package/cli/dist/domain/security-alerts-source.d.ts +29 -0
  182. package/cli/dist/domain/security-alerts-source.js +4 -0
  183. package/cli/dist/domain/security-alerts.d.ts +52 -0
  184. package/cli/dist/domain/security-alerts.js +107 -0
  185. package/cli/dist/domain/security-tracker.d.ts +115 -0
  186. package/cli/dist/domain/security-tracker.js +353 -0
  187. package/cli/dist/domain/state.d.ts +59 -0
  188. package/cli/dist/domain/state.js +95 -0
  189. package/cli/dist/domain/tracker-body.d.ts +70 -0
  190. package/cli/dist/domain/tracker-body.js +65 -0
  191. package/cli/dist/domain/work-start.d.ts +34 -0
  192. package/cli/dist/domain/work-start.js +49 -0
  193. package/cli/dist/domain/yaml-document.d.ts +5 -0
  194. package/cli/dist/domain/yaml-document.js +206 -0
  195. package/cli/dist/infra/authored-notes.d.ts +37 -0
  196. package/cli/dist/infra/authored-notes.js +72 -0
  197. package/cli/dist/infra/changelog-file.d.ts +19 -0
  198. package/cli/dist/infra/changelog-file.js +43 -0
  199. package/cli/dist/infra/child-stdin.d.ts +4 -0
  200. package/cli/dist/infra/child-stdin.js +8 -0
  201. package/cli/dist/infra/config-store.d.ts +53 -0
  202. package/cli/dist/infra/config-store.js +134 -0
  203. package/cli/dist/infra/diagnostics.d.ts +9 -0
  204. package/cli/dist/infra/diagnostics.js +2 -0
  205. package/cli/dist/infra/file-kind.d.ts +9 -0
  206. package/cli/dist/infra/file-kind.js +26 -0
  207. package/cli/dist/infra/frontmatter-file.d.ts +14 -0
  208. package/cli/dist/infra/frontmatter-file.js +30 -0
  209. package/cli/dist/infra/git.d.ts +86 -0
  210. package/cli/dist/infra/git.js +145 -0
  211. package/cli/dist/infra/github/auth.d.ts +60 -0
  212. package/cli/dist/infra/github/auth.js +158 -0
  213. package/cli/dist/infra/github/client.d.ts +178 -0
  214. package/cli/dist/infra/github/client.js +579 -0
  215. package/cli/dist/infra/github/dependabot-source.d.ts +13 -0
  216. package/cli/dist/infra/github/dependabot-source.js +33 -0
  217. package/cli/dist/infra/github/errors.d.ts +65 -0
  218. package/cli/dist/infra/github/errors.js +64 -0
  219. package/cli/dist/infra/github/index.d.ts +13 -0
  220. package/cli/dist/infra/github/index.js +19 -0
  221. package/cli/dist/infra/github/issues.d.ts +165 -0
  222. package/cli/dist/infra/github/issues.js +428 -0
  223. package/cli/dist/infra/github/payload.d.ts +44 -0
  224. package/cli/dist/infra/github/payload.js +80 -0
  225. package/cli/dist/infra/github/projects.d.ts +143 -0
  226. package/cli/dist/infra/github/projects.js +384 -0
  227. package/cli/dist/infra/github/pulls.d.ts +104 -0
  228. package/cli/dist/infra/github/pulls.js +217 -0
  229. package/cli/dist/infra/github/queries.d.ts +44 -0
  230. package/cli/dist/infra/github/queries.js +1031 -0
  231. package/cli/dist/infra/github/readout.d.ts +22 -0
  232. package/cli/dist/infra/github/readout.js +167 -0
  233. package/cli/dist/infra/github/repos.d.ts +86 -0
  234. package/cli/dist/infra/github/repos.js +168 -0
  235. package/cli/dist/infra/github/rest-path.d.ts +14 -0
  236. package/cli/dist/infra/github/rest-path.js +31 -0
  237. package/cli/dist/infra/github/security-alerts-source.d.ts +15 -0
  238. package/cli/dist/infra/github/security-alerts-source.js +73 -0
  239. package/cli/dist/infra/gitignore-spec.d.ts +36 -0
  240. package/cli/dist/infra/gitignore-spec.js +235 -0
  241. package/cli/dist/infra/nx-scope.d.ts +51 -0
  242. package/cli/dist/infra/nx-scope.js +182 -0
  243. package/cli/dist/infra/os-error.d.ts +24 -0
  244. package/cli/dist/infra/os-error.js +38 -0
  245. package/cli/dist/infra/paths.d.ts +88 -0
  246. package/cli/dist/infra/paths.js +234 -0
  247. package/cli/dist/infra/state-store.d.ts +54 -0
  248. package/cli/dist/infra/state-store.js +130 -0
  249. package/cli/dist/infra/template-store.d.ts +15 -0
  250. package/cli/dist/infra/template-store.js +34 -0
  251. package/cli/dist/infra/text-file.d.ts +12 -0
  252. package/cli/dist/infra/text-file.js +33 -0
  253. package/cli/dist/infra/worktree-copy.d.ts +24 -0
  254. package/cli/dist/infra/worktree-copy.js +95 -0
  255. package/cli/dist/infra/worktree-links.d.ts +142 -0
  256. package/cli/dist/infra/worktree-links.js +440 -0
  257. package/cli/dist/infra/worktree-setup.d.ts +21 -0
  258. package/cli/dist/infra/worktree-setup.js +41 -0
  259. package/cli/dist/infra/worktree.d.ts +185 -0
  260. package/cli/dist/infra/worktree.js +584 -0
  261. package/cli/dist/mcp/result.d.ts +61 -0
  262. package/cli/dist/mcp/result.js +96 -0
  263. package/cli/dist/mcp/serve.d.ts +51 -0
  264. package/cli/dist/mcp/serve.js +183 -0
  265. package/cli/dist/mcp/server.d.ts +21 -0
  266. package/cli/dist/mcp/server.js +142 -0
  267. package/cli/dist/mcp/session-directory.d.ts +26 -0
  268. package/cli/dist/mcp/session-directory.js +84 -0
  269. package/cli/dist/package.json +1 -0
  270. package/cli/dist/version.d.ts +17 -0
  271. package/cli/dist/version.js +42 -0
  272. package/cli/templates/comment/merge-diff.md +34 -0
  273. package/cli/templates/comment/plan.md +195 -0
  274. package/cli/templates/comment/precede-notify.md +33 -0
  275. package/cli/templates/comment/review-findings.md +42 -0
  276. package/cli/templates/comment/review-resolution.md +48 -0
  277. package/cli/templates/issue/bug.md +63 -0
  278. package/cli/templates/issue/epic.md +54 -0
  279. package/cli/templates/issue/task-implement.md +74 -0
  280. package/cli/templates/issue/task.md +48 -0
  281. package/cli/templates/issue/tracker.md +48 -0
  282. package/cli/templates/pr/create.md +123 -0
  283. package/cli/templates/pr/release.md +56 -0
  284. package/cli/templates/workflow/pecot-board-sync.yml +84 -0
  285. package/hooks/lib/core/pecot-gitignore-ensure.sh +48 -0
  286. package/npm-shrinkwrap.json +83 -0
  287. package/package.json +22 -4
@@ -0,0 +1,852 @@
1
+ /* eslint-disable security/detect-non-literal-fs-filename -- パスは利用者が指定する */
2
+ /* eslint-disable @typescript-eslint/prefer-readonly-parameter-types -- GitHubClient は内部の状態を持つ */
3
+ // pr create・pr show・pr check。cli/commands/pr.py の移植。
4
+ // 途中で抜ける箇所は CommandExit を投げ、defineCommand が終了コードにする。
5
+ import { existsSync, statSync, writeFileSync } from 'node:fs';
6
+ import path from 'node:path';
7
+ import { z } from 'zod';
8
+ import { describeApiError } from '../domain/api-error-detail.js';
9
+ import { extractIssueNumberFromBranch } from '../domain/branch-name.js';
10
+ import { effectiveReleaseType, findRepository, getDevelopBranch, getFieldId, getOptionId, getReleaseBranch } from '../domain/config.js';
11
+ import { InvalidValueError } from '../domain/errors.js';
12
+ import { FrontmatterError } from '../domain/frontmatter.js';
13
+ import { parseRemoteUrl } from '../domain/git-url.js';
14
+ import { isEpicIssue } from '../domain/issue-kind.js';
15
+ import { jsonField } from '../domain/json.js';
16
+ import { appendIssueCloseIfNeeded, collectPreflightWarnings, decidePullRequestBase, describeBaseStop, describePushStatus, formatPreflightWarning, formatPullRequestMarkdown, formatPullRequestWithReviewsMarkdown, isReleasePullRequest, pickLowerPullRequest, validatePullRequestContent } from '../domain/pull-request.js';
17
+ import { parsePythonInteger, pythonStrip } from '../domain/python-format.js';
18
+ import { ReferenceParseError, parsePullRequestReference } from '../domain/reference-parser.js';
19
+ import { AmbiguousRepositoryError, resolveRepository, splitOwnerRepository } from '../domain/repository-resolver.js';
20
+ import { FLAG_PECOT_ACTIVE, FLAG_PR_CREATE_SLASH_PENDING } from '../domain/state.js';
21
+ import { loadActiveConfig } from '../infra/config-store.js';
22
+ import { parsePullRequestFile } from '../infra/frontmatter-file.js';
23
+ import { gitCurrentBranch, gitRemoteUrl, gitRunnerFor, gitStdout, gitToplevel, primaryRemoteName, runGit } from '../infra/git.js';
24
+ import { TransportFailure } from '../infra/github/client.js';
25
+ import { GitHubAPIError } from '../infra/github/errors.js';
26
+ import { changedFiles, expectedScope, nxProjects, parseTitleScope } from '../infra/nx-scope.js';
27
+ import { isFileNotFound } from '../infra/os-error.js';
28
+ import { outputDirectory, OutputPathReservationError, resolveRealPath, withReservedOutputPath } from '../infra/paths.js';
29
+ import { consumeFlag, readBaseRecord, readFlag } from '../infra/state-store.js';
30
+ import { readTemplateSections, templateFile } from '../infra/template-store.js';
31
+ import { readTextFile } from '../infra/text-file.js';
32
+ import { commandHint, hinted, inputHint, inputNameHint, placeholder } from './command-hint.js';
33
+ import { requireActiveConfigPlain, stopWith } from './command-stop.js';
34
+ import { kindOfFailure } from './failure.js';
35
+ import { USAGE_EXIT_CODE } from './usage-error.js';
36
+ import { directorySchema } from './directory-option.js';
37
+ import { createGitHubClient } from './github-client.js';
38
+ import { createOutput } from './output.js';
39
+ import { CommandExit, defineCommand } from './command-definition.js';
40
+ import { moveWaitingIssues } from './pr-waiting.js';
41
+ export const PR_REFERENCE_DESCRIPTION = 'PR reference (`owner/repo/N`, or the short form `N` in the repository of `--repo`, or else of the git remote of the current directory)';
42
+ // 本文の検証の失敗。1(通信・設定・引数)と 2(preflight)と区別する
43
+ const VALIDATION_EXIT_CODE = 3;
44
+ const PREFLIGHT_EXIT_CODE = 2;
45
+ // 下の段の PR が開いておらず、マージもされていない
46
+ const NO_OPEN_BASE_EXIT_CODE = 2;
47
+ // git ls-remote --exit-code が、一致する参照が無いときに返す
48
+ const LS_REMOTE_NOT_FOUND = 2;
49
+ // Python の `{e}` に当たる、例外の文
50
+ export function reasonOf(error) {
51
+ return error instanceof Error ? error.message : String(error);
52
+ }
53
+ function templateKindOf(template) {
54
+ return template === 'release' ? 'release' : 'create';
55
+ }
56
+ export function isPositive(value) {
57
+ return value !== undefined && value !== 0;
58
+ }
59
+ export function primaryRemote(directory) {
60
+ const name = primaryRemoteName(directory);
61
+ if (name === undefined)
62
+ return undefined;
63
+ const url = gitRemoteUrl(directory, name);
64
+ if (url === undefined)
65
+ return undefined;
66
+ try {
67
+ return { name, url, location: parseRemoteUrl(url) };
68
+ }
69
+ catch (error) {
70
+ if (error instanceof InvalidValueError)
71
+ return { name, url, location: undefined };
72
+ throw error;
73
+ }
74
+ }
75
+ // scope を nx のプロジェクトと比べる対象か。release_type が nx で、base が develop か積んだ base で、remote と作業ツリーが対象に合うときだけ。
76
+ // 下の段を squash でマージした後は、開発ブランチとの差分がその段のファイルも含むので、記録のコミットから比べる
77
+ function nxScopeTarget(config, owner, repository, base, directory, stacked) {
78
+ const configured = findRepository(config, owner, repository);
79
+ if (configured === undefined || effectiveReleaseType(configured) !== 'nx' || (stacked === undefined && base !== getDevelopBranch(config, owner, repository)))
80
+ return undefined;
81
+ const found = primaryRemote(directory);
82
+ const location = found?.location;
83
+ const isSameRepository = location?.owner.toLowerCase() === owner.toLowerCase() && location.repository.toLowerCase() === repository.toLowerCase();
84
+ if (found === undefined || !isSameRepository)
85
+ return undefined;
86
+ const toplevel = gitToplevel({ cwd: directory });
87
+ if (toplevel === undefined || !isRegularFile(path.join(toplevel, 'nx.json')))
88
+ return undefined;
89
+ if (stacked === undefined)
90
+ return { toplevel, from: `${found.name}/${base}` };
91
+ return { toplevel, from: 'sha' in stacked ? stacked.sha : `${found.name}/${stacked.branch}` };
92
+ }
93
+ // Python の Path.is_file() と同じく、stat の失敗は「無い」と扱う
94
+ function isRegularFile(file) {
95
+ try {
96
+ return statSync(file).isFile();
97
+ }
98
+ catch {
99
+ return false;
100
+ }
101
+ }
102
+ function expectedTitleScope(target, head, out) {
103
+ const projects = nxProjects(target.toplevel);
104
+ const files = projects === undefined ? undefined : changedFiles(target.toplevel, target.from, head);
105
+ if (projects === undefined || files === undefined) {
106
+ out.warning('cannot read nx projects or the diff; skipped the PR title scope check');
107
+ return undefined;
108
+ }
109
+ return expectedScope(files, projects);
110
+ }
111
+ function titleScopeErrors(query, out) {
112
+ const { config, owner, repository, title, base, head, directory, template, developBranch, releaseBranch } = query;
113
+ if (isReleasePullRequest(template, base, head, developBranch, releaseBranch))
114
+ return [];
115
+ const target = nxScopeTarget(config, owner, repository, base, directory, query.stacked);
116
+ if (target === undefined)
117
+ return [];
118
+ const expected = expectedTitleScope(target, head, out);
119
+ if (expected === undefined || expected.length === 0)
120
+ return [];
121
+ const given = parseTitleScope(title);
122
+ if (given !== undefined && new Set(given).size === new Set(expected).size && given.every(scope => expected.includes(scope)))
123
+ return [];
124
+ const shown = given === undefined ? 'none' : given.join(',');
125
+ return [`PR title scope must be ${expected.join(',')} (given: ${shown}; computed from the tags of the changed nx projects)`];
126
+ }
127
+ // pr create
128
+ function inReviewOperation(issueNumber) {
129
+ return { verb: 'set', target: `Issue #${String(issueNumber)} status to In Review` };
130
+ }
131
+ async function updateIssueStatusToInReview(config, client, location, headBranch, out) {
132
+ const issueNumber = extractIssueNumberFromBranch(headBranch);
133
+ if (issueNumber === undefined)
134
+ return;
135
+ const label = `Issue #${String(issueNumber)}`;
136
+ let itemId;
137
+ try {
138
+ itemId = await client.getItemIdByIssue(config.project.id, location.owner, location.repository, issueNumber);
139
+ }
140
+ catch (error) {
141
+ out.warning(`board item lookup for ${label} failed: ${reasonOf(error)}`);
142
+ return;
143
+ }
144
+ if (itemId === undefined) {
145
+ out.warning(`${label} is not on the board; status not updated`);
146
+ return;
147
+ }
148
+ const optionId = getOptionId(config, 'workflow', 'in_review');
149
+ if (optionId === undefined) {
150
+ out.warning('workflow field has no in_review status; status not updated');
151
+ return;
152
+ }
153
+ const fieldId = getFieldId(config, 'workflow');
154
+ if (fieldId === undefined) {
155
+ out.warning('workflow field not found; status not updated');
156
+ return;
157
+ }
158
+ try {
159
+ await client.updateProjectItemField(config.project.id, itemId, fieldId, optionId);
160
+ }
161
+ catch (error) {
162
+ out.warning(`status update of ${label} failed: ${reasonOf(error)}`);
163
+ return;
164
+ }
165
+ out.done(inReviewOperation(issueNumber));
166
+ }
167
+ const LINK_PATH = ['project', 'link'];
168
+ const PR_CREATE_PATH = ['pr', 'create'];
169
+ function exitOnUnsetBranch(template, base, head, developBranch, releaseBranch, out) {
170
+ const isRelease = isReleasePullRequest(template, base, head, developBranch, releaseBranch);
171
+ if (isRelease && (releaseBranch === undefined || releaseBranch === '')) {
172
+ stopWith(out, hinted `release_branch is not set\nset it with: ${commandHint(LINK_PATH, { repo: 'owner/repo', release_branch: 'main' })}`, 'repo-setting-missing');
173
+ }
174
+ if (!isRelease && (developBranch === undefined || developBranch === '')) {
175
+ stopWith(out, hinted `develop_branch is not set\nset it with: ${commandHint(LINK_PATH, { repo: 'owner/repo', develop_branch: 'develop' })}`, 'repo-setting-missing');
176
+ }
177
+ }
178
+ function resolveHeadBranch(head, directory, out) {
179
+ if (head !== undefined && head !== '')
180
+ return head;
181
+ const current = gitCurrentBranch(directory);
182
+ return current === undefined || current === '' ? stopWith(out, 'cannot determine the head branch', 'git-unresolved') : current;
183
+ }
184
+ async function appendCloseUnlessEpic(config, location, body, issueNumber, out) {
185
+ try {
186
+ const kind = await createGitHubClient(out, config.host).getIssueKind(location.owner, location.repository, issueNumber);
187
+ if (!isEpicIssue(kind))
188
+ return appendIssueCloseIfNeeded(body, issueNumber);
189
+ out.warning(`Issue #${String(issueNumber)} at the end of the branch is an Epic; Closes not added`);
190
+ return body;
191
+ }
192
+ catch (error) {
193
+ if (error instanceof GitHubAPIError)
194
+ return appendIssueCloseIfNeeded(body, issueNumber);
195
+ throw error;
196
+ }
197
+ }
198
+ function exitOnValidationErrors(errors, out) {
199
+ if (errors.length === 0)
200
+ return;
201
+ for (const error of errors)
202
+ out.error(error);
203
+ throw new CommandExit(VALIDATION_EXIT_CODE, 'content-invalid');
204
+ }
205
+ function createOperation(draft) {
206
+ const kind = draft.isDraft ? 'draft PR' : 'PR';
207
+ const suffix = draft.isRelease ? ' (release template)' : '';
208
+ return { verb: 'create', target: `${kind} ${draft.location.owner}/${draft.location.repository} ${draft.head} -> ${draft.base}: ${draft.title}${suffix}` };
209
+ }
210
+ function printPreflightWarnings(out, warnings) {
211
+ for (const warning of warnings)
212
+ out.warning(formatPreflightWarning(warning));
213
+ }
214
+ // git の読み取り。失敗は Python の文字列の印にする
215
+ function getGitStatus(cwd) {
216
+ return gitStdout(['status'], { cwd }) ?? '(git status failed)';
217
+ }
218
+ function getStashList(cwd) {
219
+ const stdout = gitStdout(['stash', 'list'], { cwd });
220
+ return stdout === undefined ? '(git stash list failed)' : pythonStrip(stdout) || '(no stash)';
221
+ }
222
+ function getPushStatus(branch, cwd, remote) {
223
+ const failed = { isPushed: false, message: '(git rev-list failed)' };
224
+ try {
225
+ if (runGit(['rev-parse', '--verify', `${remote}/${branch}`], { cwd }).exitCode !== 0) {
226
+ return { isPushed: false, message: `${remote}/${branch} does not exist (not pushed)` };
227
+ }
228
+ }
229
+ catch (error) {
230
+ if (isFileNotFound(error))
231
+ return { isPushed: false, message: '(git rev-parse failed)' };
232
+ throw error;
233
+ }
234
+ const ahead = gitStdout(['rev-list', '--count', `${remote}/${branch}..${branch}`], { cwd });
235
+ const behind = ahead === undefined ? undefined : gitStdout(['rev-list', '--count', `${branch}..${remote}/${branch}`], { cwd });
236
+ const aheadCount = ahead === undefined ? undefined : parsePythonInteger(pythonStrip(ahead));
237
+ const behindCount = behind === undefined ? undefined : parsePythonInteger(pythonStrip(behind));
238
+ return aheadCount === undefined || behindCount === undefined ? failed : describePushStatus(remote, branch, aheadCount, behindCount);
239
+ }
240
+ // pr create の早い確認と pr check が共有する前提。満たさなければ終了コード 1
241
+ function validatePullRequestContext(directory, out) {
242
+ if (gitToplevel({ cwd: directory }) === undefined)
243
+ stopWith(out, 'not a git repository', 'git-unresolved');
244
+ const found = primaryRemote(directory);
245
+ if (found === undefined)
246
+ return stopWith(out, 'git remote not found', 'git-unresolved');
247
+ const currentBranch = gitCurrentBranch(directory);
248
+ if (currentBranch === undefined)
249
+ return stopWith(out, 'cannot determine the current branch', 'git-unresolved');
250
+ if (found.location === undefined)
251
+ return stopWith(out, 'cannot read repository info from the remote URL\ncheck it with: git remote -v', 'git-unresolved');
252
+ return { remoteUrl: found.url, currentBranch, location: found.location, remoteName: found.name };
253
+ }
254
+ function runPreflightChecksOrExit(directory, out) {
255
+ const context = validatePullRequestContext(directory, out);
256
+ const push = getPushStatus(context.currentBranch, directory, context.remoteName);
257
+ const warnings = collectPreflightWarnings({ gitStatus: getGitStatus(directory), stashList: getStashList(directory), isPushed: push.isPushed, pushMessage: push.message });
258
+ if (warnings.length === 0)
259
+ return;
260
+ out.error('preflight found warnings; fix them before creating a PR');
261
+ printPreflightWarnings(out, warnings);
262
+ throw new CommandExit(PREFLIGHT_EXIT_CODE, 'preflight-failed');
263
+ }
264
+ // PR を作った後の処理の失敗は warning にとどめ、URL の出力まで進める
265
+ function isRequestFailure(error) {
266
+ return error instanceof GitHubAPIError || error instanceof TransportFailure;
267
+ }
268
+ function describeRequestFailure(error) {
269
+ return error instanceof GitHubAPIError ? describeApiError(error) : error.message;
270
+ }
271
+ // 1 回の pr create で、クライアントを作るのは要るときの 1 回だけにする
272
+ function lazyClient(config, out) {
273
+ let client;
274
+ return () => {
275
+ client ??= createGitHubClient(out, config.host);
276
+ return client;
277
+ };
278
+ }
279
+ // 下の段の PR が入っているスタックに足す。無ければ下の段と新しい PR で作る。失敗は warning にとどめる
280
+ async function registerStack(client, location, lower, created, out) {
281
+ if (created === undefined) {
282
+ out.warning('could not register stack: the PR creation response has no PR number');
283
+ return;
284
+ }
285
+ try {
286
+ const stack = await client.getStackOfPullRequest(location.owner, location.repository, lower);
287
+ const top = stack?.pullRequests.at(-1);
288
+ // GitHub は一番上にしか足せないので、同じ下の段に 2 つ目を積んだときは 422 を待たずに知らせる
289
+ if (stack !== undefined && top !== lower) {
290
+ 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`);
291
+ return;
292
+ }
293
+ const registered = stack === undefined
294
+ ? await client.createStack(location.owner, location.repository, [lower, created])
295
+ : await client.addToStack(location.owner, location.repository, stack.number, [created]);
296
+ out.done({ verb: 'add', target: `PR #${String(created)} to stack #${String(registered.number)}` });
297
+ }
298
+ catch (error) {
299
+ if (!isRequestFailure(error))
300
+ throw error;
301
+ out.warning(`could not register stack: ${describeRequestFailure(error)}`);
302
+ }
303
+ }
304
+ async function moveWaitingIssuesSafely(client, config, location, issueNumber, pullRequest, out) {
305
+ try {
306
+ await moveWaitingIssues(out, client, config, { repository: location, issueNumber, pullRequest });
307
+ }
308
+ catch (error) {
309
+ if (!isRequestFailure(error))
310
+ throw error;
311
+ out.warning(`could not move the Issues waiting for #${String(issueNumber)}: ${describeRequestFailure(error)}`);
312
+ }
313
+ }
314
+ async function submitPullRequest(config, client, directory, draft, stackOn, out) {
315
+ runPreflightChecksOrExit(directory, out);
316
+ let created;
317
+ try {
318
+ created = await client().createPullRequest(draft.location.owner, draft.location.repository, draft.title, draft.body, draft.head, draft.base, draft.isDraft);
319
+ }
320
+ catch (error) {
321
+ if (error instanceof GitHubAPIError)
322
+ return stopWith(out, `PR creation failed: ${error.message}`, kindOfFailure(error));
323
+ throw error;
324
+ }
325
+ out.done(createOperation(draft));
326
+ const createdNumber = jsonField(created, 'number');
327
+ const pullRequest = typeof createdNumber === 'number' ? createdNumber : undefined;
328
+ if (!draft.isRelease)
329
+ await updateIssueStatusToInReview(config, client(), draft.location, draft.head, out);
330
+ if (stackOn !== undefined)
331
+ await registerStack(client(), draft.location, stackOn, pullRequest, out);
332
+ const issueNumber = extractIssueNumberFromBranch(draft.head);
333
+ if (!draft.isRelease && isPositive(issueNumber))
334
+ await moveWaitingIssuesSafely(client(), config, draft.location, issueNumber, pullRequest, out);
335
+ consumeFlag(FLAG_PR_CREATE_SLASH_PENDING);
336
+ const url = jsonField(created, 'html_url');
337
+ if (typeof url !== 'string')
338
+ return stopWith(out, 'PR was created, but the response has no html_url; find it on GitHub', 'other');
339
+ out.data(url);
340
+ }
341
+ function stopOnMalformedRecord(reading, out) {
342
+ if (reading.kind === 'malformed')
343
+ stopWith(out, describeBaseStop({ kind: 'stop', reason: 'malformed', content: reading.content }).join('\n'), 'content-invalid');
344
+ }
345
+ // merge-base --is-ancestor は、祖先でなければ 1、コミットを知らなければ 128 を返す
346
+ const NOT_ANCESTOR = 1;
347
+ // 記録を使うのは、head が今のブランチで、release のテンプレートでないときだけ。形が誤っていれば終了コード 1 で止める。
348
+ // 記録のコミットが head の履歴に無ければ、別のブランチの記録なので止める。開発ブランチ向けに作ると下の段の差分が入りうるため
349
+ function readBaseRecordFor(head, template, directory, out) {
350
+ if (template === 'release' || head !== gitCurrentBranch(directory))
351
+ return undefined;
352
+ const reading = readBaseRecord();
353
+ stopOnMalformedRecord(reading, out);
354
+ if (reading.kind !== 'stacked')
355
+ return reading;
356
+ const { branch, sha } = reading.record;
357
+ const isForeign = runGit(['merge-base', '--is-ancestor', sha, head], { cwd: directory }).exitCode === NOT_ANCESTOR;
358
+ return isForeign
359
+ ? 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')
360
+ : reading;
361
+ }
362
+ // 積んだ記録なら、PR を作るリポで下の段の PR を読み、base を決める
363
+ async function decideBase(input, client, developBranch, out) {
364
+ const { reading, base, location } = input;
365
+ if (reading === undefined)
366
+ return { kind: 'use', base, stackOn: undefined, stackedBase: undefined, isLowerMerged: false };
367
+ if (reading.kind !== 'stacked')
368
+ return decidePullRequestBase({ reading, base, developBranch });
369
+ const { branch } = reading.record;
370
+ try {
371
+ const found = await client().listPullRequestsByHead(location.owner, location.repository, branch);
372
+ return decidePullRequestBase({ reading, base, developBranch, lowerPullRequest: pickLowerPullRequest(found.pullRequests) });
373
+ }
374
+ catch (error) {
375
+ if (error instanceof GitHubAPIError)
376
+ return stopWith(out, `cannot read the PR of the base branch ${branch}: ${describeApiError(error)}`, kindOfFailure(error));
377
+ throw error;
378
+ }
379
+ }
380
+ // 下の段の PR が開いているのに開発ブランチを渡したときは、内容の検証の失敗と一緒に出す(終了コード 3)
381
+ function useOrStop(decision, out) {
382
+ if (decision.kind === 'use')
383
+ return { use: decision, errors: [] };
384
+ const lines = describeBaseStop(decision);
385
+ if (decision.reason === 'lower-open')
386
+ return { use: undefined, errors: lines };
387
+ if (decision.reason === 'malformed')
388
+ return stopWith(out, lines.join('\n'), 'content-invalid');
389
+ return stopWith(out, lines.join('\n'), 'pr-state', NO_OPEN_BASE_EXIT_CODE);
390
+ }
391
+ // 下の段がマージ済みなら記録のコミットから、開いていてそのブランチへ作るならそのブランチから、題の scope を比べる
392
+ function stackedScopeOf(reading, use) {
393
+ if (use === undefined || reading?.kind !== 'stacked')
394
+ return undefined;
395
+ if (use.isLowerMerged)
396
+ return { sha: reading.record.sha };
397
+ return use.stackOn === undefined ? undefined : { branch: reading.record.branch };
398
+ }
399
+ // 検証して、dry-run なら計画を出し、そうでなければ投稿する。file と -m の両方がここを通る
400
+ async function validateAndSubmit(input, out) {
401
+ const { config, directory, template, location, title, head } = input;
402
+ const client = lazyClient(config, out);
403
+ const developBranch = getDevelopBranch(config, location.owner, location.repository);
404
+ const releaseBranch = getReleaseBranch(config, location.owner, location.repository);
405
+ exitOnUnsetBranch(template, input.base, head, developBranch, releaseBranch, out);
406
+ const { use, errors: baseErrors } = useOrStop(await decideBase(input, client, developBranch ?? '', out), out);
407
+ const base = use?.base ?? input.base;
408
+ const stacked = stackedScopeOf(input.reading, use);
409
+ const requiredSections = readTemplateSections(templateFile('pr', templateKindOf(template)));
410
+ const errors = [
411
+ ...validatePullRequestContent({
412
+ body: input.body,
413
+ base,
414
+ developBranch,
415
+ releaseBranch,
416
+ head,
417
+ template,
418
+ skipIssueReferenceCheck: input.noIssueRef,
419
+ screenshot: input.screenshot,
420
+ requiredSections,
421
+ stackedBase: use?.stackedBase,
422
+ }),
423
+ ...baseErrors,
424
+ ...titleScopeErrors({ config, owner: location.owner, repository: location.repository, title, base, head, directory, template, developBranch, releaseBranch, stacked }, out),
425
+ ];
426
+ exitOnValidationErrors(errors, out);
427
+ const isRelease = template === 'release';
428
+ const draft = { location, title, body: input.body, head, base, isDraft: input.isDraft, isRelease };
429
+ if (!input.dryRun) {
430
+ await submitPullRequest(config, client, directory, draft, use?.stackOn, out);
431
+ return;
432
+ }
433
+ out.planned(createOperation(draft));
434
+ const issueNumber = extractIssueNumberFromBranch(head);
435
+ if (!isRelease && issueNumber !== undefined)
436
+ out.planned(inReviewOperation(issueNumber));
437
+ if (use?.stackOn !== undefined)
438
+ out.planned({ verb: 'add', target: `the new PR to the stack of PR #${String(use.stackOn)}` });
439
+ }
440
+ function requireRepository(value, out) {
441
+ return splitOwnerRepository(value) ?? stopWith(out, `invalid repository format: ${value} (expected: owner/repo)`, 'invalid-input');
442
+ }
443
+ async function createFromFile(input, directory, out) {
444
+ const config = requireActiveConfigPlain(out);
445
+ let parsed;
446
+ try {
447
+ parsed = parsePullRequestFile(input.file);
448
+ }
449
+ catch (error) {
450
+ if (error instanceof FrontmatterError)
451
+ return stopWith(out, error.message, 'content-invalid');
452
+ throw error;
453
+ }
454
+ const { frontmatter } = parsed;
455
+ if (frontmatter.repository === '' || !frontmatter.repository.includes('/'))
456
+ return stopWith(out, 'repository is required (e.g. owner/repo)', 'content-invalid');
457
+ const location = requireRepository(frontmatter.repository, out);
458
+ const head = resolveHeadBranch(frontmatter.head, directory, out);
459
+ const reading = readBaseRecordFor(head, input.template, directory, out);
460
+ let body = parsed.body;
461
+ const issueNumber = extractIssueNumberFromBranch(head);
462
+ if (input.template !== 'release' && !input.noIssueRef && isPositive(issueNumber)) {
463
+ body = await appendCloseUnlessEpic(config, location, body, issueNumber, out);
464
+ }
465
+ await validateAndSubmit({
466
+ config,
467
+ directory,
468
+ template: input.template,
469
+ noIssueRef: input.noIssueRef,
470
+ dryRun: input.dryRun,
471
+ location,
472
+ title: frontmatter.title,
473
+ base: frontmatter.base,
474
+ head,
475
+ isDraft: frontmatter.draft,
476
+ body,
477
+ screenshot: frontmatter.screenshot,
478
+ reading,
479
+ }, out);
480
+ }
481
+ async function createDirect(input, directory, out) {
482
+ const config = requireActiveConfigPlain(out);
483
+ let location;
484
+ if (input.repository === undefined || input.repository === '') {
485
+ const [only] = config.repositories;
486
+ if (only === undefined || config.repositories.length !== 1)
487
+ return stopWith(out, hinted `specify the repository (${inputHint(PR_CREATE_PATH, 'repo', placeholder('owner/repo'))})`, 'invalid-input');
488
+ location = { owner: only.owner, repository: only.name };
489
+ }
490
+ else {
491
+ location = requireRepository(input.repository, out);
492
+ }
493
+ const head = resolveHeadBranch(input.head, directory, out);
494
+ const reading = readBaseRecordFor(head, input.template, directory, out);
495
+ let body = input.message;
496
+ const issueNumber = extractIssueNumberFromBranch(head);
497
+ if (input.template !== 'release' && !input.noIssueRef && isPositive(issueNumber)) {
498
+ body = appendIssueCloseIfNeeded(body, issueNumber);
499
+ }
500
+ await validateAndSubmit({
501
+ config,
502
+ directory,
503
+ template: input.template,
504
+ noIssueRef: input.noIssueRef,
505
+ dryRun: input.dryRun,
506
+ location,
507
+ title: input.title,
508
+ base: input.base,
509
+ head,
510
+ isDraft: input.isDraft,
511
+ body,
512
+ screenshot: input.screenshot,
513
+ reading,
514
+ }, out);
515
+ }
516
+ // --prepare
517
+ function addScopeHint(content, config, location, base, directory, stacked, out) {
518
+ const target = nxScopeTarget(config, location.owner, location.repository, base, directory, stacked);
519
+ if (target === undefined)
520
+ return content;
521
+ const head = gitCurrentBranch(directory);
522
+ const expected = head === undefined || head === '' ? undefined : expectedTitleScope(target, head, out);
523
+ if (expected === undefined || expected.length === 0)
524
+ return content;
525
+ const scope = expected.join(',');
526
+ // コメントは閉じの引用符の後ろに置き、YAML の title を "" のままにする
527
+ const hinted = content.replace(/^(title:\s*"[^"]*")/mu, (_matched, title) => `${title} # expected scope: ${scope}`);
528
+ out.done({ verb: 'set', target: `title scope hint to ${scope}` });
529
+ return hinted;
530
+ }
531
+ async function fillClosesInTemplate(content, config, directory, location, out) {
532
+ let target;
533
+ const segments = readFlag(FLAG_PECOT_ACTIVE)?.split('/');
534
+ if (segments?.length === 3) {
535
+ const [activeOwner, activeRepository, digits] = segments;
536
+ const activeNumber = digits !== undefined && /^\p{Nd}+$/u.test(digits) ? parsePythonInteger(digits) : undefined;
537
+ if (activeOwner !== undefined && activeRepository !== undefined && activeNumber !== undefined)
538
+ target = { owner: activeOwner, repository: activeRepository, number: activeNumber };
539
+ }
540
+ if (target === undefined && location !== undefined) {
541
+ const branch = gitCurrentBranch(directory);
542
+ const branchNumber = branch === undefined || branch === '' ? undefined : extractIssueNumberFromBranch(branch);
543
+ if (isPositive(branchNumber))
544
+ target = { owner: location.owner, repository: location.repository, number: branchNumber };
545
+ }
546
+ if (target === undefined || target.owner === '' || target.repository === '')
547
+ return content;
548
+ const label = `Issue #${String(target.number)}`;
549
+ try {
550
+ const kind = await createGitHubClient(out, config?.host).getIssueKind(target.owner, target.repository, target.number);
551
+ if (isEpicIssue(kind)) {
552
+ out.warning(`${label} is an Epic; Closes left empty`);
553
+ return content;
554
+ }
555
+ }
556
+ catch (error) {
557
+ if (error instanceof GitHubAPIError) {
558
+ out.warning(`kind check of ${label} failed: ${error.message}; fill Closes by hand`);
559
+ return content;
560
+ }
561
+ throw error;
562
+ }
563
+ const pattern = /^Closes #\s*$/mu;
564
+ if (!pattern.test(content))
565
+ return content;
566
+ out.done({ verb: 'set', target: `Closes to #${String(target.number)}` });
567
+ return content.replace(pattern, () => `Closes #${String(target.number)}`);
568
+ }
569
+ async function prepareTemplate(directory, out, template) {
570
+ const templatePath = templateFile('pr', templateKindOf(template));
571
+ if (!existsSync(templatePath))
572
+ stopWith(out, `template not found: ${templatePath}`, 'other');
573
+ let content = readTextFile(templatePath);
574
+ // release テンプレートは、base をテンプレートの既定(main)のままにする
575
+ if (template !== 'release') {
576
+ // 下の段の PR がマージ済みかは、準備と投稿の間に変わりうるので、ここでは読まずに投稿のときに見る
577
+ const reading = readBaseRecord();
578
+ stopOnMalformedRecord(reading, out);
579
+ const record = reading.kind === 'stacked' ? reading.record : undefined;
580
+ const location = primaryRemote(directory)?.location;
581
+ const config = loadActiveConfig();
582
+ if (location !== undefined) {
583
+ const developBranch = config === undefined ? undefined : getDevelopBranch(config, location.owner, location.repository);
584
+ if (config !== undefined && developBranch !== undefined && developBranch !== '') {
585
+ const base = record?.branch ?? developBranch;
586
+ content = content.replace(/^base:\s*"[^"]*"/mu, () => `base: "${base}"`);
587
+ out.done({ verb: 'set', target: `base to ${base}` });
588
+ content = addScopeHint(content, config, { owner: location.owner, repository: location.repository }, base, directory, record === undefined ? undefined : { sha: record.sha }, out);
589
+ }
590
+ }
591
+ content = await fillClosesInTemplate(content, config, directory, location, out);
592
+ }
593
+ const prefix = template === 'release' ? 'pr-release' : 'pr-create';
594
+ try {
595
+ withReservedOutputPath(outputDirectory(), timestamp => `${prefix}-${timestamp}.md`, (reserved) => {
596
+ writeFileSync(reserved, content, 'utf8');
597
+ out.data(reserved);
598
+ });
599
+ }
600
+ catch (error) {
601
+ if (error instanceof OutputPathReservationError)
602
+ return stopWith(out, error.message, 'other');
603
+ throw error;
604
+ }
605
+ }
606
+ const CreateInputSchema = z.strictObject({
607
+ file: z.string().optional().describe('Path to a Markdown file with front matter'),
608
+ message: z.string().optional().describe('PR body, given directly'),
609
+ title: z.string().optional().describe('PR title (required with -m)'),
610
+ base: z.string().optional().describe('Base branch (required with -m)'),
611
+ head: z.string().optional().describe('Head branch (default: the current branch)'),
612
+ draft: z.boolean().default(false).describe('Create as a draft PR'),
613
+ prepare: z.boolean().default(false).describe('Copy the template to the work directory'),
614
+ dry_run: z.boolean().default(false).describe('Validate only (skip the early preflight check, do not create the PR)'),
615
+ repo: z.string().optional().describe('Repository in owner/repo form (with -m)'),
616
+ no_issue_ref: z.boolean().default(false).describe('Skip the automatic related-Issue setup (extraction from the branch name, adding it to the body, and the validation check)'),
617
+ template: z.string().default('default').describe('PR template kind (default / release)'),
618
+ screenshot: z.string().optional().describe('Reason to omit an image from Summary (with -m)'),
619
+ });
620
+ async function runCreate(input, io) {
621
+ const directory = process.cwd();
622
+ const out = createOutput(input.dry_run, io);
623
+ if (input.template !== 'default' && input.template !== 'release')
624
+ stopWith(out, hinted `${inputNameHint(PR_CREATE_PATH, 'template')} must be 'default' or 'release' (given: ${input.template})`, 'invalid-input');
625
+ if (input.prepare) {
626
+ await prepareTemplate(directory, createOutput(false, io), input.template);
627
+ }
628
+ else if (input.file !== undefined) {
629
+ if (input.screenshot !== undefined)
630
+ 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');
631
+ await createFromFile({ file: input.file, template: input.template, noIssueRef: input.no_issue_ref, dryRun: input.dry_run }, directory, out);
632
+ }
633
+ else if (input.message === undefined) {
634
+ 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');
635
+ }
636
+ else {
637
+ if (input.title === undefined || input.title === '' || input.base === undefined || input.base === '')
638
+ 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');
639
+ await createDirect({
640
+ message: input.message,
641
+ title: input.title,
642
+ base: input.base,
643
+ head: input.head,
644
+ isDraft: input.draft,
645
+ dryRun: input.dry_run,
646
+ repository: input.repo,
647
+ noIssueRef: input.no_issue_ref,
648
+ template: input.template,
649
+ screenshot: pythonStrip(input.screenshot ?? '') || undefined,
650
+ }, directory, out);
651
+ }
652
+ }
653
+ // pr show
654
+ // グローバルの --repo か、いまの git の repository。決められなければ undefined
655
+ function resolveBaseRepository(globalRepository) {
656
+ try {
657
+ return resolveRepository(globalRepository, gitRunnerFor(process.cwd())).repository;
658
+ }
659
+ catch (error) {
660
+ if (error instanceof AmbiguousRepositoryError)
661
+ return undefined;
662
+ throw error;
663
+ }
664
+ }
665
+ export function parseReference(reference, globalRepository, out) {
666
+ try {
667
+ const parsed = parsePullRequestReference(reference, resolveBaseRepository(globalRepository), { repositoryFlag: true });
668
+ return { owner: parsed.repository.owner, repository: parsed.repository.repository, number: parsed.number };
669
+ }
670
+ catch (error) {
671
+ if (error instanceof ReferenceParseError)
672
+ return stopWith(out, error.hintedText ?? error.message, 'invalid-input', USAGE_EXIT_CODE);
673
+ throw error;
674
+ }
675
+ }
676
+ const ShowInputSchema = z.strictObject({
677
+ pr_ref: z.string().describe(PR_REFERENCE_DESCRIPTION),
678
+ json: z.boolean().default(false).describe('Output as JSON'),
679
+ reviews: z.boolean().default(false).describe('Include review details (bodies and line comments)'),
680
+ });
681
+ async function runShow(input, io) {
682
+ const out = createOutput(false, io);
683
+ const config = requireActiveConfigPlain(out);
684
+ const { owner, repository, number } = parseReference(input.pr_ref, input.repo, out);
685
+ try {
686
+ const client = createGitHubClient(out, config.host);
687
+ if (input.reviews) {
688
+ const pr = await client.getPullRequestWithReviews(owner, repository, number);
689
+ out.data(`${input.json ? JSON.stringify(pr, undefined, 2) : formatPullRequestWithReviewsMarkdown(pr, owner, repository)}\n`);
690
+ }
691
+ else {
692
+ const pr = await client.getPullRequestSlim(owner, repository, number);
693
+ out.data(`${input.json ? JSON.stringify(pr, undefined, 2) : formatPullRequestMarkdown(pr)}\n`);
694
+ }
695
+ }
696
+ catch (error) {
697
+ if (error instanceof GitHubAPIError)
698
+ return stopWith(out, error.message, kindOfFailure(error));
699
+ throw error;
700
+ }
701
+ }
702
+ // pr check
703
+ function hasBranch(branch, cwd) {
704
+ return runGit(['rev-parse', '--verify', branch], { cwd }).exitCode === 0;
705
+ }
706
+ // pr check の ls-remote は、認証の入力を待たずに、この時間で諦める
707
+ const LS_REMOTE_TIMEOUT_MILLISECONDS = 10_000;
708
+ // 端末で尋ねさせない。ssh は GIT_SSH_COMMAND で BatchMode にすると利用者の GIT_SSH と core.sshCommand を上書きするので、askpass を失敗させる
709
+ const NON_INTERACTIVE_GIT = { GIT_TERMINAL_PROMPT: '0', SSH_ASKPASS: 'false', SSH_ASKPASS_REQUIRE: 'force' };
710
+ // 下の段のブランチがマージで消えた後は、開発ブランチと比べる。追跡参照は fetch --prune まで残るので、
711
+ // remote に尋ね、無い(終了コード 2)ときだけ消えたとみなす。届かないか時間切れなら追跡参照で決める
712
+ function isOnRemote(branch, cwd, remote, out) {
713
+ const listed = runGit(['ls-remote', '--exit-code', remote, `refs/heads/${branch}`], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: LS_REMOTE_TIMEOUT_MILLISECONDS });
714
+ if (listed.exitCode === LS_REMOTE_NOT_FOUND)
715
+ return false;
716
+ const isTracked = hasBranch(`${remote}/${branch}`, cwd);
717
+ if (!isTracked && listed.exitCode === 0)
718
+ out.warning(`base branch ${branch} is on ${remote}, but ${remote}/${branch} is not fetched; compared with the develop branch\nrun: git fetch ${remote} ${branch}`);
719
+ return isTracked;
720
+ }
721
+ function determineBaseBranch(location, cwd, remote, out) {
722
+ const config = loadActiveConfig();
723
+ if (config === undefined)
724
+ return stopWith(out, hinted `project config not found\nactivate a project with: ${commandHint(['project', 'activate'], { project: placeholder('PROJECT') })}`, 'no-active-project');
725
+ const reading = readBaseRecord();
726
+ stopOnMalformedRecord(reading, out);
727
+ if (reading.kind === 'stacked' && isOnRemote(reading.record.branch, cwd, remote, out))
728
+ return `${remote}/${reading.record.branch}`;
729
+ const developBranch = getDevelopBranch(config, location.owner, location.repository);
730
+ if (developBranch === undefined || developBranch === '') {
731
+ 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');
732
+ }
733
+ const branchName = `${remote}/${developBranch}`;
734
+ return hasBranch(branchName, cwd) ? branchName : stopWith(out, `branch ${branchName} does not exist\ncheck the remote branches with: git branch -r`, 'git-unresolved');
735
+ }
736
+ function readGitignore(cwd) {
737
+ const root = gitToplevel({ cwd });
738
+ if (root === undefined)
739
+ return '(not a git repository)';
740
+ const file = path.join(root, '.gitignore');
741
+ if (!existsSync(file))
742
+ return '(no .gitignore)';
743
+ try {
744
+ return readTextFile(file);
745
+ }
746
+ catch {
747
+ return '(read error)';
748
+ }
749
+ }
750
+ function readGitExclude(cwd) {
751
+ try {
752
+ const common = gitStdout(['rev-parse', '--git-common-dir'], { cwd });
753
+ if (common === undefined)
754
+ return '(read error)';
755
+ const file = path.join(path.resolve(cwd, pythonStrip(common)), 'info', 'exclude');
756
+ return existsSync(file) ? readTextFile(file) : '(no exclude)';
757
+ }
758
+ catch {
759
+ return '(read error)';
760
+ }
761
+ }
762
+ function getWorktreeInfo(cwd) {
763
+ const listed = gitStdout(['worktree', 'list'], { cwd });
764
+ const lines = [listed === undefined ? '(git worktree list failed)' : pythonStrip(listed), '', `Current directory name: ${path.basename(cwd)}`];
765
+ const gitDirectory = gitStdout(['rev-parse', '--git-dir'], { cwd });
766
+ const commonDirectory = gitDirectory === undefined ? undefined : gitStdout(['rev-parse', '--git-common-dir'], { cwd });
767
+ if (gitDirectory === undefined || commonDirectory === undefined) {
768
+ lines.push('Is worktree environment: (unknown)');
769
+ }
770
+ else {
771
+ const isWorktree = resolveRealPath(path.resolve(cwd, pythonStrip(gitDirectory))) !== resolveRealPath(path.resolve(cwd, pythonStrip(commonDirectory)));
772
+ lines.push(`Is worktree environment: ${isWorktree ? 'true' : 'false'}`);
773
+ }
774
+ return lines.join('\n');
775
+ }
776
+ const CheckInputSchema = z.strictObject({
777
+ directory: directorySchema,
778
+ });
779
+ function runCheck(input, io) {
780
+ const out = createOutput(false, io);
781
+ const directory = input.directory;
782
+ const context = validatePullRequestContext(directory, out);
783
+ const baseBranch = determineBaseBranch(context.location, directory, context.remoteName, out);
784
+ const gitStatus = getGitStatus(directory);
785
+ const commits = gitStdout(['log', '--oneline', `${baseBranch}..HEAD`], { cwd: directory });
786
+ const diffSummary = gitStdout(['diff', '--stat', `${baseBranch}...HEAD`], { cwd: directory });
787
+ const push = getPushStatus(context.currentBranch, directory, context.remoteName);
788
+ const stashList = getStashList(directory);
789
+ const sections = [
790
+ ['=== Git Remote ===', context.remoteUrl],
791
+ ['=== Current Branch ===', context.currentBranch],
792
+ ['=== Push Status ===', push.message],
793
+ ['=== Base Branch ===', baseBranch],
794
+ ['=== Git Status ===', gitStatus],
795
+ ['=== .gitignore ===', readGitignore(directory)],
796
+ ['=== Git Exclude ===', readGitExclude(directory)],
797
+ [`=== Commits (vs ${baseBranch}) ===`, commits === undefined ? '(git log failed)' : pythonStrip(commits) || '(no commits)'],
798
+ [`=== Diff Summary (vs ${baseBranch}) ===`, diffSummary === undefined ? '(git diff failed)' : pythonStrip(diffSummary) || '(no diff)'],
799
+ ['=== Worktree Info ===', getWorktreeInfo(directory)],
800
+ ['=== Stash List ===', stashList],
801
+ ];
802
+ for (const [index, [heading, content]] of sections.entries()) {
803
+ if (index > 0)
804
+ out.data('\n');
805
+ out.data(`${heading}\n`);
806
+ out.data(`${content}\n`);
807
+ }
808
+ const warnings = collectPreflightWarnings({ gitStatus, stashList, isPushed: push.isPushed, pushMessage: push.message });
809
+ out.count('preflight warnings', warnings.length);
810
+ printPreflightWarnings(out, warnings);
811
+ if (warnings.length > 0)
812
+ throw new CommandExit(PREFLIGHT_EXIT_CODE, 'preflight-failed');
813
+ }
814
+ const prCreate = defineCommand({
815
+ path: PR_CREATE_PATH,
816
+ description: 'Create a PR (pull request)',
817
+ input: CreateInputSchema,
818
+ positional: ['file'],
819
+ shortFlags: { message: '-m', title: '-t', base: '-b', draft: '-d', prepare: '-p', dry_run: '-n', repo: '-r' },
820
+ hasOwnRepo: true,
821
+ interactive: false,
822
+ run: async (input, io) => {
823
+ await runCreate(input, io);
824
+ return 0;
825
+ },
826
+ });
827
+ const prShow = defineCommand({
828
+ path: ['pr', 'show'],
829
+ description: 'Get PR details efficiently (GraphQL, only the needed fields)',
830
+ input: ShowInputSchema,
831
+ positional: ['pr_ref'],
832
+ shortFlags: { json: '-j', reviews: '-r' },
833
+ interactive: false,
834
+ run: async (input, io) => {
835
+ await runShow(input, io);
836
+ return 0;
837
+ },
838
+ });
839
+ const prCheck = defineCommand({
840
+ path: ['pr', 'check'],
841
+ description: 'Show all the information to check before creating a PR',
842
+ input: CheckInputSchema,
843
+ positional: [],
844
+ shortFlags: { directory: '-D' },
845
+ interactive: false,
846
+ run: (input, io) => {
847
+ runCheck(input, io);
848
+ return Promise.resolve(0);
849
+ },
850
+ });
851
+ export const PR_COMMANDS = [prCreate, prShow, prCheck];
852
+ //# sourceMappingURL=pr.js.map