@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.
- package/.claude-plugin/plugin.json +8 -0
- package/LICENSE +21 -0
- package/README.md +184 -2
- package/bin/pecot-workflow-mcp.mjs +10 -0
- package/cli/dist/cli.d.ts +26 -0
- package/cli/dist/cli.js +227 -0
- package/cli/dist/commands/board-add.d.ts +3 -0
- package/cli/dist/commands/board-add.js +59 -0
- package/cli/dist/commands/board-judgment.d.ts +60 -0
- package/cli/dist/commands/board-judgment.js +144 -0
- package/cli/dist/commands/board-move.d.ts +3 -0
- package/cli/dist/commands/board-move.js +57 -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 +72 -0
- package/cli/dist/commands/board-sync.d.ts +3 -0
- package/cli/dist/commands/board-sync.js +111 -0
- package/cli/dist/commands/board-view.d.ts +62 -0
- package/cli/dist/commands/board-view.js +191 -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 +100 -0
- package/cli/dist/commands/cell-table.d.ts +3 -0
- package/cli/dist/commands/cell-table.js +495 -0
- package/cli/dist/commands/command-binding.d.ts +26 -0
- package/cli/dist/commands/command-binding.js +270 -0
- package/cli/dist/commands/command-definition.d.ts +150 -0
- package/cli/dist/commands/command-definition.js +105 -0
- package/cli/dist/commands/command-help.d.ts +8 -0
- package/cli/dist/commands/command-help.js +173 -0
- 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 +21 -0
- package/cli/dist/commands/command-stop.js +31 -0
- package/cli/dist/commands/directory-option.d.ts +7 -0
- package/cli/dist/commands/directory-option.js +48 -0
- package/cli/dist/commands/failure-kind.d.ts +3 -0
- package/cli/dist/commands/failure-kind.js +34 -0
- package/cli/dist/commands/failure.d.ts +19 -0
- package/cli/dist/commands/failure.js +59 -0
- package/cli/dist/commands/fuzzy.d.ts +7 -0
- package/cli/dist/commands/fuzzy.js +79 -0
- package/cli/dist/commands/github-client.d.ts +16 -0
- package/cli/dist/commands/github-client.js +33 -0
- package/cli/dist/commands/global-options.d.ts +25 -0
- package/cli/dist/commands/global-options.js +83 -0
- package/cli/dist/commands/help-layout.d.ts +40 -0
- package/cli/dist/commands/help-layout.js +117 -0
- package/cli/dist/commands/help.d.ts +8 -0
- package/cli/dist/commands/help.js +50 -0
- package/cli/dist/commands/input-schema.d.ts +14 -0
- package/cli/dist/commands/input-schema.js +56 -0
- package/cli/dist/commands/issue-board.d.ts +71 -0
- package/cli/dist/commands/issue-board.js +122 -0
- package/cli/dist/commands/issue-comment.d.ts +3 -0
- package/cli/dist/commands/issue-comment.js +215 -0
- package/cli/dist/commands/issue-create.d.ts +3 -0
- package/cli/dist/commands/issue-create.js +786 -0
- package/cli/dist/commands/issue-dependency.d.ts +3 -0
- package/cli/dist/commands/issue-dependency.js +282 -0
- package/cli/dist/commands/issue-readiness.d.ts +94 -0
- package/cli/dist/commands/issue-readiness.js +218 -0
- package/cli/dist/commands/issue-reopen.d.ts +3 -0
- package/cli/dist/commands/issue-reopen.js +115 -0
- package/cli/dist/commands/issue-shared.d.ts +172 -0
- package/cli/dist/commands/issue-shared.js +426 -0
- package/cli/dist/commands/issue-show.d.ts +3 -0
- package/cli/dist/commands/issue-show.js +169 -0
- package/cli/dist/commands/issue.d.ts +3 -0
- package/cli/dist/commands/issue.js +13 -0
- package/cli/dist/commands/names.d.ts +42 -0
- package/cli/dist/commands/names.js +78 -0
- package/cli/dist/commands/output.d.ts +90 -0
- package/cli/dist/commands/output.js +194 -0
- package/cli/dist/commands/pr-waiting.d.ts +20 -0
- package/cli/dist/commands/pr-waiting.js +106 -0
- package/cli/dist/commands/pr.d.ts +22 -0
- package/cli/dist/commands/pr.js +852 -0
- package/cli/dist/commands/project-sync.d.ts +92 -0
- package/cli/dist/commands/project-sync.js +282 -0
- package/cli/dist/commands/project.d.ts +6 -0
- package/cli/dist/commands/project.js +714 -0
- package/cli/dist/commands/registry.d.ts +6 -0
- package/cli/dist/commands/registry.js +30 -0
- package/cli/dist/commands/release.d.ts +10 -0
- package/cli/dist/commands/release.js +353 -0
- package/cli/dist/commands/renamed-commands.d.ts +26 -0
- package/cli/dist/commands/renamed-commands.js +53 -0
- package/cli/dist/commands/repository-display.d.ts +3 -0
- package/cli/dist/commands/repository-display.js +7 -0
- package/cli/dist/commands/repository-match.d.ts +14 -0
- package/cli/dist/commands/repository-match.js +34 -0
- package/cli/dist/commands/rich-panel.d.ts +22 -0
- package/cli/dist/commands/rich-panel.js +295 -0
- package/cli/dist/commands/session-finish.d.ts +3 -0
- package/cli/dist/commands/session-finish.js +267 -0
- package/cli/dist/commands/session-start.d.ts +3 -0
- package/cli/dist/commands/session-start.js +236 -0
- package/cli/dist/commands/session.d.ts +6 -0
- package/cli/dist/commands/session.js +214 -0
- package/cli/dist/commands/tracker-sync-dependabot.d.ts +7 -0
- package/cli/dist/commands/tracker-sync-dependabot.js +156 -0
- package/cli/dist/commands/tracker-sync-security.d.ts +7 -0
- package/cli/dist/commands/tracker-sync-security.js +153 -0
- package/cli/dist/commands/tracker-sync.d.ts +65 -0
- package/cli/dist/commands/tracker-sync.js +50 -0
- package/cli/dist/commands/tracker.d.ts +3 -0
- package/cli/dist/commands/tracker.js +18 -0
- package/cli/dist/commands/usage-error.d.ts +51 -0
- package/cli/dist/commands/usage-error.js +78 -0
- package/cli/dist/commands/value-types.d.ts +46 -0
- package/cli/dist/commands/value-types.js +94 -0
- package/cli/dist/commands/work-target.d.ts +22 -0
- package/cli/dist/commands/work-target.js +82 -0
- package/cli/dist/commands/worktree.d.ts +3 -0
- package/cli/dist/commands/worktree.js +339 -0
- package/cli/dist/domain/api-error-detail.d.ts +10 -0
- package/cli/dist/domain/api-error-detail.js +25 -0
- 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.d.ts +5 -0
- package/cli/dist/domain/branch-name.js +10 -0
- package/cli/dist/domain/changelog.d.ts +43 -0
- package/cli/dist/domain/changelog.js +107 -0
- 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 +219 -0
- package/cli/dist/domain/config.js +310 -0
- package/cli/dist/domain/dependabot-pull-requests.d.ts +82 -0
- package/cli/dist/domain/dependabot-pull-requests.js +338 -0
- package/cli/dist/domain/dependabot-source.d.ts +51 -0
- package/cli/dist/domain/dependabot-source.js +4 -0
- package/cli/dist/domain/dependabot.d.ts +47 -0
- package/cli/dist/domain/dependabot.js +88 -0
- package/cli/dist/domain/errors.d.ts +24 -0
- package/cli/dist/domain/errors.js +36 -0
- package/cli/dist/domain/field-options.d.ts +31 -0
- package/cli/dist/domain/field-options.js +44 -0
- package/cli/dist/domain/format.d.ts +94 -0
- package/cli/dist/domain/format.js +234 -0
- package/cli/dist/domain/frontmatter.d.ts +137 -0
- package/cli/dist/domain/frontmatter.js +290 -0
- package/cli/dist/domain/git-runner.d.ts +10 -0
- package/cli/dist/domain/git-runner.js +4 -0
- package/cli/dist/domain/git-url.d.ts +17 -0
- package/cli/dist/domain/git-url.js +30 -0
- package/cli/dist/domain/issue-kind.d.ts +16 -0
- package/cli/dist/domain/issue-kind.js +16 -0
- 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 +143 -0
- package/cli/dist/domain/issue-readout.js +4 -0
- package/cli/dist/domain/json-null.d.ts +2 -0
- package/cli/dist/domain/json-null.js +5 -0
- package/cli/dist/domain/json.d.ts +21 -0
- package/cli/dist/domain/json.js +47 -0
- package/cli/dist/domain/prerequisites.d.ts +32 -0
- package/cli/dist/domain/prerequisites.js +192 -0
- package/cli/dist/domain/pull-request.d.ts +201 -0
- package/cli/dist/domain/pull-request.js +281 -0
- package/cli/dist/domain/python-format.d.ts +105 -0
- package/cli/dist/domain/python-format.js +304 -0
- package/cli/dist/domain/readiness.d.ts +199 -0
- package/cli/dist/domain/readiness.js +391 -0
- package/cli/dist/domain/reference-parser.d.ts +51 -0
- package/cli/dist/domain/reference-parser.js +123 -0
- package/cli/dist/domain/release.d.ts +53 -0
- package/cli/dist/domain/release.js +65 -0
- package/cli/dist/domain/repository-policy.d.ts +38 -0
- package/cli/dist/domain/repository-policy.js +66 -0
- package/cli/dist/domain/repository-resolver.d.ts +57 -0
- package/cli/dist/domain/repository-resolver.js +122 -0
- package/cli/dist/domain/sections.d.ts +69 -0
- package/cli/dist/domain/sections.js +514 -0
- package/cli/dist/domain/security-alerts-source.d.ts +29 -0
- package/cli/dist/domain/security-alerts-source.js +4 -0
- package/cli/dist/domain/security-alerts.d.ts +52 -0
- package/cli/dist/domain/security-alerts.js +107 -0
- package/cli/dist/domain/security-tracker.d.ts +115 -0
- package/cli/dist/domain/security-tracker.js +353 -0
- package/cli/dist/domain/state.d.ts +59 -0
- package/cli/dist/domain/state.js +95 -0
- package/cli/dist/domain/tracker-body.d.ts +70 -0
- package/cli/dist/domain/tracker-body.js +65 -0
- package/cli/dist/domain/work-start.d.ts +34 -0
- package/cli/dist/domain/work-start.js +49 -0
- package/cli/dist/domain/yaml-document.d.ts +5 -0
- package/cli/dist/domain/yaml-document.js +206 -0
- package/cli/dist/infra/authored-notes.d.ts +37 -0
- package/cli/dist/infra/authored-notes.js +72 -0
- package/cli/dist/infra/changelog-file.d.ts +19 -0
- package/cli/dist/infra/changelog-file.js +43 -0
- package/cli/dist/infra/child-stdin.d.ts +4 -0
- package/cli/dist/infra/child-stdin.js +8 -0
- package/cli/dist/infra/config-store.d.ts +53 -0
- package/cli/dist/infra/config-store.js +134 -0
- package/cli/dist/infra/diagnostics.d.ts +9 -0
- package/cli/dist/infra/diagnostics.js +2 -0
- package/cli/dist/infra/file-kind.d.ts +9 -0
- package/cli/dist/infra/file-kind.js +26 -0
- package/cli/dist/infra/frontmatter-file.d.ts +14 -0
- package/cli/dist/infra/frontmatter-file.js +30 -0
- package/cli/dist/infra/git.d.ts +86 -0
- package/cli/dist/infra/git.js +145 -0
- package/cli/dist/infra/github/auth.d.ts +60 -0
- package/cli/dist/infra/github/auth.js +158 -0
- package/cli/dist/infra/github/client.d.ts +178 -0
- package/cli/dist/infra/github/client.js +579 -0
- package/cli/dist/infra/github/dependabot-source.d.ts +13 -0
- package/cli/dist/infra/github/dependabot-source.js +33 -0
- package/cli/dist/infra/github/errors.d.ts +65 -0
- package/cli/dist/infra/github/errors.js +64 -0
- package/cli/dist/infra/github/index.d.ts +13 -0
- package/cli/dist/infra/github/index.js +19 -0
- package/cli/dist/infra/github/issues.d.ts +165 -0
- package/cli/dist/infra/github/issues.js +428 -0
- package/cli/dist/infra/github/payload.d.ts +44 -0
- package/cli/dist/infra/github/payload.js +80 -0
- package/cli/dist/infra/github/projects.d.ts +143 -0
- package/cli/dist/infra/github/projects.js +384 -0
- package/cli/dist/infra/github/pulls.d.ts +104 -0
- package/cli/dist/infra/github/pulls.js +217 -0
- package/cli/dist/infra/github/queries.d.ts +44 -0
- package/cli/dist/infra/github/queries.js +1031 -0
- package/cli/dist/infra/github/readout.d.ts +22 -0
- package/cli/dist/infra/github/readout.js +167 -0
- package/cli/dist/infra/github/repos.d.ts +86 -0
- package/cli/dist/infra/github/repos.js +168 -0
- package/cli/dist/infra/github/rest-path.d.ts +14 -0
- package/cli/dist/infra/github/rest-path.js +31 -0
- package/cli/dist/infra/github/security-alerts-source.d.ts +15 -0
- package/cli/dist/infra/github/security-alerts-source.js +73 -0
- package/cli/dist/infra/gitignore-spec.d.ts +36 -0
- package/cli/dist/infra/gitignore-spec.js +235 -0
- package/cli/dist/infra/nx-scope.d.ts +51 -0
- package/cli/dist/infra/nx-scope.js +182 -0
- package/cli/dist/infra/os-error.d.ts +24 -0
- package/cli/dist/infra/os-error.js +38 -0
- package/cli/dist/infra/paths.d.ts +88 -0
- package/cli/dist/infra/paths.js +234 -0
- package/cli/dist/infra/state-store.d.ts +54 -0
- package/cli/dist/infra/state-store.js +130 -0
- package/cli/dist/infra/template-store.d.ts +15 -0
- package/cli/dist/infra/template-store.js +34 -0
- package/cli/dist/infra/text-file.d.ts +12 -0
- package/cli/dist/infra/text-file.js +33 -0
- package/cli/dist/infra/worktree-copy.d.ts +24 -0
- package/cli/dist/infra/worktree-copy.js +95 -0
- package/cli/dist/infra/worktree-links.d.ts +142 -0
- package/cli/dist/infra/worktree-links.js +440 -0
- package/cli/dist/infra/worktree-setup.d.ts +21 -0
- package/cli/dist/infra/worktree-setup.js +41 -0
- package/cli/dist/infra/worktree.d.ts +185 -0
- package/cli/dist/infra/worktree.js +584 -0
- package/cli/dist/mcp/result.d.ts +61 -0
- package/cli/dist/mcp/result.js +96 -0
- package/cli/dist/mcp/serve.d.ts +51 -0
- package/cli/dist/mcp/serve.js +183 -0
- package/cli/dist/mcp/server.d.ts +21 -0
- package/cli/dist/mcp/server.js +142 -0
- package/cli/dist/mcp/session-directory.d.ts +26 -0
- package/cli/dist/mcp/session-directory.js +84 -0
- package/cli/dist/package.json +1 -0
- package/cli/dist/version.d.ts +17 -0
- package/cli/dist/version.js +42 -0
- package/cli/templates/comment/merge-diff.md +34 -0
- package/cli/templates/comment/plan.md +195 -0
- package/cli/templates/comment/precede-notify.md +33 -0
- package/cli/templates/comment/review-findings.md +42 -0
- package/cli/templates/comment/review-resolution.md +48 -0
- package/cli/templates/issue/bug.md +63 -0
- package/cli/templates/issue/epic.md +54 -0
- package/cli/templates/issue/task-implement.md +74 -0
- package/cli/templates/issue/task.md +48 -0
- package/cli/templates/issue/tracker.md +48 -0
- package/cli/templates/pr/create.md +123 -0
- package/cli/templates/pr/release.md +56 -0
- package/cli/templates/workflow/pecot-board-sync.yml +84 -0
- package/hooks/lib/core/pecot-gitignore-ensure.sh +48 -0
- package/npm-shrinkwrap.json +83 -0
- package/package.json +22 -4
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
/* eslint-disable security/detect-non-literal-fs-filename -- パスは呼び出し側が渡すリポジトリ・プロジェクトルート配下 */
|
|
2
|
+
// ワークツリー管理のコアロジック。ワークツリーの作成・削除を提供する。
|
|
3
|
+
//
|
|
4
|
+
// 全ての関数は cwd 引数で対象リポジトリを指定する。
|
|
5
|
+
// pecot CLI は pecot リポジトリ内で実行されるが、worktree コマンドは別のリポジトリを対象にするため、cwd 引数が必須。
|
|
6
|
+
// 失敗は WorktreeRuntimeError(Python の RuntimeError に当たる)で伝える。
|
|
7
|
+
//
|
|
8
|
+
// 設定ファイル(worktree-config.json・.worktreeignore)の読み書きと symlink 作成は worktree-links.ts にある。
|
|
9
|
+
// ファイルのコピーは worktree-copy.ts、setup_command の実行は worktree-setup.ts にある。
|
|
10
|
+
// このファイルがそれらを読む。逆向きの import は作らない(findWorktreeConfigFile と findMainWorktree をここに置くのはそのため)。
|
|
11
|
+
import { BaseError } from '../domain/errors.js';
|
|
12
|
+
import { existsSync, readdirSync, readFileSync, rmdirSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { commandHint, formatHinted, hinted, inputHint, inputNameHint, placeholder } from '../domain/command-hint.js';
|
|
15
|
+
import { findRepository, getDevelopBranch } from '../domain/config.js';
|
|
16
|
+
import { pythonStrip, ValidationFailure } from '../domain/python-format.js';
|
|
17
|
+
import { createRepositoryReference } from '../domain/repository-resolver.js';
|
|
18
|
+
import { loadActiveConfig } from './config-store.js';
|
|
19
|
+
import { isDirectory } from './file-kind.js';
|
|
20
|
+
import { GitCommandError, gitToplevel, listRemotes, preferredRemotes, remoteRepository, runGit } from './git.js';
|
|
21
|
+
import { toOsError } from './os-error.js';
|
|
22
|
+
import { normalizePath, resolveRealPath, WORKTREE_CONFIG_FILENAME } from './paths.js';
|
|
23
|
+
import { createSymlinks, loadConfig, loadCopyExcludeSpec, WorktreeConfigError, } from './worktree-links.js';
|
|
24
|
+
import { copyFiles } from './worktree-copy.js';
|
|
25
|
+
import { runSetupCommand } from './worktree-setup.js';
|
|
26
|
+
const WORKTREE_ADD_PATH = ['worktree', 'add'];
|
|
27
|
+
/**
|
|
28
|
+
ワークツリー操作に失敗した(Python の RuntimeError に当たる)。メッセージは利用者に見せる文
|
|
29
|
+
*/
|
|
30
|
+
export class WorktreeRuntimeError extends BaseError {
|
|
31
|
+
hintedText;
|
|
32
|
+
failure;
|
|
33
|
+
// message は CLI の形。MCP では最上位が hintedText から描き直す
|
|
34
|
+
constructor(message, options = {}) {
|
|
35
|
+
super(formatHinted(message, 'cli'), options.cause === undefined ? undefined : { cause: options.cause });
|
|
36
|
+
this.hintedText = typeof message === 'string' ? undefined : message;
|
|
37
|
+
this.failure = options.failure ?? 'other';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
// 環境ガード
|
|
41
|
+
function isSet(value = '') {
|
|
42
|
+
return value !== '';
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
pecot worktree 系コマンドが devcontainer 内で実行されていることを確認する。
|
|
46
|
+
|
|
47
|
+
devcontainer 外(host 直接)での実行はサポート外。プロジェクトの devcontainer が整えるマウント構造
|
|
48
|
+
(/workspaces/<project>/base/<repo>)に依存するため、外で動かしても動作は保証しない。
|
|
49
|
+
|
|
50
|
+
検出方法(いずれかでヒットすれば通過)は次のとおり。
|
|
51
|
+
- `/.dockerenv` ファイルの存在。パスは dockerEnvironmentFile で差し替えられる。
|
|
52
|
+
- 環境変数 REMOTE_CONTAINERS・CODESPACES・DEVCONTAINER のいずれかが設定されている。
|
|
53
|
+
|
|
54
|
+
いずれも満たさなければ WorktreeRuntimeError
|
|
55
|
+
*/
|
|
56
|
+
export function ensureDevcontainerEnvironment(dockerEnvironmentFile = '/.dockerenv') {
|
|
57
|
+
if (existsSync(dockerEnvironmentFile) || isSet(process.env['REMOTE_CONTAINERS']) || isSet(process.env['CODESPACES']) || isSet(process.env['DEVCONTAINER']))
|
|
58
|
+
return;
|
|
59
|
+
throw new WorktreeRuntimeError('this command must run inside a devcontainer\n'
|
|
60
|
+
+ 'the current environment does not have the mount layout pecot expects '
|
|
61
|
+
+ '(/workspaces/<project>/base/<repo>)\n'
|
|
62
|
+
+ 'prepare .devcontainer/ in the project, run Reopen in Container in VS Code, and run it again');
|
|
63
|
+
}
|
|
64
|
+
// Git 操作関数
|
|
65
|
+
function outputLines(stdout) {
|
|
66
|
+
return pythonStrip(stdout).split('\n').filter(line => line !== '');
|
|
67
|
+
}
|
|
68
|
+
// `git worktree list --porcelain` を worktree ごとに分ける。パスの空白はそのまま残る
|
|
69
|
+
function parsePorcelain(stdout) {
|
|
70
|
+
const entries = [];
|
|
71
|
+
for (const line of outputLines(stdout)) {
|
|
72
|
+
if (line.startsWith('worktree '))
|
|
73
|
+
entries.push({ path: line.slice('worktree '.length), commit: '', branch: undefined });
|
|
74
|
+
const entry = entries.at(-1);
|
|
75
|
+
if (entry === undefined)
|
|
76
|
+
continue;
|
|
77
|
+
if (line.startsWith('HEAD '))
|
|
78
|
+
entry.commit = line.slice('HEAD '.length);
|
|
79
|
+
else if (line.startsWith('branch '))
|
|
80
|
+
entry.branch = line.slice('branch '.length).replace(/^refs\/heads\//u, '');
|
|
81
|
+
}
|
|
82
|
+
return entries;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
git worktree list --porcelain の結果を分ける。実行に失敗したら空
|
|
86
|
+
*/
|
|
87
|
+
export function getWorktreeList(cwd) {
|
|
88
|
+
const result = runGit(['worktree', 'list', '--porcelain'], { cwd });
|
|
89
|
+
return result.exitCode === 0 ? parsePorcelain(result.stdout) : [];
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
メインワークツリーのパスを取得する。git worktree list の最初のエントリがメイン WT。
|
|
93
|
+
任意の WT 内から呼べる。一覧を取得できなければ WorktreeRuntimeError
|
|
94
|
+
*/
|
|
95
|
+
export function findMainWorktree(cwd) {
|
|
96
|
+
const result = runGit(['worktree', 'list', '--porcelain'], { cwd });
|
|
97
|
+
const main = result.exitCode === 0 ? parsePorcelain(result.stdout)[0] : undefined;
|
|
98
|
+
if (main === undefined)
|
|
99
|
+
throw new WorktreeRuntimeError(`cannot get the worktree list: ${result.stderr}`);
|
|
100
|
+
return normalizePath(main.path);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
メインワークツリーの設定ファイルを探す。無ければ undefined
|
|
104
|
+
*/
|
|
105
|
+
export function findWorktreeConfigFile(cwd = process.cwd()) {
|
|
106
|
+
let mainWorktree;
|
|
107
|
+
try {
|
|
108
|
+
mainWorktree = findMainWorktree(cwd);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (error instanceof WorktreeRuntimeError)
|
|
112
|
+
return undefined;
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
const configPath = path.join(mainWorktree, WORKTREE_CONFIG_FILENAME);
|
|
116
|
+
return existsSync(configPath) ? configPath : undefined;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
サブワークツリー環境かどうかを判定する。git rev-parse --git-dir と --git-common-dir を比較し、
|
|
120
|
+
サブ WT では git-dir がメインの .git を指すため、両者が異なる。
|
|
121
|
+
Git リポジトリ外、または git コマンドの失敗なら WorktreeRuntimeError
|
|
122
|
+
*/
|
|
123
|
+
export function isWorktreeEnvironment(cwd) {
|
|
124
|
+
let gitDirectory;
|
|
125
|
+
let commonDirectory;
|
|
126
|
+
try {
|
|
127
|
+
gitDirectory = runGit(['rev-parse', '--git-dir'], { cwd, check: true }).stdout;
|
|
128
|
+
commonDirectory = runGit(['rev-parse', '--git-common-dir'], { cwd, check: true }).stdout;
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error instanceof GitCommandError)
|
|
132
|
+
throw new WorktreeRuntimeError(`not a git repository: ${error.stderr.trim()}`, { cause: error });
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
// 相対パスは、cwd ではなくこのプロセスの作業ディレクトリ基準で解決する(Python の Path.resolve() と同じ)
|
|
136
|
+
return resolveRealPath(pythonStrip(gitDirectory)) !== resolveRealPath(pythonStrip(commonDirectory));
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
サブワークツリーのパス一覧を取得する。get_worktree_list の最初のエントリ(メイン WT)を除く。
|
|
140
|
+
一覧を取得できなければ WorktreeRuntimeError
|
|
141
|
+
*/
|
|
142
|
+
export function getWorktreeDirectories(cwd) {
|
|
143
|
+
const entries = getWorktreeList(cwd);
|
|
144
|
+
if (entries.length === 0)
|
|
145
|
+
throw new WorktreeRuntimeError('cannot get the worktree list');
|
|
146
|
+
return entries.slice(1).map(entry => normalizePath(entry.path));
|
|
147
|
+
}
|
|
148
|
+
// worktree add が wtN を書く記録。管理ディレクトリ(.git/worktrees/<id>/)の中に置く
|
|
149
|
+
const WORKTREE_NAME_RECORD = 'pecot-worktree-name';
|
|
150
|
+
// 記録のパス。git が解決した絶対パス(このプロセスの cwd に依らない)。取れなければ undefined
|
|
151
|
+
function worktreeNameRecordPath(cwd) {
|
|
152
|
+
const result = runGit(['rev-parse', '--path-format=absolute', '--git-path', WORKTREE_NAME_RECORD], { cwd });
|
|
153
|
+
const recordPath = pythonStrip(result.stdout);
|
|
154
|
+
return recordPath !== '' && result.exitCode === 0 ? recordPath : undefined;
|
|
155
|
+
}
|
|
156
|
+
function readRecord(file) {
|
|
157
|
+
try {
|
|
158
|
+
return pythonStrip(readFileSync(file, 'utf8'));
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
return '';
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// 作った worktree に名前を記録する。失敗は warning にとどめる
|
|
165
|
+
function recordWorktreeName(worktreePath, name, diagnostics) {
|
|
166
|
+
const recordPath = worktreeNameRecordPath(worktreePath);
|
|
167
|
+
if (recordPath === undefined) {
|
|
168
|
+
diagnostics.warning(`failed to record the worktree name ${name}: cannot resolve the git path: ${worktreePath}`);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
writeFileSync(recordPath, `${name}\n`);
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
const converted = toOsError(error);
|
|
176
|
+
diagnostics.warning(`failed to record the worktree name ${name}: ${recordPath}: ${converted instanceof Error ? converted.message : String(converted)}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
使用中の wtN の名前を返す。全 worktree の記録と、wtN のブランチを checkout している worktree の和
|
|
181
|
+
*/
|
|
182
|
+
export function claimedSetNames(mainWorktree) {
|
|
183
|
+
const names = new Set();
|
|
184
|
+
const common = runGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: mainWorktree });
|
|
185
|
+
const commonDirectory = pythonStrip(common.stdout);
|
|
186
|
+
if (commonDirectory !== '' && common.exitCode === 0) {
|
|
187
|
+
const administrative = path.join(commonDirectory, 'worktrees');
|
|
188
|
+
const entries = existsSync(administrative) ? readdirSync(administrative) : [];
|
|
189
|
+
for (const entry of entries) {
|
|
190
|
+
const recorded = readRecord(path.join(administrative, entry, WORKTREE_NAME_RECORD));
|
|
191
|
+
if (recorded !== '')
|
|
192
|
+
names.add(recorded);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const references = runGit(['for-each-ref', '--format=%(refname:short)%00%(worktreepath)', 'refs/heads/'], { cwd: mainWorktree });
|
|
196
|
+
if (references.exitCode === 0) {
|
|
197
|
+
for (const line of references.stdout.split('\n')) {
|
|
198
|
+
const [branch, worktreePath] = line.split('\0', 2);
|
|
199
|
+
if (branch !== undefined && worktreePath !== undefined && worktreePath !== '' && /^wt\d+$/u.test(branch))
|
|
200
|
+
names.add(branch);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return names;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
現在のサブワークツリー名を取得する。
|
|
207
|
+
サブ WT でなければ undefined。記録(`pecot-worktree-name`)があればそれを返す。
|
|
208
|
+
無ければ toplevel の親ディレクトリ名を、`wt\d+` か `base` のときだけ返し、それ以外は undefined。
|
|
209
|
+
Git リポジトリ外なら WorktreeRuntimeError
|
|
210
|
+
*/
|
|
211
|
+
export function getCurrentWorktreeName(cwd) {
|
|
212
|
+
if (!isWorktreeEnvironment(cwd))
|
|
213
|
+
return undefined;
|
|
214
|
+
const recordPath = worktreeNameRecordPath(cwd);
|
|
215
|
+
const recorded = recordPath === undefined ? '' : readRecord(recordPath);
|
|
216
|
+
if (recorded !== '')
|
|
217
|
+
return recorded;
|
|
218
|
+
const toplevel = gitToplevel({ cwd });
|
|
219
|
+
const parent = toplevel === undefined ? undefined : path.basename(path.dirname(toplevel));
|
|
220
|
+
return parent !== undefined && /^(?:wt\d+|base)$/u.test(parent) ? parent : undefined;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
プロジェクトルートを検出する。呼び出し側リポジトリの main WT を正規化し、`<root>/base/<repo>` の形になっているか確認する。
|
|
224
|
+
`<root>` の絶対パスを返す。その形でなければ WorktreeRuntimeError
|
|
225
|
+
*/
|
|
226
|
+
export function detectProjectRoot(cwd) {
|
|
227
|
+
const resolved = resolveRealPath(findMainWorktree(cwd));
|
|
228
|
+
const parent = path.dirname(resolved);
|
|
229
|
+
if (path.basename(parent) !== 'base') {
|
|
230
|
+
const expected = path.join(parent, 'base', path.basename(resolved));
|
|
231
|
+
throw new WorktreeRuntimeError('this repository is not placed in the layout pecot expects for a project\n'
|
|
232
|
+
+ '\n'
|
|
233
|
+
+ ` current: ${resolved}\n`
|
|
234
|
+
+ ` expected: ${expected}\n`
|
|
235
|
+
+ '\n'
|
|
236
|
+
+ 'why base/ is needed:\n'
|
|
237
|
+
+ ' the devcontainer mounts the parallel sets (wt1, wt2...) selectively, so base/ '
|
|
238
|
+
+ 'separates the resident set from the parallel sets\n'
|
|
239
|
+
+ '\n'
|
|
240
|
+
+ 'migration steps (the cwd goes away, so close this CLI session first):\n'
|
|
241
|
+
+ ' 1. close this CLI session\n'
|
|
242
|
+
+ ' 2. in another terminal, run:\n'
|
|
243
|
+
+ ` mkdir -p ${parent}/base\n`
|
|
244
|
+
+ ` mv ${resolved} ${parent}/base/\n`
|
|
245
|
+
+ ` 3. restart the CLI in ${parent}/base/${path.basename(resolved)}/`);
|
|
246
|
+
}
|
|
247
|
+
return path.dirname(parent);
|
|
248
|
+
}
|
|
249
|
+
// プロジェクトルート直下の `<prefix><数字>` ディレクトリの番号を昇順で返す
|
|
250
|
+
function existingSetNumbers(projectRoot, prefix) {
|
|
251
|
+
const entries = existsSync(projectRoot) ? readdirSync(projectRoot) : [];
|
|
252
|
+
return entries
|
|
253
|
+
.filter(entry => entry.startsWith(prefix) && /^\d+$/u.test(entry.slice(prefix.length)) && isDirectory(path.join(projectRoot, entry)))
|
|
254
|
+
.map(entry => Number(entry.slice(prefix.length)))
|
|
255
|
+
.toSorted((a, b) => a - b);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
プロジェクトルート基準で、対象リポの参加先セット名を決める(プロジェクトセット = 同じ wtN 配下の複数リポ WT)。
|
|
259
|
+
|
|
260
|
+
1. `<projectRoot>/wt\d+/` と `options.claimed` の番号を列挙する。claimed の番号は参加せず、max にも数える。
|
|
261
|
+
2. 各 wtN について `wtN/<repositoryDirectoryName>` が存在しないものを先頭から探す。見つかったら既存セットに参加させる形でその名前を返す。
|
|
262
|
+
3. 全ての既存 wtN に該当リポが既にあるなら、max(N)+1 で新セット `wt<N+1>` を返す。
|
|
263
|
+
4. 既存セットが無ければ `wt1` を返す。
|
|
264
|
+
|
|
265
|
+
全セットに参加済みで maxNumber を超えるなら WorktreeRuntimeError
|
|
266
|
+
*/
|
|
267
|
+
export function getNextSetName(projectRoot, repositoryDirectoryName, options = {}) {
|
|
268
|
+
const prefix = options.prefix ?? 'wt';
|
|
269
|
+
const maxNumber = options.maxNumber ?? 9;
|
|
270
|
+
const claimed = new Set();
|
|
271
|
+
const claimedNames = [...options.claimed ?? []];
|
|
272
|
+
for (const claimedName of claimedNames) {
|
|
273
|
+
if (claimedName.startsWith(prefix) && /^\d+$/u.test(claimedName.slice(prefix.length)))
|
|
274
|
+
claimed.add(Number(claimedName.slice(prefix.length)));
|
|
275
|
+
}
|
|
276
|
+
const numbers = [...new Set([...existingSetNumbers(projectRoot, prefix), ...claimed])].toSorted((a, b) => a - b);
|
|
277
|
+
const last = numbers.at(-1);
|
|
278
|
+
if (last === undefined)
|
|
279
|
+
return `${prefix}1`;
|
|
280
|
+
// 既存セットで該当リポが未登場のものがあればそこに参加
|
|
281
|
+
const joinable = numbers.find(number => !claimed.has(number) && !existsSync(path.join(projectRoot, `${prefix}${String(number)}`, repositoryDirectoryName)));
|
|
282
|
+
if (joinable !== undefined)
|
|
283
|
+
return `${prefix}${String(joinable)}`;
|
|
284
|
+
// 全セットに参加済み → 新セット
|
|
285
|
+
if (last + 1 > maxNumber)
|
|
286
|
+
throw new WorktreeRuntimeError(`all of ${prefix}1 to ${prefix}${String(maxNumber)} are in use: no free set`);
|
|
287
|
+
return `${prefix}${String(last + 1)}`;
|
|
288
|
+
}
|
|
289
|
+
// 未追跡ファイル操作
|
|
290
|
+
/**
|
|
291
|
+
git 管理外(gitignored)ファイルの一覧を取得する。cwd はメイン WT のルート。相対パスを返す
|
|
292
|
+
*/
|
|
293
|
+
export function getUntrackedFiles(cwd) {
|
|
294
|
+
const result = runGit(['ls-files', '--others', '--ignored', '--exclude-standard'], { cwd });
|
|
295
|
+
return result.exitCode === 0 ? outputLines(result.stdout).map(line => normalizePath(line)) : [];
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
コピー対象外のファイルを除く。spec は .worktreeignore から読んだ判定
|
|
299
|
+
*/
|
|
300
|
+
export function filterCopyableFiles(files, spec) {
|
|
301
|
+
return files.filter(file => !spec.matchFile(normalizePath(file)));
|
|
302
|
+
}
|
|
303
|
+
// オーケストレーション
|
|
304
|
+
const NO_REMOTE_MESSAGE = 'cannot get the repository information: check that a git remote is set to a GitHub repository URL';
|
|
305
|
+
// remote 候補を優先順に返す。origin があれば origin だけ、無ければ git remote の順にすべて。URL を読めない remote の repository は undefined
|
|
306
|
+
function readRemoteCandidates(cwd) {
|
|
307
|
+
return preferredRemotes(listRemotes(cwd) ?? []).map((remote) => {
|
|
308
|
+
const location = remoteRepository(cwd, remote);
|
|
309
|
+
if (location === undefined)
|
|
310
|
+
return { remote, repository: undefined };
|
|
311
|
+
try {
|
|
312
|
+
return { remote, repository: createRepositoryReference(location.owner, location.repository) };
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
if (error instanceof ValidationFailure)
|
|
316
|
+
return { remote, repository: undefined };
|
|
317
|
+
throw error;
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
// 必須設定ファイルの存在チェック(無ければ早期エラー、init を促す)。(ワークツリー設定ファイルのパス, コピー除外 spec) を返す
|
|
322
|
+
function loadCopyExcludeSpecOrRaise(mainWorktree, diagnostics) {
|
|
323
|
+
const configPath = path.join(mainWorktree, WORKTREE_CONFIG_FILENAME);
|
|
324
|
+
if (!existsSync(configPath)) {
|
|
325
|
+
throw new WorktreeRuntimeError(hinted `worktree config not found: ${WORKTREE_CONFIG_FILENAME}\n run ${commandHint(['worktree', 'init'])} to generate the template`, { failure: 'not-initialized' });
|
|
326
|
+
}
|
|
327
|
+
try {
|
|
328
|
+
return { configPath, spec: loadCopyExcludeSpec(mainWorktree, diagnostics) };
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
// loadCopyExcludeSpec の WorktreeConfigError は、.worktreeignore が無いときだけ
|
|
332
|
+
if (error instanceof WorktreeConfigError)
|
|
333
|
+
throw new WorktreeRuntimeError(error.hintedText ?? error.message, { cause: error, failure: 'not-initialized' });
|
|
334
|
+
throw error;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
// リポジトリ登録チェック。remote は origin、無ければ登録済みのリポを指す最初の remote、どれも未登録なら最初の remote(未登録として止まる)
|
|
338
|
+
function requireRegisteredRepository(cwd) {
|
|
339
|
+
const candidates = readRemoteCandidates(cwd);
|
|
340
|
+
if (candidates.length === 0)
|
|
341
|
+
throw new WorktreeRuntimeError(NO_REMOTE_MESSAGE);
|
|
342
|
+
const config = loadActiveConfig();
|
|
343
|
+
if (config === undefined) {
|
|
344
|
+
throw new WorktreeRuntimeError(hinted `project config not found\n hint: run ${commandHint(['project', 'activate'], { project: placeholder('PROJECT') })} to set the project`, { failure: 'no-active-project' });
|
|
345
|
+
}
|
|
346
|
+
for (const candidate of candidates) {
|
|
347
|
+
if (candidate.repository !== undefined && findRepository(config, candidate.repository.owner, candidate.repository.repository) !== undefined) {
|
|
348
|
+
return { repository: candidate.repository, config, remote: candidate.remote };
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const repository = candidates[0]?.repository;
|
|
352
|
+
if (repository === undefined)
|
|
353
|
+
throw new WorktreeRuntimeError(NO_REMOTE_MESSAGE);
|
|
354
|
+
const registered = config.repositories.length > 0
|
|
355
|
+
? config.repositories.map(item => ` - ${item.owner}/${item.name}`).join('\n')
|
|
356
|
+
: ' (none registered)';
|
|
357
|
+
throw new WorktreeRuntimeError(hinted `repository ${repository.owner}/${repository.repository} is not registered in the active pecot project
|
|
358
|
+
|
|
359
|
+
registered repositories:
|
|
360
|
+
${registered}
|
|
361
|
+
|
|
362
|
+
to add this repository to the pecot project:
|
|
363
|
+
${commandHint(['project', 'link'], { repo: `${repository.owner}/${repository.repository}` })}
|
|
364
|
+
|
|
365
|
+
to switch to another project:
|
|
366
|
+
${commandHint(['project', 'activate'], { project: placeholder('PROJECT') })}`, { failure: 'repo-not-in-project' });
|
|
367
|
+
}
|
|
368
|
+
// ベースブランチ決定(プロジェクト設定の develop_branch を使用)
|
|
369
|
+
function defaultBaseBranch(config, repository) {
|
|
370
|
+
const developBranch = getDevelopBranch(config, repository.owner, repository.repository);
|
|
371
|
+
if (developBranch === undefined || developBranch === '') {
|
|
372
|
+
throw new WorktreeRuntimeError(hinted `develop_branch is not set for repository ${repository.owner}/${repository.repository}
|
|
373
|
+
add develop_branch to repositories in the project config file
|
|
374
|
+
or pass ${inputNameHint(WORKTREE_ADD_PATH, 'base')} explicitly`, { failure: 'repo-setting-missing' });
|
|
375
|
+
}
|
|
376
|
+
return developBranch;
|
|
377
|
+
}
|
|
378
|
+
// ワークツリー設定を読み込む(設定は存在確認済み)。存在するが読み込み・検証に失敗したときは、不在と同様に hard error にして修正を促す
|
|
379
|
+
function loadWorktreeConfigOrRaise(configPath) {
|
|
380
|
+
try {
|
|
381
|
+
return loadConfig(configPath);
|
|
382
|
+
}
|
|
383
|
+
catch (error) {
|
|
384
|
+
if (error instanceof WorktreeConfigError) {
|
|
385
|
+
throw new WorktreeRuntimeError(`failed to load the worktree config: ${normalizePath(configPath)}: ${error.message}\n fix the config file and run it again`, { cause: error, failure: 'config-invalid' });
|
|
386
|
+
}
|
|
387
|
+
throw error;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
// シンボリックリンク作成。(結果, 作成成功したリンクの WT 相対パス) を返す。後者はコピー除外に使う
|
|
391
|
+
function createWorktreeSymlinks(config, projectRoot, worktreePath, diagnostics) {
|
|
392
|
+
const linkedFiles = createSymlinks(config, projectRoot, worktreePath, diagnostics);
|
|
393
|
+
const symlinkedPaths = linkedFiles
|
|
394
|
+
.filter(link => link.action === 'created')
|
|
395
|
+
.map(link => path.relative(worktreePath, link.symlinkPath))
|
|
396
|
+
.filter(relative => relative !== '..' && !relative.startsWith('../'));
|
|
397
|
+
return { linkedFiles, symlinkedPaths };
|
|
398
|
+
}
|
|
399
|
+
function isRelativeTo(file, base) {
|
|
400
|
+
const relative = path.relative(base, file);
|
|
401
|
+
return relative !== '..' && !relative.startsWith('../') && !path.isAbsolute(relative);
|
|
402
|
+
}
|
|
403
|
+
// 未追跡ファイルコピー(シンボリックリンク対象を除外)
|
|
404
|
+
function copyUntrackedToWorktree(mainWorktree, worktreePath, spec, symlinkedPaths) {
|
|
405
|
+
const copyable = filterCopyableFiles(getUntrackedFiles(mainWorktree), spec)
|
|
406
|
+
.filter(file => symlinkedPaths.every(linked => !isRelativeTo(file, linked)));
|
|
407
|
+
return copyable.length > 0 ? copyFiles(mainWorktree, worktreePath, copyable) : [];
|
|
408
|
+
}
|
|
409
|
+
// セットアップコマンド実行。優先順位: CLI --setup 明示 > config.setup_command > skip
|
|
410
|
+
function runEffectiveSetup(setupCommand, config, worktreePath, diagnostics) {
|
|
411
|
+
const effective = setupCommand ?? config.setup_command;
|
|
412
|
+
if (effective === undefined || effective === '')
|
|
413
|
+
return undefined;
|
|
414
|
+
const result = runSetupCommand(effective, worktreePath, config.setup_command_timeout);
|
|
415
|
+
if (result.exitCode !== 0) {
|
|
416
|
+
// Python の core と同じ 1 メッセージ。字下げは受け口側が付ける
|
|
417
|
+
const head = result.exitCode === -1 ? `setup command timed out: ${effective}` : `setup command failed (exit ${String(result.exitCode)}): ${effective}`;
|
|
418
|
+
const lines = [head];
|
|
419
|
+
if (result.stdout.trim() !== '')
|
|
420
|
+
for (const line of result.stdout.replace(/\n+$/, '').split('\n'))
|
|
421
|
+
lines.push(`out: ${line}`);
|
|
422
|
+
if (result.stderr.trim() !== '')
|
|
423
|
+
for (const line of result.stderr.replace(/\n+$/, '').split('\n'))
|
|
424
|
+
lines.push(`err: ${line}`);
|
|
425
|
+
diagnostics.warning(lines.join('\n'));
|
|
426
|
+
}
|
|
427
|
+
return result;
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
ワークツリーを作成する。cwd は対象 Git リポジトリのパス。
|
|
431
|
+
作成に失敗した場合、プロジェクトルート・既存ブランチ衝突・設定の不備は WorktreeRuntimeError
|
|
432
|
+
*/
|
|
433
|
+
export function createWorktree(cwd, diagnostics, options = {}) {
|
|
434
|
+
// 1. メインWT検出 & プロジェクトルート
|
|
435
|
+
const mainWorktree = findMainWorktree(cwd);
|
|
436
|
+
const projectRoot = detectProjectRoot(cwd);
|
|
437
|
+
// 1.1 必須設定ファイルの存在チェック(無ければ早期エラー、init を促す)
|
|
438
|
+
const { configPath, spec } = loadCopyExcludeSpecOrRaise(mainWorktree, diagnostics);
|
|
439
|
+
// 1.2 container rebuild 後の stale worktree メタデータを事前に掃除する。
|
|
440
|
+
// `.git/worktrees/<name>/` だけ残って実体が消えているケース(rebuild や手動 rm -rf のあと)で、add が衝突エラーになるのを防ぐ
|
|
441
|
+
runGit(['worktree', 'prune'], { cwd: mainWorktree });
|
|
442
|
+
// 1.5 リポジトリ登録チェック(アクティブプロジェクト配下か確認)
|
|
443
|
+
const { repository, config, remote } = requireRegisteredRepository(cwd);
|
|
444
|
+
// 2. 名前決定(プロジェクトセットへの自動参加)
|
|
445
|
+
const repositoryDirectoryName = path.basename(mainWorktree);
|
|
446
|
+
const name = options.name ?? getNextSetName(projectRoot, repositoryDirectoryName, { claimed: claimedSetNames(mainWorktree) });
|
|
447
|
+
// 3. ベースブランチ決定(プロジェクト設定の develop_branch を使用)
|
|
448
|
+
const baseBranch = options.baseBranch ?? defaultBaseBranch(config, repository);
|
|
449
|
+
// 4. パス計算: <project_root>/<name>/<repo_dir_name>
|
|
450
|
+
const worktreePath = options.path === undefined ? path.join(projectRoot, name, repositoryDirectoryName) : normalizePath(options.path);
|
|
451
|
+
// dry-run時はここで結果を返す
|
|
452
|
+
if (options.isDryRun === true) {
|
|
453
|
+
return { name, path: worktreePath, branch: name, baseBranch, copiedFiles: [], linkedFiles: [], setupResult: undefined };
|
|
454
|
+
}
|
|
455
|
+
// 5. git worktree add
|
|
456
|
+
addGitWorktree(cwd, worktreePath, name, { remote, baseBranch }, options.isExistingBranchAllowed === true);
|
|
457
|
+
recordWorktreeName(worktreePath, name, diagnostics);
|
|
458
|
+
// 6〜8. シンボリックリンク作成・未追跡ファイルコピー・セットアップコマンド実行
|
|
459
|
+
const worktreeConfig = loadWorktreeConfigOrRaise(configPath);
|
|
460
|
+
const linking = options.shouldLink === false
|
|
461
|
+
? { linkedFiles: [], symlinkedPaths: [] }
|
|
462
|
+
: createWorktreeSymlinks(worktreeConfig, projectRoot, worktreePath, diagnostics);
|
|
463
|
+
const copiedFiles = options.shouldCopy === false ? [] : copyUntrackedToWorktree(mainWorktree, worktreePath, spec, linking.symlinkedPaths);
|
|
464
|
+
const setupResult = runEffectiveSetup(options.setupCommand, worktreeConfig, worktreePath, diagnostics);
|
|
465
|
+
return { name, path: worktreePath, branch: name, baseBranch, copiedFiles, linkedFiles: linking.linkedFiles, setupResult };
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
`git worktree add` を実行し、既存ブランチ衝突ガードも含めて処理する。
|
|
469
|
+
cwd は対象 Git リポジトリのパス(メイン WT でもサブ WT でも可)。
|
|
470
|
+
既存ブランチの upstream 不一致、または git worktree add 失敗時は WorktreeRuntimeError
|
|
471
|
+
*/
|
|
472
|
+
function addGitWorktree(cwd, worktreePath, name, base, isExistingBranchAllowed) {
|
|
473
|
+
const { remote, baseBranch } = base;
|
|
474
|
+
let hasBranch = runGit(['show-ref', '--verify', '--quiet', `refs/heads/${name}`], { cwd }).exitCode === 0;
|
|
475
|
+
if (hasBranch && !isExistingBranchAllowed) {
|
|
476
|
+
const currentUpstream = pythonStrip(runGit(['for-each-ref', '--format=%(upstream:short)', `refs/heads/${name}`], { cwd }).stdout);
|
|
477
|
+
const expectedUpstream = baseBranch === '' ? undefined : `${remote}/${baseBranch}`;
|
|
478
|
+
if ((currentUpstream === '' ? undefined : currentUpstream) !== expectedUpstream) {
|
|
479
|
+
const current = currentUpstream === '' ? '(unset)' : currentUpstream;
|
|
480
|
+
throw new WorktreeRuntimeError(hinted `branch '${name}' already exists and its upstream differs from the expected one (current: ${current}, expected: ${expectedUpstream ?? 'None'}): pass ${inputHint(WORKTREE_ADD_PATH, 'allow_existing_branch')} to reuse it`);
|
|
481
|
+
}
|
|
482
|
+
// upstream 一致かつ bind なし → prune に取り残された孤児ブランチとみなし除去
|
|
483
|
+
const worktreeOfBranch = runGit(['for-each-ref', '--format=%(worktreepath)', `refs/heads/${name}`], { cwd });
|
|
484
|
+
if (worktreeOfBranch.exitCode === 0 && pythonStrip(worktreeOfBranch.stdout) === '') {
|
|
485
|
+
runGit(['branch', '-D', name], { cwd });
|
|
486
|
+
hasBranch = false;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
const gitArguments = hasBranch ? ['worktree', 'add', worktreePath, name] : ['worktree', 'add', worktreePath, '-b', name];
|
|
490
|
+
if (!hasBranch && baseBranch !== '')
|
|
491
|
+
gitArguments.push('--track', `${remote}/${baseBranch}`);
|
|
492
|
+
const result = runGit(gitArguments, { cwd });
|
|
493
|
+
if (result.exitCode !== 0)
|
|
494
|
+
throw new WorktreeRuntimeError(`failed to create the worktree: ${result.stderr}`);
|
|
495
|
+
}
|
|
496
|
+
// worktree の記録。ディレクトリが無い、toplevel が別(.git の消えた跡)なら空。GIT_* は外して読む
|
|
497
|
+
function recordedNameOf(worktreePath) {
|
|
498
|
+
if (!isDirectory(worktreePath))
|
|
499
|
+
return '';
|
|
500
|
+
const toplevel = gitToplevel({ cwd: worktreePath, stripGitEnvironment: true });
|
|
501
|
+
if (toplevel === undefined || resolveRealPath(toplevel) !== resolveRealPath(worktreePath))
|
|
502
|
+
return '';
|
|
503
|
+
const result = runGit(['rev-parse', '--path-format=absolute', '--git-path', WORKTREE_NAME_RECORD], { cwd: worktreePath, stripGitEnvironment: true });
|
|
504
|
+
const recordPath = pythonStrip(result.stdout);
|
|
505
|
+
return recordPath !== '' && result.exitCode === 0 ? readRecord(recordPath) : '';
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
名前から削除対象の worktree を探す(メインを除く)。記録の名前、置き場所 `<root>/<name>/<repo>`、ブランチ名の順に、段ごとに全件を見る
|
|
509
|
+
*/
|
|
510
|
+
function findWorktreePathByName(cwd, name) {
|
|
511
|
+
const candidates = getWorktreeList(cwd).slice(1);
|
|
512
|
+
const recorded = candidates.find(info => recordedNameOf(info.path) === name);
|
|
513
|
+
if (recorded !== undefined)
|
|
514
|
+
return recorded.path;
|
|
515
|
+
let expected;
|
|
516
|
+
try {
|
|
517
|
+
const repositoryName = path.basename(resolveRealPath(findMainWorktree(cwd)));
|
|
518
|
+
expected = path.join(detectProjectRoot(cwd), name, repositoryName);
|
|
519
|
+
}
|
|
520
|
+
catch (error) {
|
|
521
|
+
if (!(error instanceof WorktreeRuntimeError))
|
|
522
|
+
throw error;
|
|
523
|
+
}
|
|
524
|
+
const placed = expected === undefined ? undefined : candidates.find(info => resolveRealPath(info.path) === resolveRealPath(expected));
|
|
525
|
+
return placed?.path ?? candidates.find(info => info.branch === name)?.path;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
ワークツリーを削除する。name は worktree add が付けた名前(wtN)か、checkout しているブランチ名。
|
|
529
|
+
WT が見つからない・削除に失敗した場合は WorktreeRuntimeError。
|
|
530
|
+
ローカルブランチを消せなかったときは、その理由を返す。成功時と shouldKeepBranch は undefined。isDryRun は WT を探すだけで何も消さない
|
|
531
|
+
*/
|
|
532
|
+
export function removeWorktree(cwd, name, diagnostics, options = {}) {
|
|
533
|
+
// 1. WTパスを特定
|
|
534
|
+
const worktreePath = findWorktreePathByName(cwd, name);
|
|
535
|
+
if (worktreePath === undefined)
|
|
536
|
+
throw new WorktreeRuntimeError(`worktree not found: ${name}`);
|
|
537
|
+
if (options.isDryRun === true)
|
|
538
|
+
return undefined;
|
|
539
|
+
// 2. git worktree remove
|
|
540
|
+
const gitArguments = ['worktree', 'remove', worktreePath];
|
|
541
|
+
if (options.isForced === true)
|
|
542
|
+
gitArguments.push('--force');
|
|
543
|
+
const removed = runGit(gitArguments, { cwd });
|
|
544
|
+
if (removed.exitCode !== 0) {
|
|
545
|
+
const reason = pythonStrip(removed.stderr);
|
|
546
|
+
// git の文は CLI の `--force` を案内するので、MCP でも打てる形の案内を添える
|
|
547
|
+
if (options.isForced !== true && reason.includes('contains modified or untracked files')) {
|
|
548
|
+
throw new WorktreeRuntimeError(hinted `failed to remove the worktree: ${reason}\nhint: to remove it with its changes, pass ${inputHint(['worktree', 'remove'], 'force')}`);
|
|
549
|
+
}
|
|
550
|
+
throw new WorktreeRuntimeError(`failed to remove the worktree: ${removed.stderr}`);
|
|
551
|
+
}
|
|
552
|
+
// 3. ブランチ削除(ローカルブランチ)
|
|
553
|
+
let branchError;
|
|
554
|
+
if (options.shouldKeepBranch !== true) {
|
|
555
|
+
const branchResult = runGit(['branch', '-D', name], { cwd });
|
|
556
|
+
if (branchResult.exitCode !== 0)
|
|
557
|
+
branchError = pythonStrip(branchResult.stderr) || `git branch -D exited with ${String(branchResult.exitCode)}`;
|
|
558
|
+
}
|
|
559
|
+
// 4. プロジェクトルート配下の <name> ディレクトリが空なら rmdir
|
|
560
|
+
removeEmptySetDirectory(cwd, name, diagnostics);
|
|
561
|
+
return branchError;
|
|
562
|
+
}
|
|
563
|
+
function removeEmptySetDirectory(cwd, name, diagnostics) {
|
|
564
|
+
let projectRoot;
|
|
565
|
+
try {
|
|
566
|
+
projectRoot = detectProjectRoot(cwd);
|
|
567
|
+
}
|
|
568
|
+
catch (error) {
|
|
569
|
+
if (error instanceof WorktreeRuntimeError)
|
|
570
|
+
return;
|
|
571
|
+
throw error;
|
|
572
|
+
}
|
|
573
|
+
const groupDirectory = path.join(projectRoot, name);
|
|
574
|
+
if (!isDirectory(groupDirectory) || readdirSync(groupDirectory).length > 0)
|
|
575
|
+
return;
|
|
576
|
+
try {
|
|
577
|
+
rmdirSync(groupDirectory);
|
|
578
|
+
}
|
|
579
|
+
catch (error) {
|
|
580
|
+
const converted = toOsError(error);
|
|
581
|
+
diagnostics.warning(`failed to remove the set directory: ${groupDirectory}: ${converted instanceof Error ? converted.message : String(converted)}`);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
//# sourceMappingURL=worktree.js.map
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { CallToolResult } from '@modelcontextprotocol/server';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import type { FailureKind } from '../commands/failure-kind.js';
|
|
4
|
+
import type { CommandIo } from '../commands/registry.js';
|
|
5
|
+
export interface CommandOutcome {
|
|
6
|
+
readonly exitCode: number;
|
|
7
|
+
readonly stdout: string;
|
|
8
|
+
readonly stderr: string;
|
|
9
|
+
/**
|
|
10
|
+
失敗の原因の名前。終了コードが 0 でないのに無ければ other
|
|
11
|
+
*/
|
|
12
|
+
readonly kind?: FailureKind | undefined;
|
|
13
|
+
/**
|
|
14
|
+
失敗の message に使う文。無ければ stderr の行から決める
|
|
15
|
+
*/
|
|
16
|
+
readonly message?: string | undefined;
|
|
17
|
+
/**
|
|
18
|
+
成功の message に使う結果の行(片付けの行を除いた最初のもの)。無ければ stdout の最初の空でない行
|
|
19
|
+
*/
|
|
20
|
+
readonly resultLine?: string | undefined;
|
|
21
|
+
}
|
|
22
|
+
export interface CollectedIo {
|
|
23
|
+
/**
|
|
24
|
+
readLine を持たない。標準入力の無い io は、入力の終端と同じ扱い
|
|
25
|
+
*/
|
|
26
|
+
readonly io: CommandIo;
|
|
27
|
+
readonly stdout: () => string;
|
|
28
|
+
readonly stderr: () => string;
|
|
29
|
+
readonly kind: () => FailureKind | undefined;
|
|
30
|
+
readonly resultLine: () => string | undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
stdout・stderr に書かれた文字列と、失敗の原因の名前、最初の結果の行を集める io
|
|
34
|
+
*/
|
|
35
|
+
export declare function collectIo(): CollectedIo;
|
|
36
|
+
/**
|
|
37
|
+
全ツールが共有する outputSchema。pecot-tools・pecot-visual と項目の名前をそろえる
|
|
38
|
+
*/
|
|
39
|
+
export declare const TOOL_OUTPUT_SCHEMA: z.ZodObject<{
|
|
40
|
+
ok: z.ZodBoolean;
|
|
41
|
+
exitCode: z.ZodNumber;
|
|
42
|
+
kind: z.ZodOptional<z.ZodString>;
|
|
43
|
+
artifacts: z.ZodArray<z.ZodString>;
|
|
44
|
+
data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
45
|
+
message: z.ZodString;
|
|
46
|
+
stdout: z.ZodOptional<z.ZodString>;
|
|
47
|
+
stderr: z.ZodOptional<z.ZodString>;
|
|
48
|
+
}, z.core.$strip>;
|
|
49
|
+
/**
|
|
50
|
+
structuredContent と、同じ JSON を本文にした content の両方で返す。ホストがどちらを渡しても同じ中身が届く
|
|
51
|
+
*/
|
|
52
|
+
export declare function toToolResult(outcome: Readonly<CommandOutcome>): CallToolResult;
|
|
53
|
+
/**
|
|
54
|
+
コマンドを呼ぶ前に入力を断った結果。終了コードは使い方の誤りと同じ 2
|
|
55
|
+
*/
|
|
56
|
+
export declare function toRejectedResult(message: string): CallToolResult;
|
|
57
|
+
/**
|
|
58
|
+
中断(notifications/cancelled か接続の切断)で本体を呼ばなかった結果。応答はクライアントに届かない
|
|
59
|
+
*/
|
|
60
|
+
export declare function toAbortedResult(): CallToolResult;
|
|
61
|
+
//# sourceMappingURL=result.d.ts.map
|