From 070b0a6db7f70fb0ac2b7cf7945b8832cc5e2cd8 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:42:30 +0000 Subject: [PATCH 01/18] =?UTF-8?q?Docs:=20#514=20=E3=81=AE=E5=AE=9F?= =?UTF-8?q?=E8=A3=85=E8=A8=88=E7=94=BB=E3=82=92=E6=9B=B8=E3=81=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- issues/issue-514-plan.md | 156 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 issues/issue-514-plan.md diff --git a/issues/issue-514-plan.md b/issues/issue-514-plan.md new file mode 100644 index 00000000..e5b594f3 --- /dev/null +++ b/issues/issue-514-plan.md @@ -0,0 +1,156 @@ +# #514: リポジトリ・プラグイン・プロジェクトの新規追加コマンドと TUI の操作 + +## 関連リンク + +- 課題: #514(写しは `issues/issue-514-requirements.md`) +- 設計: `issues/issue-514-design.md`(決定 1〜11、不変条件 I1〜I9、「経路ごとの反映と登録」、「テスト設計」) + +## モード + +`standard`(設計の「当たるモード」のとおり。公開の CLI と TUI が増え、GitHub へ書く) + +## 目的と非目的 + +達成したい状態: + +- 引数 1 つのコマンドか `devbase list` の TUI で、権限の確認からマージ、手元の取り込みと登録までが終わる + +やらないこと: + +- `devbase up` の実行、`env` の値の登録、フックや `Dockerfile` の雛形の出し分け +- プラグインの `description` の書き足し、GitHub 以外のホスト、Organization の作成、`gh` の導入の代行 +- #516(大文字小文字の違う URL の二重登録) + +## 前提 + +- 前提 1: テストは実の GitHub に触らない。偽の `gh` と手元の bare リポジトリ(`url..insteadOf`)で通す +- 前提 2: 手元の `plugins.yml`・`repos/`・`projects/` の実物に触らない。テストは一時のルートで組む + +## 受け入れ条件 + +`issues/issue-514-requirements.md` の 1〜22 をそのまま使う。検証手段は「テスト設計」の表の行で、下の各タスクへ割り当てる。 + +## 代替案と採否 + +設計の決定 1〜11 のとおり。実装の計画で新たに選んだものは次の 2 つである。 + +| 案 | 内容 | 採否 | 理由 | +| --- | --- | --- | --- | +| A | 作成フローのテストは実の `git` と偽の `gh` の実行ファイルで通す | 採用 | `gh` と `git` の引数と順序を実物の push・マージの結果で縛れる | +| B | `subprocess.run` をモックする | 不採用 | 手元の作業ツリーへ書かないこと(I4)や push の順序を結果で確かめられない | +| C | 既定ブランチの `registry.yml` と既存のパスは `gh api` の contents で読む | 採用 | 計画の確定の前に手元へ何も作らない(I1)。手元の clone が古くても重複を見つけられる | +| D | 計画の段階で一時の clone を作って読む | 不採用 | 確認の前に時間のかかる clone が要る | + +## 不変条件 + +設計の I1〜I9 をそのまま使う。 + +## 互換性 + +| 対象 | 変更 | 互換性の扱い | +| --- | --- | --- | +| 公開インタフェース(コマンド) | `plugin repo new`・`plugin new`・`project new` | 追加のみ | +| TUI | プラグインのメニューの階層 | 変わる(受け入れ条件 19) | +| データスキーマ | `plugins.yml` | 変えない | + +## 修正対象 + +- 新規: `lib/devbase/plugin/{github,scaffold,publish,creator}.py` +- 変更: `lib/devbase/plugin/repo_manager.py`、`lib/devbase/commands/{plugin,project}.py`、`lib/devbase/cli.py`、`lib/devbase/tui/actions_plugin.py`、`etc/_devbase`、`etc/devbase-completion.bash` +- 文書: `docs/user/cli-reference/`、`docs/plugin-dev/`、`docs/glossary/glossary.json`、`docs/glossary.md`、`CHANGELOG.md` +- テスト: `tests/plugin/`(作成フロー)、`tests/cli/`(解決・補完)、`tests/cli/tui/test_actions_plugin.py` + +## タスク分解 + +### Task 1: 引数の解決と `gh` の呼び出し + +- **対象ファイル:** `lib/devbase/plugin/github.py`、`tests/plugin/test_github.py` +- **変更内容:** `GitHubRef.parse`、`GhClient`(認証・権限・作成の可否・読み取り・作成・PR・マージ) +- **満たす受け入れ条件:** 5、14 +- **進め方:** 失敗するテスト → 通す最小実装 → 整理 + +### Task 2: 雛形と `registry.yml` の追記 + +- **対象ファイル:** `lib/devbase/plugin/scaffold.py`、`tests/plugin/test_scaffold.py` +- **変更内容:** 3 種類の雛形の文字列、書式を保つ 1 項目の追記と読み直しの検証 +- **満たす受け入れ条件:** 6、9、I3 +- **進め方:** 失敗するテスト → 通す最小実装 → 整理 + +### Task 3: 登録の照合と早送りの取り込み + +- **対象ファイル:** `lib/devbase/plugin/repo_manager.py`、`tests/plugin/test_repo_manager_creation.py` +- **変更内容:** `_find_registered`・`_pull_ff_only` の追加。既存の関数は変えない +- **満たす受け入れ条件:** 16、I4、I8、決定 9 +- **進め方:** 失敗するテスト → 通す最小実装 → 整理 + +### Task 4: 一時の clone から既定ブランチへの反映 + +- **対象ファイル:** `lib/devbase/plugin/publish.py`、`tests/plugin/creation_harness.py`、`tests/plugin/conftest.py`、`tests/plugin/test_publish.py` +- **変更内容:** 最初のコミットの直接の push、ブランチ・PR・マージ。偽の `gh` と bare リポジトリの土台 +- **満たす受け入れ条件:** 1、2、16、17、I7 +- **進め方:** 失敗するテスト → 通す最小実装 → 整理 + +### Task 5: `devbase plugin repo new` + +- **対象ファイル:** `lib/devbase/plugin/creator.py`、`lib/devbase/commands/plugin.py`、`lib/devbase/cli.py`、`tests/plugin/test_create_repo.py` +- **変更内容:** `plan_repo`・`execute`・計画の確認と `--yes`、パーサと `SUBCMD_MAP`・`repo_subcmds` +- **満たす受け入れ条件:** 1〜5、14、15、17、I1、I2、I5、I7 +- **進め方:** 失敗するテスト → 通す最小実装 → 整理 + +### Task 6: `devbase plugin new` + +- **対象ファイル:** `lib/devbase/plugin/creator.py`、`lib/devbase/commands/plugin.py`、`lib/devbase/cli.py`、`tests/plugin/test_create_plugin.py` +- **変更内容:** `plan_plugin`、未登録の 4 状態、登録済みの経路、登録の clone の確かめ +- **満たす受け入れ条件:** 6、7、8、16、17、I2、I8、I9、決定 8、決定 9 +- **進め方:** 失敗するテスト → 通す最小実装 → 整理 + +### Task 7: `devbase project new` + +- **対象ファイル:** `lib/devbase/plugin/creator.py`、`lib/devbase/commands/project.py`、`lib/devbase/cli.py`、`tests/plugin/test_create_project.py`、`tests/cli/test_project_new_dispatch.py` +- **変更内容:** 入れ先の決定、グループの決定、`plan_project`、`_NO_SECRET_INJECTION` +- **満たす受け入れ条件:** 9〜13、22、I6、I9 +- **進め方:** 失敗するテスト → 通す最小実装 → 整理 + +### Task 8: シェル補完 + +- **対象ファイル:** `etc/_devbase`、`etc/devbase-completion.bash`、`tests/cli/test_completion.py` +- **変更内容:** 3 つのコマンドとオプションの候補 +- **満たす受け入れ条件:** 目的の「シェル補完」 +- **進め方:** 失敗するテスト → 通す最小実装 → 整理 + +### Task 9: TUI のメニューの組み直しと 3 つの入口 + +- **対象ファイル:** `lib/devbase/tui/actions_plugin.py`、`tests/cli/tui/test_actions_plugin.py` +- **変更内容:** 第 1 階層を用途で分け、新規追加の入力の順を設計のとおりに置く +- **満たす受け入れ条件:** 18、19、20 +- **進め方:** 失敗するテスト → 通す最小実装 → 整理 + +### Task 10: 文書 + +- **対象ファイル:** `docs/user/cli-reference/`、`docs/plugin-dev/`、`docs/glossary/glossary.json`、`docs/glossary.md`、`CHANGELOG.md` +- **変更内容:** コマンドのリファレンス、プラグインリポジトリの定義、用語集の出所、変更履歴 +- **満たす受け入れ条件:** 影響の「公開インタフェース」 +- **進め方:** テスト駆動を適用しない(文書だけ。`glossary.py check` と固有の語の検査で確かめる) + +## 影響範囲 + +- `devbase plugin`・`devbase plugin repo`・`devbase project` の接頭辞の解決と補完 +- `devbase list` のプラグインのメニュー + +## リスクと対処 + +| リスク | 対処 | +| --- | --- | +| `SUBCMD_MAP` と補完の一致テストに新しい値が当たる | タスクごとにテストを通す | +| `actions_plugin.py` のメニューの変更で既存のテストの前提が変わる | タスクごとにテストを通す。`_run_operation`・`_run_repo_operation` の契約は残す | +| `repo_manager.py` の既存の経路を壊す | 足すだけにして既存の関数を変えない | + +## 切り戻し手順 + +- 追加のコマンドは該当のコミットを revert すれば消える。`plugins.yml` の形は変わらないので、データの戻しは要らない + +## 完了の定義 + +- [ ] 受け入れ条件 1〜22 と I1〜I9 が「テスト設計」の行のテストに対応している +- [ ] `env -u DEVBASE_ROOT uv run --locked pytest tests/ -q`、`uvx ruff check --select=E9,F63,F7,F82 lib`、`python3 .github/scripts/proper_term_check.py` が通る +- [ ] 実の GitHub での完走は、リリース後テストで利用者が確かめる(テストからは書かない) From 94f10987eaf4be1534c90534dd824f6bab303820 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:43:55 +0000 Subject: [PATCH 02/18] =?UTF-8?q?Feat:=20#514=20GitHub=20=E3=81=AE?= =?UTF-8?q?=E5=8F=82=E7=85=A7=E3=81=AE=E8=A7=A3=E6=B1=BA=E3=81=A8=20gh=20?= =?UTF-8?q?=E3=81=AE=E5=91=BC=E3=81=B3=E5=87=BA=E3=81=97=E3=82=92=E8=B6=B3?= =?UTF-8?q?=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/devbase/plugin/github.py | 225 ++++++++++++++++++++++++++++ tests/plugin/test_github.py | 279 +++++++++++++++++++++++++++++++++++ 2 files changed, 504 insertions(+) create mode 100644 lib/devbase/plugin/github.py create mode 100644 tests/plugin/test_github.py diff --git a/lib/devbase/plugin/github.py b/lib/devbase/plugin/github.py new file mode 100644 index 00000000..a01a3517 --- /dev/null +++ b/lib/devbase/plugin/github.py @@ -0,0 +1,225 @@ +"""GitHub の参照の解決と ``gh`` の呼び出し (#514)。 + +引数の解決 (:class:`GitHubRef`) と、権限の確認・リポジトリの作成・PR・マージ +(:class:`GhClient`) を持つ。認証は利用者の ``gh`` の設定に任せ、トークンを扱わない +(設計の決定 11)。 +""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +import time +from dataclasses import dataclass +from typing import Optional + +from devbase.errors import RepositoryError + +_HTTPS_RE = re.compile(r'https://github\.com/([^/]+)/([^/]+?)(?:\.git)?/?') +_SSH_RE = re.compile(r'git@github\.com:([^/]+)/([^/]+?)(?:\.git)?') +_SHORT_RE = re.compile(r'([^/:@]+)/([^/:@]+?)(?:\.git)?') + +_OWNER_RE = re.compile(r'[A-Za-z0-9][A-Za-z0-9-]*') +_REPO_RE = re.compile(r'[A-Za-z0-9._][A-Za-z0-9._-]*') +_RESERVED_REPOS = frozenset({'.', '..', '.git'}) + +_PUSH_PERMISSIONS = frozenset({'ADMIN', 'MAINTAIN', 'WRITE'}) +_MISSING_REPO_MARK = 'Could not resolve to a Repository' +_NOT_ACCESSIBLE_MARKS = ('HTTP 403', 'HTTP 404') + +#: マージの方式。リポジトリが許す順に選ぶ (設計の決定 4) +_MERGE_METHODS = ( + ('mergeCommitAllowed', '--merge'), + ('squashMergeAllowed', '--squash'), + ('rebaseMergeAllowed', '--rebase'), +) +#: ``mergeable`` が ``UNKNOWN`` の間の待ち (2 秒 × 15 回で最長 30 秒。設計の決定 4) +_MERGEABLE_POLL_SECONDS = 2 +_MERGEABLE_POLLS = 15 + + +@dataclass(frozen=True) +class GitHubRef: + """GitHub のリポジトリの参照。``clone_url`` は入力の形を保つ (``git@`` は ``git@`` のまま)""" + owner: str + repo: str + clone_url: str + + @property + def full_name(self) -> str: + return f"{self.owner}/{self.repo}" + + @classmethod + def parse(cls, value: str) -> 'GitHubRef': + """``owner/repo``・``https://github.com/...``・``git@github.com:...`` を解決する。 + + Raises: + RepositoryError: 形が違う・GitHub 以外のとき + """ + text = (value or '').strip() + ssh = _SSH_RE.fullmatch(text) + match = ssh or _HTTPS_RE.fullmatch(text) or _SHORT_RE.fullmatch(text) + if match is None: + raise RepositoryError( + f"GitHub のリポジトリとして読めません: '{value}'\n" + "owner/repo・https://github.com/owner/repo・git@github.com:owner/repo.git の" + "どれかで指定してください" + ) + owner, repo = match.groups() + if (_OWNER_RE.fullmatch(owner) is None or _REPO_RE.fullmatch(repo) is None + or repo in _RESERVED_REPOS): + raise RepositoryError(f"GitHub の owner/repo の形ではありません: '{value}'") + clone_url = (f"git@github.com:{owner}/{repo}.git" if ssh + else f"https://github.com/{owner}/{repo}.git") + return cls(owner, repo, clone_url) + + +@dataclass(frozen=True) +class RepoView: + """``gh repo view`` の結果""" + empty: bool + default_branch: str + can_push: bool + + +class GhClient: + """``gh`` の呼び出し。読むものと書くものをメソッドで分ける""" + + def __init__(self) -> None: + self._login: Optional[str] = None + + def _run(self, *args: str) -> subprocess.CompletedProcess: + return subprocess.run(['gh', *args], capture_output=True, text=True, check=False) + + def _json(self, *args: str, what: str): + result = self._run(*args) + if result.returncode != 0: + raise RepositoryError(f"{what}に失敗しました: {result.stderr.strip()}") + return json.loads(result.stdout) + + def ensure_ready(self) -> None: + """``gh`` が入っていて認証済みであることを確かめる (読むだけ)""" + if shutil.which('gh') is None: + raise RepositoryError( + "gh が見つかりません。https://cli.github.com/ から入れて、" + "gh auth login でログインしてください" + ) + self.login() + + def login(self) -> str: + """認証中のアカウントの ``login``""" + if self._login is None: + result = self._run('api', 'user') + if result.returncode != 0: + raise RepositoryError( + "gh の認証を確かめられません。gh auth login でログインしてください: " + f"{result.stderr.strip()}" + ) + self._login = json.loads(result.stdout)['login'] + return self._login + + def view_repo(self, ref: GitHubRef) -> Optional[RepoView]: + """リポジトリの状態を返す。無い (読めない private を含む) ときは ``None``""" + result = self._run('repo', 'view', ref.full_name, + '--json', 'isEmpty,defaultBranchRef,viewerPermission') + if result.returncode != 0: + if _MISSING_REPO_MARK in result.stderr: + return None + raise RepositoryError( + f"{ref.full_name} の確認に失敗しました: {result.stderr.strip()}") + data = json.loads(result.stdout) + return RepoView( + empty=bool(data.get('isEmpty')), + default_branch=(data.get('defaultBranchRef') or {}).get('name') or '', + can_push=data.get('viewerPermission') in _PUSH_PERMISSIONS, + ) + + def can_create_in(self, owner: str) -> bool: + """``owner`` の下にリポジトリを作れるか (読むだけ)""" + if owner.lower() == self.login().lower(): + return True + membership = self._read_api(f'user/memberships/orgs/{owner}') + if membership is None or membership.get('state') != 'active': + return False + if membership.get('role') == 'admin': + return True + org = self._read_api(f'orgs/{owner}') + return bool(org and org.get('members_can_create_repositories')) + + def _read_api(self, path: str) -> Optional[dict]: + """権限が無い・無いものは ``None``、それ以外の失敗は例外にする""" + result = self._run('api', path) + if result.returncode == 0: + return json.loads(result.stdout) + if any(mark in result.stderr for mark in _NOT_ACCESSIBLE_MARKS): + return None + raise RepositoryError(f"gh api {path} に失敗しました: {result.stderr.strip()}") + + def read_file(self, ref: GitHubRef, path: str) -> Optional[str]: + """既定ブランチのファイルの中身。無いときは ``None``。ディレクトリは一覧の JSON が返る""" + result = self._run('api', f'repos/{ref.full_name}/contents/{path}', + '-H', 'Accept: application/vnd.github.raw+json') + if result.returncode == 0: + return result.stdout + if 'HTTP 404' in result.stderr: + return None + raise RepositoryError( + f"{ref.full_name} の {path} を読めません: {result.stderr.strip()}") + + def create_repo(self, ref: GitHubRef, *, public: bool) -> None: + visibility = '--public' if public else '--private' + result = self._run('repo', 'create', ref.full_name, visibility) + if result.returncode != 0: + raise RepositoryError( + f"{ref.full_name} を作れませんでした: {result.stderr.strip()}") + + def create_pr(self, ref: GitHubRef, *, base: str, head: str, + title: str, body: str) -> str: + result = self._run('pr', 'create', '--repo', ref.full_name, '--base', base, + '--head', head, '--title', title, '--body', body) + if result.returncode != 0: + raise RepositoryError( + f"{ref.full_name} へ PR を作れませんでした: {result.stderr.strip()}\n" + f"ブランチ {head} は GitHub に残っています。" + "消してから同じコマンドを打ち直してください" + ) + return result.stdout.strip().splitlines()[-1] + + def find_open_pr(self, ref: GitHubRef, branch: str) -> Optional[str]: + pulls = self._json('pr', 'list', '--repo', ref.full_name, '--head', branch, + '--state', 'open', '--json', 'url', + what=f"{ref.full_name} の PR の確認") + return pulls[0]['url'] if pulls else None + + def merge_pr(self, ref: GitHubRef, url: str) -> None: + """PR を 1 回だけマージする。CI を待たず、``--auto``・``--admin`` を使わない (決定 4)""" + mergeable = self._wait_mergeable(ref, url) + if mergeable != 'MERGEABLE': + raise RepositoryError(f"マージできる状態ではありません (mergeable: {mergeable})") + result = self._run('pr', 'merge', url, '--repo', ref.full_name, + self._merge_method(ref), '--delete-branch') + if result.returncode != 0: + raise RepositoryError(f"マージに失敗しました: {result.stderr.strip()}") + + def _wait_mergeable(self, ref: GitHubRef, url: str) -> str: + mergeable = 'UNKNOWN' + for attempt in range(_MERGEABLE_POLLS): + if attempt: + time.sleep(_MERGEABLE_POLL_SECONDS) + mergeable = self._json('pr', 'view', url, '--repo', ref.full_name, + '--json', 'mergeable', + what="PR の状態の確認")['mergeable'] + if mergeable != 'UNKNOWN': + break + return mergeable + + def _merge_method(self, ref: GitHubRef) -> str: + allowed = self._json('repo', 'view', ref.full_name, '--json', + ','.join(key for key, _ in _MERGE_METHODS), + what=f"{ref.full_name} のマージの方式の確認") + for key, flag in _MERGE_METHODS: + if allowed.get(key): + return flag + raise RepositoryError(f"{ref.full_name} はどのマージの方式も許していません") diff --git a/tests/plugin/test_github.py b/tests/plugin/test_github.py new file mode 100644 index 00000000..257219b6 --- /dev/null +++ b/tests/plugin/test_github.py @@ -0,0 +1,279 @@ +"""引数の解決 (GitHubRef) と gh の呼び出し (GhClient) のテスト (#514)。""" + +from __future__ import annotations + +import subprocess + +import pytest + +from devbase.errors import RepositoryError +from devbase.plugin import github +from devbase.plugin.github import GhClient, GitHubRef + + +@pytest.mark.parametrize("value, clone_url", [ + ("owner/repo", "https://github.com/owner/repo.git"), + ("https://github.com/owner/repo", "https://github.com/owner/repo.git"), + ("https://github.com/owner/repo/", "https://github.com/owner/repo.git"), + ("https://github.com/owner/repo.git", "https://github.com/owner/repo.git"), + ("git@github.com:owner/repo.git", "git@github.com:owner/repo.git"), + ("git@github.com:owner/repo", "git@github.com:owner/repo.git"), +]) +def test_parse_accepts_every_form(value, clone_url): + ref = GitHubRef.parse(value) + assert (ref.owner, ref.repo) == ("owner", "repo") + assert ref.full_name == "owner/repo" + assert ref.clone_url == clone_url + + +@pytest.mark.parametrize("value", [ + "", + "repo", + "owner/repo/extra", + "https://gitlab.com/owner/repo", + "https://github.com.example.com/owner/repo", + "https://example.com/github.com/owner/repo", + "git@gitlab.com:owner/repo.git", + "ssh://git@github.com/owner/repo.git", + "/local/path", + "./owner/repo", + "-owner/repo", + "owner/-repo", + "owner/..", + "owner/.git", + "own er/repo", +]) +def test_parse_rejects_anything_else(value): + with pytest.raises(RepositoryError): + GitHubRef.parse(value) + + +def _completed(args, returncode=0, stdout="", stderr=""): + return subprocess.CompletedProcess(args, returncode, stdout, stderr) + + +class _Script: + """gh の引数の接頭辞ごとに結果を返す subprocess.run の代役。""" + + def __init__(self, table): + self.table = table + self.calls = [] + + def __call__(self, cmd, **_kwargs): + assert cmd[0] == "gh" + self.calls.append(cmd[1:]) + for prefix, result in self.table: + if cmd[1:len(prefix) + 1] == prefix: + if callable(result): + return result(cmd) + return _completed(cmd, *result) + raise AssertionError(f"unexpected gh call: {cmd}") + + +@pytest.fixture +def client(monkeypatch): + monkeypatch.setattr(github.shutil, "which", lambda name: f"/fake/{name}") + monkeypatch.setattr(github.time, "sleep", lambda _s: None) + + def _make(table): + script = _Script(table) + monkeypatch.setattr(github.subprocess, "run", script) + return GhClient(), script + return _make + + +REF = GitHubRef("owner", "repo", "https://github.com/owner/repo.git") + + +def test_ensure_ready_without_gh_tells_what_to_do(monkeypatch): + monkeypatch.setattr(github.shutil, "which", lambda name: None) + with pytest.raises(RepositoryError, match="gh"): + GhClient().ensure_ready() + + +def test_ensure_ready_unauthenticated_tells_login(client): + gh, _ = client([(["api", "user"], (1, "", "To get started, please run: gh auth login"))]) + with pytest.raises(RepositoryError, match="gh auth login"): + gh.ensure_ready() + + +def test_ensure_ready_ok(client): + gh, script = client([(["api", "user"], (0, '{"login": "me"}'))]) + gh.ensure_ready() + assert gh.login() == "me" + assert len(script.calls) == 1, "login は 1 回だけ問い合わせる" + + +def test_view_repo_missing_is_none(client): + gh, _ = client([(["repo", "view"], (1, "", "GraphQL: Could not resolve to a Repository"))]) + assert gh.view_repo(REF) is None + + +def test_view_repo_other_error_stops(client): + gh, _ = client([(["repo", "view"], (1, "", "connection refused"))]) + with pytest.raises(RepositoryError, match="connection refused"): + gh.view_repo(REF) + + +@pytest.mark.parametrize("permission, can_push", [ + ("ADMIN", True), ("MAINTAIN", True), ("WRITE", True), + ("TRIAGE", False), ("READ", False), ("", False), +]) +def test_view_repo_can_push(client, permission, can_push): + body = ('{"isEmpty": false, "defaultBranchRef": {"name": "main"}, ' + f'"viewerPermission": "{permission}"}}') + gh, _ = client([(["repo", "view"], (0, body))]) + view = gh.view_repo(REF) + assert view.can_push is can_push + assert view.default_branch == "main" + assert view.empty is False + + +def test_view_repo_empty_has_no_default_branch(client): + body = '{"isEmpty": true, "defaultBranchRef": null, "viewerPermission": "ADMIN"}' + gh, _ = client([(["repo", "view"], (0, body))]) + view = gh.view_repo(REF) + assert view.empty is True + assert view.default_branch == "" + + +@pytest.mark.parametrize("owner, membership, org, expected", [ + ("me", None, None, True), + ("ME", None, None, True), + ("team-a", '{"state": "active", "role": "admin"}', None, True), + ("team-a", '{"state": "active", "role": "member"}', + '{"members_can_create_repositories": true}', True), + ("team-a", '{"state": "active", "role": "member"}', + '{"members_can_create_repositories": false}', False), + ("team-a", '{"state": "pending", "role": "admin"}', None, False), + ("team-a", False, None, False), +]) +def test_can_create_in(client, owner, membership, org, expected): + table = [(["api", "user"], (0, '{"login": "me"}'))] + if membership is False: + table.insert(0, (["api", f"user/memberships/orgs/{owner}"], + (1, "", "gh: Not Found (HTTP 404)"))) + elif membership: + table.insert(0, (["api", f"user/memberships/orgs/{owner}"], (0, membership))) + if org: + table.insert(0, (["api", f"orgs/{owner}"], (0, org))) + gh, _ = client(table) + assert gh.can_create_in(owner) is expected + + +def test_read_file_missing_is_none(client): + gh, _ = client([(["api", "repos/owner/repo/contents/registry.yml"], + (1, "", "gh: Not Found (HTTP 404)"))]) + assert gh.read_file(REF, "registry.yml") is None + + +def test_read_file_returns_text(client): + gh, _ = client([(["api", "repos/owner/repo/contents/registry.yml"], (0, "name: x\n"))]) + assert gh.read_file(REF, "registry.yml") == "name: x\n" + + +def test_read_file_other_error_stops(client): + gh, _ = client([(["api", "repos/owner/repo/contents/registry.yml"], + (1, "", "gh: Server Error (HTTP 500)"))]) + with pytest.raises(RepositoryError, match="HTTP 500"): + gh.read_file(REF, "registry.yml") + + +@pytest.mark.parametrize("public, flag", [(False, "--private"), (True, "--public")]) +def test_create_repo_visibility(client, public, flag): + gh, script = client([(["repo", "create"], (0,))]) + gh.create_repo(REF, public=public) + assert script.calls == [["repo", "create", "owner/repo", flag]] + + +def test_create_repo_failure_carries_gh_output(client): + gh, _ = client([(["repo", "create"], (1, "", "Name already exists on this account"))]) + with pytest.raises(RepositoryError, match="Name already exists"): + gh.create_repo(REF, public=False) + + +def test_create_pr_returns_url(client): + gh, script = client([(["pr", "create"], (0, "https://github.com/owner/repo/pull/7\n"))]) + url = gh.create_pr(REF, base="main", head="devbase/new-plugin-x", title="t", body="b") + assert url == "https://github.com/owner/repo/pull/7" + assert script.calls[0][:4] == ["pr", "create", "--repo", "owner/repo"] + + +PR = "https://github.com/owner/repo/pull/7" +ALLOWED_ALL = '{"mergeCommitAllowed": true, "squashMergeAllowed": true, "rebaseMergeAllowed": true}' + + +@pytest.mark.parametrize("allowed, flag", [ + (ALLOWED_ALL, "--merge"), + ('{"mergeCommitAllowed": false, "squashMergeAllowed": true, "rebaseMergeAllowed": true}', + "--squash"), + ('{"mergeCommitAllowed": false, "squashMergeAllowed": false, "rebaseMergeAllowed": true}', + "--rebase"), +]) +def test_merge_pr_picks_the_allowed_method(client, allowed, flag): + gh, script = client([ + (["pr", "view"], (0, '{"mergeable": "MERGEABLE"}')), + (["repo", "view"], (0, allowed)), + (["pr", "merge"], (0,)), + ]) + gh.merge_pr(REF, PR) + merges = [c for c in script.calls if c[:2] == ["pr", "merge"]] + assert merges == [["pr", "merge", PR, "--repo", "owner/repo", flag, "--delete-branch"]] + + +def test_merge_pr_waits_for_unknown_then_merges_once(client): + states = iter(['{"mergeable": "UNKNOWN"}', '{"mergeable": "UNKNOWN"}', + '{"mergeable": "MERGEABLE"}']) + gh, script = client([ + (["pr", "view"], lambda cmd: _completed(cmd, 0, next(states))), + (["repo", "view"], (0, ALLOWED_ALL)), + (["pr", "merge"], (0,)), + ]) + gh.merge_pr(REF, PR) + assert len([c for c in script.calls if c[:2] == ["pr", "merge"]]) == 1 + + +def test_merge_pr_never_uses_auto_or_admin(client): + gh, script = client([ + (["pr", "view"], (0, '{"mergeable": "MERGEABLE"}')), + (["repo", "view"], (0, ALLOWED_ALL)), + (["pr", "merge"], (0,)), + ]) + gh.merge_pr(REF, PR) + used = {arg for call in script.calls for arg in call} + assert not used & {"--auto", "--admin"} + + +def test_merge_pr_gives_up_when_unknown_lasts(client): + gh, script = client([(["pr", "view"], (0, '{"mergeable": "UNKNOWN"}'))]) + with pytest.raises(RepositoryError): + gh.merge_pr(REF, PR) + assert not [c for c in script.calls if c[:2] == ["pr", "merge"]] + + +def test_merge_pr_conflict_stops_without_merging(client): + gh, script = client([(["pr", "view"], (0, '{"mergeable": "CONFLICTING"}'))]) + with pytest.raises(RepositoryError, match="CONFLICTING"): + gh.merge_pr(REF, PR) + assert not [c for c in script.calls if c[:2] == ["pr", "merge"]] + + +def test_merge_pr_failure_is_tried_once(client): + gh, script = client([ + (["pr", "view"], (0, '{"mergeable": "MERGEABLE"}')), + (["repo", "view"], (0, ALLOWED_ALL)), + (["pr", "merge"], (1, "", "base branch policy prohibits the merge")), + ]) + with pytest.raises(RepositoryError, match="base branch policy"): + gh.merge_pr(REF, PR) + assert len([c for c in script.calls if c[:2] == ["pr", "merge"]]) == 1 + + +def test_find_open_pr(client): + gh, _ = client([(["pr", "list"], (0, f'[{{"url": "{PR}"}}]'))]) + assert gh.find_open_pr(REF, "devbase/new-plugin-x") == PR + + +def test_find_open_pr_none(client): + gh, _ = client([(["pr", "list"], (0, "[]"))]) + assert gh.find_open_pr(REF, "devbase/new-plugin-x") is None From 642f121b1964d56dafa91f5a93c76745f4474ccd Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:44:22 +0000 Subject: [PATCH 03/18] =?UTF-8?q?Feat:=20#514=20=E4=BD=9C=E6=88=90?= =?UTF-8?q?=E3=83=95=E3=83=AD=E3=83=BC=E3=81=AE=E9=9B=9B=E5=BD=A2=E3=81=A8?= =?UTF-8?q?=20registry.yml=20=E3=81=B8=E3=81=AE=E8=BF=BD=E8=A8=98=E3=82=92?= =?UTF-8?q?=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/devbase/plugin/scaffold.py | 178 +++++++++++++++++++++++++++++++++ tests/plugin/test_scaffold.py | 149 +++++++++++++++++++++++++++ 2 files changed, 327 insertions(+) create mode 100644 lib/devbase/plugin/scaffold.py create mode 100644 tests/plugin/test_scaffold.py diff --git a/lib/devbase/plugin/scaffold.py b/lib/devbase/plugin/scaffold.py new file mode 100644 index 00000000..6ba560d0 --- /dev/null +++ b/lib/devbase/plugin/scaffold.py @@ -0,0 +1,178 @@ +"""作成フローの雛形の生成と ``registry.yml`` への追記 (#514)。 + +外部へ出ない純粋な処理だけを置く。``registry.yml`` はコメントと引用符を保つため、YAML を +書き戻さず文字列で 1 項目を足し、読み直して確かめる (設計の決定 6・不変条件 I3)。 +""" + +from __future__ import annotations + +from typing import Dict, List, Optional + +import yaml + +from devbase.env import keys +from devbase.errors import RepositoryError + +from .github import GitHubRef + +REGISTRY_FILE = 'registry.yml' + +_PLUGINS_KEY = 'plugins:' +_EMPTY_LIST_VALUE = '[]' + + +def _scalar(value: str) -> str: + """YAML の 1 行のスカラー。``null``・``1.0`` のような名前も文字列のまま読める形にする""" + return yaml.safe_dump(value, default_flow_style=True).splitlines()[0] + + +def registry_yml(name: str) -> str: + return f'name: {_scalar(name)}\ndescription: ""\nplugins: []\n' + + +def plugin_files(name: str) -> Dict[str, str]: + """プラグインのファイル (リポジトリの直下からのパス → 中身)""" + plugin_yml = ( + f'name: {_scalar(name)}\n' + 'version: "1.0.0"\n' + 'description: ""\n' + 'requires:\n' + ' devbase: ">=3.0.0"\n' + 'projects:\n' + ' mode: auto\n' + 'priority: 50\n' + ) + return {f'{name}/plugin.yml': plugin_yml, f'{name}/projects/.gitkeep': ''} + + +def project_files(plugin_path: str, name: str, ref: GitHubRef, group: str) -> Dict[str, str]: + """プロジェクトのファイル (リポジトリの直下からのパス → 中身)""" + project_yml = ( + 'version: 1\n' + 'scale: 1\n' + 'open_editor: true\n' + 'repos:\n' + f' - owner: {_scalar(ref.owner)}\n' + f' repo: {_scalar(ref.repo)}\n' + ) + compose_yml = f"""\ +services: + + dev: + image: {_scalar(name.lower() + ':latest')} + build: + context: ${{DEVBASE_ROOT}}/containers/general/ + dockerfile: Dockerfile + volumes: + - /var/run/docker.sock:/var/run/docker.sock + env_file: + - ${{DEVBASE_ROOT}}/.env + - env + - .env + group_add: ["${{DOCKER_GID}}"] + command: tail -f /dev/null + working_dir: /work + networks: + - devbase_net + +networks: + devbase_net: + external: true +""" + base = f"{plugin_path.rstrip('/')}/projects/{name}" + return { + f'{base}/project.yml': project_yml, + f'{base}/compose.yml': compose_yml, + f'{base}/env': f'{keys.DEVBASE_ACCOUNT_GROUP}={group}\n', + } + + +def add_registry_entry(text: str, name: str) -> str: + """``registry.yml`` の ``plugins`` へ 1 項目を足した文字列を返す。 + + Raises: + RepositoryError: 読めない・足せない形・足した結果が 1 項目の増加にならないとき + """ + before = _load_registry(text) + added = _insert_entry(text, name) + after = _load_registry(added) + expected = dict(before) + expected['plugins'] = list(before.get('plugins') or []) + [ + {'name': name, 'path': name, 'description': ''}] + if after != expected: + raise RepositoryError( + f"{REGISTRY_FILE} へ 1 項目だけを足せませんでした。手で足してください") + return added + + +def _load_registry(text: str) -> dict: + try: + data = yaml.safe_load(text) + except yaml.YAMLError as e: + raise RepositoryError(f"{REGISTRY_FILE} を読めません: {e}") from e + if data is None: + return {} + if not isinstance(data, dict): + raise RepositoryError(f"{REGISTRY_FILE} の直下がマッピングではありません") + return data + + +def _entry_lines(name: str, indent: str) -> List[str]: + return [f'{indent}- name: {_scalar(name)}', + f'{indent} path: {_scalar(name)}', + f'{indent} description: ""'] + + +def _insert_entry(text: str, name: str) -> str: + lines = text.splitlines() + key_index = _find_plugins_key(lines) + if key_index is None: + return '\n'.join([*lines, _PLUGINS_KEY, *_entry_lines(name, ' ')]) + '\n' + + value = _value_of(lines[key_index]) + if value == _EMPTY_LIST_VALUE: + lines[key_index:key_index + 1] = [_PLUGINS_KEY, *_entry_lines(name, ' ')] + return '\n'.join(lines) + '\n' + if value: + raise RepositoryError( + f"{REGISTRY_FILE} の plugins がブロックの形ではないので足せません。手で足してください") + + items = _block_lines(lines, key_index) + if not items: + lines[key_index + 1:key_index + 1] = _entry_lines(name, ' ') + return '\n'.join(lines) + '\n' + first = lines[items[0]] + indent = first[:len(first) - len(first.lstrip())] + lines[items[-1] + 1:items[-1] + 1] = _entry_lines(name, indent) + return '\n'.join(lines) + '\n' + + +def _find_plugins_key(lines: List[str]) -> Optional[int]: + for index, line in enumerate(lines): + if line.startswith(_PLUGINS_KEY): + return index + return None + + +def _value_of(line: str) -> str: + """``plugins:`` の行の値。行末のコメントは外す""" + return line[len(_PLUGINS_KEY):].split(' #', 1)[0].strip() + + +def _is_blank_or_comment(line: str) -> bool: + stripped = line.strip() + return not stripped or stripped.startswith('#') + + +def _block_lines(lines: List[str], key_index: int) -> List[int]: + """``plugins`` のブロックの中身の行番号 (空行とコメントを除く)""" + found = [] + for index in range(key_index + 1, len(lines)): + line = lines[index] + if _is_blank_or_comment(line): + continue + # 列 0 で `-` から始まる行は、字下げの無い列の項目である + if line[0] not in ' \t-': + break + found.append(index) + return found diff --git a/tests/plugin/test_scaffold.py b/tests/plugin/test_scaffold.py new file mode 100644 index 00000000..e34e79ac --- /dev/null +++ b/tests/plugin/test_scaffold.py @@ -0,0 +1,149 @@ +"""雛形の生成と registry.yml への追記のテスト (#514)。""" + +from __future__ import annotations + +import textwrap + +import pytest +import yaml + +from devbase.errors import RepositoryError +from devbase.plugin import scaffold +from devbase.plugin.github import GitHubRef +from devbase.project.config import parse_project_config + +REF = GitHubRef("owner", "app", "https://github.com/owner/app.git") + + +def test_registry_template_has_no_plugins(): + data = yaml.safe_load(scaffold.registry_yml("my-repo")) + assert data == {"name": "my-repo", "description": "", "plugins": []} + + +def test_plugin_files(): + files = scaffold.plugin_files("team-a") + assert set(files) == {"team-a/plugin.yml", "team-a/projects/.gitkeep"} + data = yaml.safe_load(files["team-a/plugin.yml"]) + assert data == { + "name": "team-a", "version": "1.0.0", "description": "", + "requires": {"devbase": ">=3.0.0"}, + "projects": {"mode": "auto"}, "priority": 50, + } + + +def test_project_files(): + files = scaffold.project_files("team-a/", "My-App", REF, "acme") + assert set(files) == { + "team-a/projects/My-App/project.yml", + "team-a/projects/My-App/compose.yml", + "team-a/projects/My-App/env", + } + config = parse_project_config( + yaml.safe_load(files["team-a/projects/My-App/project.yml"]), "project.yml") + assert config.scale == 1 + assert config.open_editor is True + assert config.primary.owner == "owner" + assert config.primary.repo == "app" + + compose = yaml.safe_load(files["team-a/projects/My-App/compose.yml"]) + assert list(compose["services"]) == ["dev"] + dev = compose["services"]["dev"] + assert dev["image"] == "my-app:latest" + assert dev["build"]["context"] == "${DEVBASE_ROOT}/containers/general/" + assert "env" in dev["env_file"] + + assert files["team-a/projects/My-App/env"] == "DEVBASE_ACCOUNT_GROUP=acme\n" + + +@pytest.mark.parametrize("name", ["null", "true", "1.0", "yes", "012"]) +def test_templates_keep_names_as_strings(name): + assert yaml.safe_load(scaffold.registry_yml(name))["name"] == name + assert yaml.safe_load(scaffold.plugin_files(name)[f"{name}/plugin.yml"])["name"] == name + added = scaffold.add_registry_entry("plugins: []\n", name) + assert yaml.safe_load(added)["plugins"][0]["name"] == name + + +def _entries(text): + return yaml.safe_load(text)["plugins"] + + +def test_add_to_empty_flow_list(): + text = scaffold.registry_yml("r") + added = scaffold.add_registry_entry(text, "team-a") + assert _entries(added) == [{"name": "team-a", "path": "team-a", "description": ""}] + assert added.startswith('name: r\n') + + +COMMENTED = textwrap.dedent("""\ + # 社内の説明コメント + name: 'quoted' # 引用符を保つ + plugins: + # 先頭のプラグイン + - name: alpha + path: alpha/ + description: "A" + + # 二つ目 + - name: beta + path: beta + description: B + + maintainer: someone + # 末尾のコメント + """) + + +def test_add_keeps_comments_quotes_and_order(): + added = scaffold.add_registry_entry(COMMENTED, "gamma") + # 既存の行はすべて同じ順で残る + new_lines = added.splitlines() + position = 0 + for line in COMMENTED.splitlines(): + position = new_lines.index(line, position) + 1 + assert len(new_lines) == len(COMMENTED.splitlines()) + 3 + assert [e["name"] for e in _entries(added)] == ["alpha", "beta", "gamma"] + assert yaml.safe_load(added)["maintainer"] == "someone" + # 項目は最後の項目の直後に入る (空行やコメントの後ろへ流れない) + assert new_lines[new_lines.index(" description: B") + 1] == " - name: gamma" + + +def test_add_with_unindented_sequence(): + text = "name: r\nplugins:\n- name: alpha\n path: alpha\n description: ''\n" + added = scaffold.add_registry_entry(text, "beta") + assert [e["name"] for e in _entries(added)] == ["alpha", "beta"] + assert added.splitlines()[-3] == "- name: beta" + + +def test_add_when_key_is_empty(): + assert _entries(scaffold.add_registry_entry("name: r\nplugins:\ndescription: d\n", "x")) == [ + {"name": "x", "path": "x", "description": ""}] + + +def test_add_when_key_is_missing(): + added = scaffold.add_registry_entry("name: r\n", "x") + assert yaml.safe_load(added)["name"] == "r" + assert [e["name"] for e in _entries(added)] == ["x"] + + +def test_add_without_trailing_newline(): + added = scaffold.add_registry_entry("plugins:\n - name: a\n path: a", "b") + assert [e["name"] for e in _entries(added)] == ["a", "b"] + + +def test_add_refuses_flow_list_with_items(): + text = "plugins: [{name: a, path: a}]\n" + with pytest.raises(RepositoryError, match="registry.yml"): + scaffold.add_registry_entry(text, "b") + + +def test_add_refuses_broken_yaml(): + with pytest.raises(RepositoryError, match="registry.yml"): + scaffold.add_registry_entry("plugins: [\n", "b") + + +def test_add_stops_when_the_result_differs(monkeypatch): + """読み直しの検証 (I3): 既存の項目が変わる追記は返さない。""" + monkeypatch.setattr(scaffold, "_insert_entry", + lambda text, name: "plugins:\n - name: other\n path: other\n") + with pytest.raises(RepositoryError, match="registry.yml"): + scaffold.add_registry_entry("plugins:\n - name: a\n path: a\n", "b") From cb1d1c7403f141baa531823f380b9bf410c29ad3 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:46:01 +0000 Subject: [PATCH 04/18] =?UTF-8?q?Feat:=20#514=20=E7=99=BB=E9=8C=B2?= =?UTF-8?q?=E3=81=AE=E7=85=A7=E5=90=88=E3=81=A8=E6=97=A9=E9=80=81=E3=82=8A?= =?UTF-8?q?=E3=81=AE=E5=8F=96=E3=82=8A=E8=BE=BC=E3=81=BF=E3=82=92=E8=B6=B3?= =?UTF-8?q?=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/devbase/plugin/repo_manager.py | 45 ++++++++ tests/plugin/test_repo_manager_creation.py | 122 +++++++++++++++++++++ 2 files changed, 167 insertions(+) create mode 100644 tests/plugin/test_repo_manager_creation.py diff --git a/lib/devbase/plugin/repo_manager.py b/lib/devbase/plugin/repo_manager.py index 63eed41d..d8239394 100644 --- a/lib/devbase/plugin/repo_manager.py +++ b/lib/devbase/plugin/repo_manager.py @@ -179,6 +179,35 @@ def _git_pull(repo_dir: Path) -> None: ) +def _pull_ff_only(repo_dir: Path) -> None: + """既定ブランチの clone を早送りだけで取り込む (#514 の I4・I8)。 + + 既定ブランチ以外・detached HEAD・分岐した clone・作業ツリーの変更とぶつかる取り込みは + 何も変えずに止める。既定ブランチは clone の ``origin/HEAD`` で決める。 + + Raises: + RepositoryError: 早送りで取り込めないとき + """ + current = _run_git(repo_dir, 'branch', '--show-current').stdout.strip() + head = _run_git(repo_dir, 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD') + default = head.stdout.strip().split('/', 1)[-1] if head.returncode == 0 else '' + if not current or (default and current != default): + raise RepositoryError( + f"{repo_dir} は既定ブランチ {default or '(不明)'} ではありません " + f"(今: {current or 'detached HEAD'})。\n" + f"確かめる: git -C {repo_dir} status" + ) + if _run_git(repo_dir, 'rev-parse', '--abbrev-ref', '@{u}').returncode != 0: + raise RepositoryError(str(_missing_upstream_error(repo_dir))) + + result = _run_git(repo_dir, 'pull', '--ff-only') + if result.returncode != 0: + raise RepositoryError( + f"{repo_dir} を早送りで取り込めません: {result.stderr.strip()}\n" + f"確かめる: git -C {repo_dir} status" + ) + + def _log_available_plugins( registry: PluginRegistry, plugins: list[AvailablePlugin], ) -> None: @@ -220,6 +249,22 @@ def _reject_duplicate_registration(registry: PluginRegistry, repo_url: str) -> N ) +def _find_registered( + registry: PluginRegistry, url: str, +) -> Optional[RegisteredRepository]: + """URL の形 (SSH・HTTPS・``.git`` の有無) によらず登録を探す (読むだけ。#514 の決定 9)。 + + 比べ方は ``_reject_duplicate_registration`` と同じで、``add_repository`` が拒否する + ものをここで見つける。 + """ + dirname = _url_to_repos_dirname(url) + return next( + (repo for repo in registry.list_repositories() + if _url_to_repos_dirname(repo.url) == dirname), + None, + ) + + def _resolve_new_repo_name( registry: PluginRegistry, repo_url: str, name: Optional[str], reg_info, ) -> str: diff --git a/tests/plugin/test_repo_manager_creation.py b/tests/plugin/test_repo_manager_creation.py new file mode 100644 index 00000000..117ca46b --- /dev/null +++ b/tests/plugin/test_repo_manager_creation.py @@ -0,0 +1,122 @@ +"""作成フローが足した _find_registered / _pull_ff_only のテスト (#514)。""" + +from __future__ import annotations + +import subprocess + +import pytest + +from devbase.errors import RepositoryError +from devbase.plugin.models import RegisteredRepository +from devbase.plugin.registry import PluginRegistry +from devbase.plugin.repo_manager import _find_registered, _pull_ff_only + + +@pytest.fixture +def registry(tmp_path): + return PluginRegistry(tmp_path) + + +@pytest.mark.parametrize("registered, given", [ + ("https://github.com/owner/repo.git", "https://github.com/owner/repo.git"), + ("https://github.com/owner/repo", "https://github.com/owner/repo.git"), + ("git@github.com:owner/repo.git", "https://github.com/owner/repo.git"), + ("https://github.com/owner/repo.git", "git@github.com:owner/repo.git"), +]) +def test_find_registered_ignores_the_url_form(registry, registered, given): + registry.add_repository(RegisteredRepository(name="r", url=registered)) + found = _find_registered(registry, given) + assert found is not None + assert found.url == registered + + +def test_find_registered_none(registry): + registry.add_repository(RegisteredRepository( + name="r", url="https://github.com/owner/other.git")) + assert _find_registered(registry, "https://github.com/owner/repo.git") is None + assert _find_registered(registry, "https://gitlab.com/owner/other.git") is None + + +def _git(cwd, *args): + return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", + *args], cwd=str(cwd), check=True, capture_output=True, text=True) + + +@pytest.fixture +def remote_and_clone(tmp_path): + """origin と、その clone と、origin へ push する別の clone の組。""" + origin = tmp_path / "origin.git" + subprocess.run(["git", "init", "--bare", "-b", "main", str(origin)], + check=True, capture_output=True) + writer = tmp_path / "writer" + subprocess.run(["git", "clone", str(origin), str(writer)], check=True, capture_output=True) + _git(writer, "checkout", "-b", "main") + (writer / "a.txt").write_text("1\n") + _git(writer, "add", "-A") + _git(writer, "commit", "-m", "one") + _git(writer, "push", "origin", "main") + clone = tmp_path / "clone" + subprocess.run(["git", "clone", str(origin), str(clone)], check=True, capture_output=True) + return writer, clone + + +def _advance(writer, name="b.txt"): + (writer / name).write_text("new\n") + _git(writer, "add", "-A") + _git(writer, "commit", "-m", "two") + _git(writer, "push", "origin", "main") + + +def test_pull_ff_only_advances(remote_and_clone): + writer, clone = remote_and_clone + _advance(writer) + _pull_ff_only(clone) + assert (clone / "b.txt").is_file() + + +def test_pull_ff_only_keeps_uncommitted_changes(remote_and_clone): + writer, clone = remote_and_clone + _advance(writer) + (clone / "a.txt").write_text("edited\n") + (clone / "note.txt").write_text("untracked\n") + _pull_ff_only(clone) + assert (clone / "b.txt").is_file() + assert (clone / "a.txt").read_text() == "edited\n" + assert (clone / "note.txt").read_text() == "untracked\n" + + +def test_pull_ff_only_stops_when_changes_collide(remote_and_clone): + writer, clone = remote_and_clone + _advance(writer, "note.txt") + (clone / "note.txt").write_text("mine\n") + with pytest.raises(RepositoryError, match="status"): + _pull_ff_only(clone) + assert (clone / "note.txt").read_text() == "mine\n" + + +def test_pull_ff_only_stops_when_diverged(remote_and_clone): + writer, clone = remote_and_clone + _advance(writer) + (clone / "c.txt").write_text("local\n") + _git(clone, "add", "-A") + _git(clone, "commit", "-m", "local") + head = _git(clone, "rev-parse", "HEAD").stdout + with pytest.raises(RepositoryError): + _pull_ff_only(clone) + assert _git(clone, "rev-parse", "HEAD").stdout == head, "マージコミットを作らない" + + +def test_pull_ff_only_stops_on_other_branch(remote_and_clone): + writer, clone = remote_and_clone + _advance(writer) + _git(clone, "checkout", "-b", "work") + with pytest.raises(RepositoryError, match="work"): + _pull_ff_only(clone) + assert not (clone / "b.txt").exists() + + +def test_pull_ff_only_stops_on_detached_head(remote_and_clone): + _, clone = remote_and_clone + _git(clone, "checkout", "--detach") + with pytest.raises(RepositoryError): + _pull_ff_only(clone) From 858405a63c1cf9ee0445b700142a47fb6b03b291 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:47:28 +0000 Subject: [PATCH 05/18] =?UTF-8?q?Feat:=20#514=20=E4=B8=80=E6=99=82?= =?UTF-8?q?=E3=81=AE=20clone=20=E3=81=8B=E3=82=89=E6=97=A2=E5=AE=9A?= =?UTF-8?q?=E3=83=96=E3=83=A9=E3=83=B3=E3=83=81=E3=81=B8=E5=8F=8D=E6=98=A0?= =?UTF-8?q?=E3=81=99=E3=82=8B=E5=87=A6=E7=90=86=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/devbase/plugin/publish.py | 134 +++++++++++++ tests/plugin/conftest.py | 49 +++++ tests/plugin/creation_harness.py | 314 +++++++++++++++++++++++++++++++ tests/plugin/test_publish.py | 93 +++++++++ 4 files changed, 590 insertions(+) create mode 100644 lib/devbase/plugin/publish.py create mode 100644 tests/plugin/conftest.py create mode 100644 tests/plugin/creation_harness.py create mode 100644 tests/plugin/test_publish.py diff --git a/lib/devbase/plugin/publish.py b/lib/devbase/plugin/publish.py new file mode 100644 index 00000000..1826bf09 --- /dev/null +++ b/lib/devbase/plugin/publish.py @@ -0,0 +1,134 @@ +"""一時の浅い clone から既定ブランチへ変更を入れる (#514 の E6・E7)。 + +手元の ``repos/`` の clone には触らない。未登録のリポジトリには手元の clone が無く、登録済みの +clone には利用者の変更があるので、どちらも一時の clone で同じ手順にする (設計の決定 1)。 +既定ブランチへの直接の push は、空のリポジトリの最初のコミットだけである (不変条件 I7)。 +""" + +from __future__ import annotations + +import tempfile +from pathlib import Path +from typing import Dict, Optional + +from devbase.errors import RepositoryError +from devbase.log import get_logger + +from . import scaffold +from .github import GhClient, GitHubRef +from .installer import git_clone +from .repo_manager import _run_git + +logger = get_logger("devbase.plugin.publish") + +_PR_BODY = "devbase の作成フローが足しました。" + + +class MergeFailed(RepositoryError): + """PR を作ったがマージできなかった。``pr_url`` に PR が残っている""" + + def __init__(self, message: str, pr_url: str): + super().__init__(message) + self.pr_url = pr_url + + +def branch_name(kind: str, name: str) -> str: + return f"devbase/new-{kind}-{name}" + + +def pr_title(kind: str, name: str) -> str: + return f"devbase: {kind} {name} を足す" + + +def _git(clone: Path, *args: str) -> str: + result = _run_git(clone, *args) + if result.returncode != 0: + raise RepositoryError(f"git {args[0]} に失敗しました: {result.stderr.strip()}") + return result.stdout.strip() + + +def _write_files(clone: Path, files: Dict[str, str]) -> None: + for relative, text in files.items(): + target = clone / relative + if target.exists(): + raise RepositoryError(f"{relative} は既にあります。上書きしません") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text) + + +def _add_to_registry(clone: Path, name: str) -> None: + path = clone / scaffold.REGISTRY_FILE + path.write_text(scaffold.add_registry_entry(path.read_text(), name)) + + +def _commit(clone: Path, title: str) -> None: + _git(clone, 'add', '-A') + _git(clone, 'commit', '-m', title) + + +def push_initial(ref: GitHubRef, files: Dict[str, str], *, title: str) -> None: + """空のリポジトリへ最初のコミットを入れる (GitHub は空のリポジトリに PR を作れない)""" + with tempfile.TemporaryDirectory(prefix='devbase-publish-') as tmp: + clone = Path(tmp) / 'repo' + git_clone(ref.clone_url, clone) + branch = _git(clone, 'symbolic-ref', '--short', 'HEAD') + _write_files(clone, files) + _commit(clone, title) + _git(clone, 'push', 'origin', f'HEAD:refs/heads/{branch}') + logger.info("最初のコミットを入れました: %s (%s)", ref.full_name, branch) + + +def _reject_existing_branch(gh: GhClient, ref: GitHubRef, clone: Path, branch: str) -> None: + if _run_git(clone, 'ls-remote', '--exit-code', '--heads', 'origin', branch).returncode != 0: + return + url = gh.find_open_pr(ref, branch) + if url: + raise RepositoryError( + f"ブランチ {branch} と開いている PR が既にあります: {url}\n" + "PR を片付けてから同じコマンドを打ち直してください" + ) + raise RepositoryError( + f"ブランチ {branch} が {ref.full_name} に既にあります。" + "消してから同じコマンドを打ち直してください" + ) + + +def publish_change( + gh: GhClient, + ref: GitHubRef, + *, + kind: str, + name: str, + files: Dict[str, str], + registry_entry: Optional[str] = None, +) -> str: + """ブランチへ変更を push し、PR を作ってマージする。PR の URL を返す。 + + ``registry_entry`` があれば ``registry.yml`` へその名前の項目を足す。 + + Raises: + MergeFailed: PR を作ったがマージできなかったとき + """ + branch = branch_name(kind, name) + title = pr_title(kind, name) + with tempfile.TemporaryDirectory(prefix='devbase-publish-') as tmp: + clone = Path(tmp) / 'repo' + git_clone(ref.clone_url, clone) + base = _git(clone, 'branch', '--show-current') + _reject_existing_branch(gh, ref, clone, branch) + _git(clone, 'checkout', '-b', branch) + _write_files(clone, files) + if registry_entry is not None: + _add_to_registry(clone, registry_entry) + _commit(clone, title) + _git(clone, 'push', 'origin', f'{branch}:refs/heads/{branch}') + logger.info("ブランチを push しました: %s", branch) + + url = gh.create_pr(ref, base=base, head=branch, title=title, body=_PR_BODY) + logger.info("PR を作りました: %s", url) + try: + gh.merge_pr(ref, url) + except RepositoryError as e: + raise MergeFailed(f"{url} をマージできませんでした: {e}", url) from e + logger.info("PR をマージしました: %s", url) + return url diff --git a/tests/plugin/conftest.py b/tests/plugin/conftest.py new file mode 100644 index 00000000..ef790d52 --- /dev/null +++ b/tests/plugin/conftest.py @@ -0,0 +1,49 @@ +"""作成フローのテストの fixture (#514)。""" + +from __future__ import annotations + +import builtins +import os +import sys + +import pytest + +from devbase import cli + +from .creation_harness import FakeGitHub + + +@pytest.fixture +def github(tmp_path, monkeypatch): + """偽の gh を PATH の先頭に置き、git の URL を手元の bare リポジトリへ向ける。""" + world = FakeGitHub(tmp_path / "world") + monkeypatch.setenv("PATH", f"{world.bin}{os.pathsep}{os.environ['PATH']}") + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(world.gitconfig)) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + return world + + +@pytest.fixture +def root(tmp_path, monkeypatch): + """一時の devbase のルート。""" + path = tmp_path / "root" + (path / "projects").mkdir(parents=True) + monkeypatch.setenv("DEVBASE_ROOT", str(path)) + return path + + +@pytest.fixture +def run_cli(root, github, monkeypatch): + """devbase の CLI を同じプロセスで打つ。``tty`` と ``answers`` で端末を再現する。""" + def _run(*argv, tty=False, answers=()): + pending = list(answers) + + def _input(_prompt=""): + assert tty, "TTY が無いのに入力を求めた" + return pending.pop(0) + + monkeypatch.setattr(sys, "argv", ["devbase", *argv]) + monkeypatch.setattr(sys.stdin, "isatty", lambda: tty, raising=False) + monkeypatch.setattr(builtins, "input", _input) + return cli.main() + return _run diff --git a/tests/plugin/creation_harness.py b/tests/plugin/creation_harness.py new file mode 100644 index 00000000..6a17fbc4 --- /dev/null +++ b/tests/plugin/creation_harness.py @@ -0,0 +1,314 @@ +"""作成フローのテストの土台: 偽の ``gh`` と手元の bare リポジトリ (#514)。 + +実の GitHub へ触らない。``git`` は本物を使い、``https://github.com/`` と +``git@github.com:`` を ``url..insteadOf`` で手元の bare リポジトリへ向ける。``gh`` は +PATH の先頭に置いたこのファイル自身で、状態は ``state.json`` に持つ。 +``python creation_harness.py `` で偽の ``gh`` として動く。 +""" + +from __future__ import annotations + +import json +import os +import stat +import subprocess +import sys +from pathlib import Path + +GIT = ['git', '-c', 'protocol.file.allow=always'] + + +def _bare_git(bare, *args, check=True): + return subprocess.run([*GIT, '--git-dir', str(bare), *args], capture_output=True, + text=True, check=check) + + +def init_bare(world: Path, full_name: str) -> Path: + bare = world / 'git' / f'{full_name}.git' + bare.parent.mkdir(parents=True, exist_ok=True) + subprocess.run(['git', 'init', '--bare', '-q', '-b', 'main', str(bare)], check=True) + hook = bare / 'hooks' / 'post-receive' + hook.write_text(f'#!/bin/sh\ncat >> "{world}/pushes-{full_name.replace("/", "--")}.log"\n') + hook.chmod(hook.stat().st_mode | stat.S_IEXEC) + return bare + + +# ── 偽の gh ───────────────────────────────────────────────────── + + +class _Fail(Exception): + pass + + +def _option(argv, name, default=None): + return argv[argv.index(name) + 1] if name in argv else default + + +def _repo_entry(state, full_name): + entry = state['repos'].get(full_name) + if entry is None or entry.get('hidden'): + raise _Fail(f"GraphQL: Could not resolve to a Repository with the name '{full_name}'.") + return entry + + +def _gh_api(world, state, argv): + path = argv[0] + if path == 'user': + return json.dumps({'login': state['user']}) + if path.startswith('user/memberships/orgs/'): + org = state['orgs'].get(path.rsplit('/', 1)[-1]) + if org is None: + raise _Fail('gh: Not Found (HTTP 404)') + return json.dumps({'state': org['state'], 'role': org['role']}) + if path.startswith('orgs/'): + org = state['orgs'].get(path.split('/', 1)[1]) + if org is None: + raise _Fail('gh: Not Found (HTTP 404)') + return json.dumps({ + 'members_can_create_repositories': org.get('members_can_create_repositories')}) + if path.startswith('repos/'): + _, owner, repo, _, file_path = path.split('/', 4) + bare = world / 'git' / owner / f'{repo}.git' + found = _bare_git(bare, 'show', f'HEAD:{file_path}', check=False) + if found.returncode != 0: + raise _Fail('gh: Not Found (HTTP 404)') + return found.stdout + raise _Fail(f'unexpected api path: {path}') + + +def _gh_repo_view(world, state, argv): + full_name = argv[0] + entry = _repo_entry(state, full_name) + bare = world / 'git' / f'{full_name}.git' + has_commits = bool(_bare_git(bare, 'for-each-ref', 'refs/heads').stdout.strip()) + allowed = entry.get('merge_methods', ['merge', 'squash', 'rebase']) + values = { + 'isEmpty': not has_commits, + 'defaultBranchRef': {'name': 'main'} if has_commits else None, + 'viewerPermission': entry.get('permission', 'ADMIN'), + 'mergeCommitAllowed': 'merge' in allowed, + 'squashMergeAllowed': 'squash' in allowed, + 'rebaseMergeAllowed': 'rebase' in allowed, + } + return json.dumps({k: values[k] for k in _option(argv, '--json').split(',')}) + + +def _gh_repo_create(world, state, argv): + full_name = argv[0] + if full_name in state['repos']: + raise _Fail('GraphQL: Name already exists on this account (createRepository)') + state['repos'][full_name] = { + 'permission': 'ADMIN', + 'visibility': 'public' if '--public' in argv else 'private', + } + init_bare(world, full_name) + return f'https://github.com/{full_name}' + + +def _gh_pr_create(world, state, argv): + full_name = _option(argv, '--repo') + if state['repos'][full_name].get('pr_error'): + raise _Fail(state['repos'][full_name]['pr_error']) + number = len(state['prs']) + 1 + url = f'https://github.com/{full_name}/pull/{number}' + state['prs'].append({ + 'url': url, 'repo': full_name, 'base': _option(argv, '--base'), + 'head': _option(argv, '--head'), 'title': _option(argv, '--title'), 'state': 'OPEN', + }) + return url + + +def _find_pr(state, url): + return next(pr for pr in state['prs'] if pr['url'] == url) + + +def _gh_pr_view(state, argv): + entry = state['repos'][_option(argv, '--repo')] + return json.dumps({'mergeable': entry.get('mergeable', 'MERGEABLE')}) + + +def _gh_pr_merge(world, state, argv): + pr = _find_pr(state, argv[0]) + entry = state['repos'][pr['repo']] + if entry.get('merge_error'): + raise _Fail(entry['merge_error']) + bare = world / 'git' / f"{pr['repo']}.git" + head = _bare_git(bare, 'rev-parse', f"refs/heads/{pr['head']}").stdout.strip() + _bare_git(bare, 'update-ref', f"refs/heads/{pr['base']}", head) + if '--delete-branch' in argv: + _bare_git(bare, 'update-ref', '-d', f"refs/heads/{pr['head']}") + pr['state'] = 'MERGED' + return '' + + +def _gh_pr_list(state, argv): + head = _option(argv, '--head') + return json.dumps([{'url': pr['url']} for pr in state['prs'] + if pr['head'] == head and pr['state'] == 'OPEN']) + + +def _gh(world, state, argv): + if not state['authed']: + raise _Fail('To get started with GitHub CLI, please run: gh auth login') + group, rest = argv[0], argv[1:] + if group == 'api': + return _gh_api(world, state, rest) + action, rest = rest[0], rest[1:] + handlers = { + ('repo', 'view'): lambda: _gh_repo_view(world, state, rest), + ('repo', 'create'): lambda: _gh_repo_create(world, state, rest), + ('pr', 'create'): lambda: _gh_pr_create(world, state, rest), + ('pr', 'view'): lambda: _gh_pr_view(state, rest), + ('pr', 'merge'): lambda: _gh_pr_merge(world, state, rest), + ('pr', 'list'): lambda: _gh_pr_list(state, rest), + } + return handlers[(group, action)]() + + +def _gh_main(argv): + world = Path(argv[0]) + args = argv[1:] + with open(world / 'calls.jsonl', 'a') as f: + f.write(json.dumps(args) + '\n') + state = json.loads((world / 'state.json').read_text()) + try: + out = _gh(world, state, args) + except _Fail as e: + print(str(e), file=sys.stderr) + return 1 + (world / 'state.json').write_text(json.dumps(state)) + print(out) + return 0 + + +# ── テストから使う側 ──────────────────────────────────────────── + + +WRITE_CALLS = (('repo', 'create'), ('pr', 'create'), ('pr', 'merge')) + + +class FakeGitHub: + def __init__(self, world: Path): + self.world = world + self.bin = world / 'bin' + self.bin.mkdir(parents=True) + self.update(user='me', authed=True, orgs={}, repos={}, prs=[]) + shim = self.bin / 'gh' + shim.write_text( + f'#!/bin/sh\nexec "{sys.executable}" "{__file__}" "{world}" "$@"\n') + shim.chmod(0o755) + for tool in ('docker', 'docker-compose'): + spy = self.bin / tool + spy.write_text(f'#!/bin/sh\necho "{tool} $*" >> "{world}/docker.log"\n') + spy.chmod(0o755) + self.gitconfig = world / 'gitconfig' + self.gitconfig.write_text( + '[user]\n\tname = tester\n\temail = tester@example.com\n' + '[init]\n\tdefaultBranch = main\n' + '[protocol "file"]\n\tallow = always\n' + f'[url "file://{world}/git/"]\n' + '\tinsteadOf = https://github.com/\n' + '\tinsteadOf = git@github.com:\n' + ) + + # 状態 + @property + def _state_file(self): + return self.world / 'state.json' + + def state(self) -> dict: + return json.loads(self._state_file.read_text()) + + def update(self, **values) -> None: + state = self.state() if self._state_file.exists() else {} + state.update(values) + self._state_file.write_text(json.dumps(state)) + + def update_repo(self, full_name: str, **values) -> None: + state = self.state() + state['repos'][full_name].update(values) + self._state_file.write_text(json.dumps(state)) + + def add_org(self, name, *, state='active', role='member', can_create=False): + orgs = self.state()['orgs'] + orgs[name] = {'state': state, 'role': role, + 'members_can_create_repositories': can_create} + self.update(orgs=orgs) + + def add_repo(self, full_name: str, files=None, **values) -> Path: + """``files`` が空なら空のリポジトリを作る。""" + state = self.state() + state['repos'][full_name] = {'permission': 'ADMIN', **values} + self._state_file.write_text(json.dumps(state)) + bare = init_bare(self.world, full_name) + if files: + self.commit(full_name, files, message='seed') + pushes = self.world / f'pushes-{full_name.replace("/", "--")}.log' + pushes.unlink(missing_ok=True) + return bare + + def commit(self, full_name: str, files: dict, message='change') -> None: + """既定ブランチへ別の人が入れたコミットを作る。""" + bare = self.world / 'git' / f'{full_name}.git' + work = self.world / 'seed' + env = {**os.environ, 'GIT_CONFIG_GLOBAL': str(self.gitconfig)} + subprocess.run([*GIT, 'clone', '-q', str(bare), str(work)], check=True, env=env, + capture_output=True) + subprocess.run(['git', 'checkout', '-q', '-B', 'main'], cwd=work, check=True, env=env) + for path, text in files.items(): + target = work / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text) + subprocess.run(['git', 'add', '-A'], cwd=work, check=True, env=env) + subprocess.run(['git', 'commit', '-q', '-m', message], cwd=work, check=True, env=env) + subprocess.run([*GIT, 'push', '-q', 'origin', 'main'], cwd=work, check=True, env=env, + capture_output=True) + subprocess.run(['rm', '-rf', str(work)], check=True) + + # 観察 + def calls(self) -> list: + path = self.world / 'calls.jsonl' + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text().splitlines()] + + def write_calls(self) -> list: + return [c for c in self.calls() if tuple(c[:2]) in WRITE_CALLS] + + def docker_calls(self) -> list: + path = self.world / 'docker.log' + return path.read_text().splitlines() if path.exists() else [] + + def exists(self, full_name: str) -> bool: + return (self.world / 'git' / f'{full_name}.git').is_dir() + + def _bare(self, full_name): + return self.world / 'git' / f'{full_name}.git' + + def file(self, full_name: str, path: str): + found = _bare_git(self._bare(full_name), 'show', f'HEAD:{path}', check=False) + return found.stdout if found.returncode == 0 else None + + def subjects(self, full_name: str) -> list: + """既定ブランチのコミットの題 (古い順)。""" + out = _bare_git(self._bare(full_name), 'log', '--reverse', '--format=%s', 'HEAD').stdout + return out.splitlines() + + def branches(self, full_name: str) -> list: + out = _bare_git(self._bare(full_name), 'for-each-ref', '--format=%(refname:short)', + 'refs/heads').stdout + return out.splitlines() + + def pushed_refs(self, full_name: str) -> list: + """push された ref (順)。マージは含まない。""" + path = self.world / f'pushes-{full_name.replace("/", "--")}.log' + if not path.exists(): + return [] + return [line.split()[2] for line in path.read_text().splitlines()] + + def prs(self) -> list: + return self.state()['prs'] + + +if __name__ == '__main__': + sys.exit(_gh_main(sys.argv[1:])) diff --git a/tests/plugin/test_publish.py b/tests/plugin/test_publish.py new file mode 100644 index 00000000..6c91688a --- /dev/null +++ b/tests/plugin/test_publish.py @@ -0,0 +1,93 @@ +"""一時の clone から既定ブランチへ反映する処理のテスト (#514)。""" + +from __future__ import annotations + +import tempfile +from pathlib import Path + +import pytest +import yaml + +from devbase.errors import RepositoryError +from devbase.plugin import publish +from devbase.plugin.github import GhClient, GitHubRef + +REF = GitHubRef("owner", "repo", "https://github.com/owner/repo.git") +FULL = "owner/repo" +REGISTRY = {"registry.yml": "name: repo\nplugins: []\n"} + + +@pytest.fixture +def gh(github): + return GhClient() + + +def _temp_leftovers(tmp_path, monkeypatch): + monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) + return lambda: [p.name for p in Path(tmp_path).iterdir() if p.name.startswith("devbase-")] + + +def test_push_initial_goes_directly_to_the_default_branch(github, tmp_path, monkeypatch): + leftovers = _temp_leftovers(tmp_path, monkeypatch) + github.add_repo(FULL) + publish.push_initial(REF, {"registry.yml": "name: repo\n"}, title="devbase: repo repo を足す") + assert github.file(FULL, "registry.yml") == "name: repo\n" + assert github.pushed_refs(FULL) == ["refs/heads/main"] + assert github.prs() == [] + assert leftovers() == [] + + +def test_publish_change_opens_and_merges_a_pr(github, gh, tmp_path, monkeypatch): + leftovers = _temp_leftovers(tmp_path, monkeypatch) + github.add_repo(FULL, REGISTRY) + url = publish.publish_change(gh, REF, kind="plugin", name="team-a", + files={"team-a/plugin.yml": "name: team-a\n"}, + registry_entry="team-a") + pr = github.prs()[0] + assert pr["url"] == url + assert pr["head"] == "devbase/new-plugin-team-a" + assert pr["base"] == "main" + assert pr["title"] == "devbase: plugin team-a を足す" + assert pr["state"] == "MERGED" + assert github.pushed_refs(FULL) == ["refs/heads/devbase/new-plugin-team-a"], \ + "既定ブランチへ直接 push しない (I7)" + assert github.branches(FULL) == ["main"], "作業用のブランチが残らない" + assert leftovers() == [], "作業場所が残らない" + assert github.file(FULL, "team-a/plugin.yml") == "name: team-a\n" + assert [e["name"] for e in yaml.safe_load(github.file(FULL, "registry.yml"))["plugins"]] \ + == ["team-a"] + + +def test_publish_change_refuses_to_overwrite(github, gh): + github.add_repo(FULL, {**REGISTRY, "team-a/plugin.yml": "mine\n"}) + with pytest.raises(RepositoryError, match="team-a/plugin.yml"): + publish.publish_change(gh, REF, kind="plugin", name="team-a", + files={"team-a/plugin.yml": "new\n"}) + assert github.write_calls() == [] + assert github.pushed_refs(FULL) == [] + + +def test_publish_change_stops_at_an_existing_branch_with_pr(github, gh): + github.add_repo(FULL, REGISTRY) + publish_branch = "devbase/new-plugin-team-a" + github.update_repo(FULL, merge_error="blocked") + with pytest.raises(publish.MergeFailed): + publish.publish_change(gh, REF, kind="plugin", name="team-a", + files={"team-a/plugin.yml": "x\n"}) + assert publish_branch in github.branches(FULL) + url = github.prs()[0]["url"] + + with pytest.raises(RepositoryError, match=url): + publish.publish_change(gh, REF, kind="plugin", name="team-a", + files={"team-a/plugin.yml": "x\n"}) + assert len(github.prs()) == 1 + + +def test_publish_change_merge_failure_keeps_pr_url(github, gh): + github.add_repo(FULL, REGISTRY) + github.update_repo(FULL, merge_error="base branch policy prohibits the merge") + with pytest.raises(publish.MergeFailed) as e: + publish.publish_change(gh, REF, kind="plugin", name="team-a", + files={"team-a/plugin.yml": "x\n"}) + assert e.value.pr_url == github.prs()[0]["url"] + assert "base branch policy" in str(e.value) From 9dececee8144aca774db2888b3cb100d932aedf8 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:49:00 +0000 Subject: [PATCH 06/18] =?UTF-8?q?Feat:=20#514=20devbase=20plugin=20repo=20?= =?UTF-8?q?new=20=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/devbase/cli.py | 20 ++- lib/devbase/commands/plugin.py | 49 +++++- lib/devbase/plugin/creator.py | 193 ++++++++++++++++++++++ tests/plugin/test_create_repo.py | 267 +++++++++++++++++++++++++++++++ 4 files changed, 527 insertions(+), 2 deletions(-) create mode 100644 lib/devbase/plugin/creator.py create mode 100644 tests/plugin/test_create_repo.py diff --git a/lib/devbase/cli.py b/lib/devbase/cli.py index f6aaad53..ae37f8be 100644 --- a/lib/devbase/cli.py +++ b/lib/devbase/cli.py @@ -669,6 +669,17 @@ def _add_env_import_parser(env_sub): help='Keep only the last N backup directories (default: 10, 0 to disable)') +def _add_new_target_arg(parser): + """作成フロー (#514) の共通の引数。GitHub のリポジトリを 1 つ取る。""" + parser.add_argument('repo', help='GitHub URL or owner/repo') + + +def _add_yes_arg(parser): + """作成フロー (#514) の確認を省く ``--yes``。TTY が無いときは必須。""" + parser.add_argument('--yes', action='store_true', + help='Proceed without confirming the plan (required without a TTY)') + + def _add_plugin_parser(subparsers): """Plugin group parser""" pl_parser = subparsers.add_parser('plugin', aliases=['pl'], @@ -704,6 +715,13 @@ def _add_plugin_parser(subparsers): pl_repo = pl_sub.add_parser('repo', help='Manage plugin repositories') pl_repo_sub = pl_repo.add_subparsers(dest='repo_command') + r_new = pl_repo_sub.add_parser( + 'new', help='Create (if needed) and register a plugin repository on GitHub') + _add_new_target_arg(r_new) + r_new.add_argument('--public', action='store_true', + help='Make the repository public when it is created (default: private)') + _add_yes_arg(r_new) + r_add = pl_repo_sub.add_parser('add', help='Register a repository') r_add.add_argument('url', help='Repository URL or GitHub shorthand') r_add.add_argument('--name', default=None, help='Custom name') @@ -882,7 +900,7 @@ def _expand_argv(): commands = ['init', 'status', 'project', 'container', 'ct', 'env', 'plugin', 'pl', 'snapshot', 'ss', 'up', 'down', 'login', 'ps', 'scale', 'rebuild', 'open', 'list', 'help'] - repo_subcmds = ['add', 'remove', 'list', 'refresh'] + repo_subcmds = ['new', 'add', 'remove', 'list', 'refresh'] if len(sys.argv) >= 2 and not sys.argv[1].startswith('-'): sys.argv[1] = _resolve_prefix(sys.argv[1], commands, TOP_PREFIX_PREFERENCES) diff --git a/lib/devbase/commands/plugin.py b/lib/devbase/commands/plugin.py index 1cdfb21a..3d25090e 100644 --- a/lib/devbase/commands/plugin.py +++ b/lib/devbase/commands/plugin.py @@ -1,9 +1,12 @@ """Plugin management CLI commands""" +import sys from pathlib import Path from devbase.errors import DevbaseError from devbase.log import get_logger +from devbase.plugin import creator +from devbase.plugin.github import GhClient from devbase.plugin.registry import PluginRegistry from devbase.plugin.installer import install_plugin, uninstall_plugin from devbase.plugin.updater import update_plugin @@ -168,15 +171,59 @@ def cmd_plugin_migrate(devbase_root: Path) -> int: return 0 +def run_creation(registry, gh, plan, yes: bool) -> int: + """作成の計画を示して確認を取り、実行する (#514 の E4 以降)""" + if plan.noop_reason: + logger.info("%s", plan.noop_reason) + return 0 + + print(plan.describe()) + if not yes and not _confirmed(): + return 1 + creator.execute(registry, gh, plan) + return 0 + + +def _confirmed() -> bool: + """TTY で確認を取る。TTY が無ければ ``--yes`` を求めて断る""" + if not sys.stdin.isatty(): + logger.error("確認できる端末がありません。この計画で進めるなら --yes を付けて打ってください") + return False + try: + answer = input("この計画で進めますか? [y/N]: ") + except (EOFError, KeyboardInterrupt): + answer = '' + if answer.strip().lower() in ('y', 'yes'): + return True + logger.info("中止しました。何も変えていません") + return False + + +def cmd_repo_new(devbase_root: Path, args) -> int: + """`plugin repo new`: プラグインリポジトリを用意して登録する""" + registry = PluginRegistry(devbase_root) + gh = GhClient() + try: + plan = creator.plan_repo(registry, gh, args.repo, + public=getattr(args, 'public', False)) + return run_creation(registry, gh, plan, getattr(args, 'yes', False)) + except DevbaseError as e: + logger.error("%s", e) + return 1 + + def cmd_repo(devbase_root: Path, args) -> int: """Dispatch repo subcommands""" registry = PluginRegistry(devbase_root) repo_cmd = getattr(args, 'repo_command', None) if not repo_cmd: - logger.error("Usage: devbase plugin repo ") + logger.error("Usage: devbase plugin repo ") return 1 + if repo_cmd == 'new': + return cmd_repo_new(devbase_root, args) + handlers = { 'add': lambda: add_repository(registry, args.url, name=args.name), 'remove': lambda: remove_repository(registry, args.name, diff --git a/lib/devbase/plugin/creator.py b/lib/devbase/plugin/creator.py new file mode 100644 index 00000000..ff56dd62 --- /dev/null +++ b/lib/devbase/plugin/creator.py @@ -0,0 +1,193 @@ +"""作成フロー: リポジトリ・プラグイン・プロジェクトを足す一連の操作 (#514)。 + +``plan_*`` は読むだけで、書き込みの前に作成の計画を確定する (不変条件 I1)。``execute`` が +GitHub と手元へ書く。手元の登録は、既定ブランチへ入れる変更がすべて反映された後に既存の +``add_repository``・``install_plugin``・``refresh_repository`` で行う (不変条件 I2・決定 2・ +決定 8)。``devbase up`` は実行しない (不変条件 I6)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import Enum +from typing import Dict, List, Optional + +from devbase.errors import DevbaseError, RepositoryError +from devbase.log import get_logger + +from . import publish, scaffold +from .github import GhClient, GitHubRef +from .installer import install_plugin +from .models import RegisteredRepository +from .registry import PluginRegistry +from .repo_manager import ( + _find_registered, + _pull_ff_only, + _url_to_repos_dirname, + add_repository, + refresh_repository, +) + +logger = get_logger("devbase.plugin.creator") + +KIND_REPO = 'repo' + + +class RepoState(Enum): + """対象のリポジトリの状態 (設計の「引数の解決と分岐」)""" + ABSENT = 'absent' + EMPTY = 'empty' + NO_REGISTRY = 'no-registry' + HAS_REGISTRY = 'has-registry' + + +@dataclass(frozen=True) +class CreationPlan: + """作成の計画: 作るもの・ファイル・マージ先の組""" + kind: str + ref: GitHubRef + name: str + state: RepoState + default_branch: str = '' + public: bool = False + registered: Optional[RegisteredRepository] = None + files: Dict[str, str] = field(default_factory=dict) + registry_entry: Optional[str] = None + #: 空でなければ何もしないで終わる。その理由 + noop_reason: str = '' + + @property + def writes_github(self) -> bool: + return self.kind != KIND_REPO or self.state is not RepoState.HAS_REGISTRY + + def describe(self) -> str: + """利用者へ示す計画の文面""" + target = self.default_branch or 'GitHub の既定ブランチ' + lines = [f"作成の計画: {self.kind} {self.name}", + f" リポジトリ: {self.ref.full_name}"] + if self.state is RepoState.ABSENT: + visibility = 'public' if self.public else 'private' + lines.append(f" 作成: {self.ref.full_name} を {visibility} で作る") + if self.state in (RepoState.ABSENT, RepoState.EMPTY): + lines.append(f" 最初のコミット: {scaffold.REGISTRY_FILE} を {target} へ直接入れる") + elif self.state is RepoState.NO_REGISTRY: + lines.append(f" PR: {scaffold.REGISTRY_FILE} を足して {target} へマージする") + if self.files or self.registry_entry: + lines.append(f" PR: 次を足して {target} へマージする") + lines.extend(f" - {path}" for path in self.files) + if self.registry_entry: + lines.append(f" - {scaffold.REGISTRY_FILE} の項目 {self.registry_entry}") + lines.append(f" 手元: {self._local_step()}") + return '\n'.join(lines) + + def _local_step(self) -> str: + if self.registered is None: + return "repos/ へ clone して plugins.yml へ登録する" + return f"{self.registered.local_path} を早送りで取り込む" + + +def _inspect( + registry: PluginRegistry, gh: GhClient, ref: GitHubRef, + registered: Optional[RegisteredRepository], +) -> tuple: + """リポジトリの状態と既定ブランチを返す。使えないときは何も書かずに止める (読むだけ)""" + view = gh.view_repo(ref) + if view is None: + if registered is not None: + raise RepositoryError( + f"{ref.full_name} は登録済みですが、GitHub で見つからないか読めません") + if not gh.can_create_in(ref.owner): + raise RepositoryError( + f"{ref.full_name} が無く、{ref.owner} の下に作る権限もありません") + _reject_stale_clone(registry, ref) + return RepoState.ABSENT, '' + if not view.can_push: + raise RepositoryError(f"{ref.full_name} へ push する権限がありません") + if registered is None: + _reject_stale_clone(registry, ref) + if view.empty: + return RepoState.EMPTY, '' + if gh.read_file(ref, scaffold.REGISTRY_FILE) is None: + return RepoState.NO_REGISTRY, view.default_branch + return RepoState.HAS_REGISTRY, view.default_branch + + +def _reject_stale_clone(registry: PluginRegistry, ref: GitHubRef) -> None: + """未登録なのに clone の置き場が塞がっていると、マージの後の登録で止まるので先に止める""" + clone_dir = registry.get_repos_dir() / _url_to_repos_dirname(ref.clone_url) + if clone_dir.exists(): + raise RepositoryError( + f"{clone_dir} が既にありますが、登録されていません。" + "片付けてから打ち直してください" + ) + + +def plan_repo( + registry: PluginRegistry, gh: GhClient, value: str, *, public: bool = False, +) -> CreationPlan: + """``plugin repo new`` の計画 (読むだけ)""" + ref = GitHubRef.parse(value) + gh.ensure_ready() + registered = _find_registered(registry, ref.clone_url) + state, default_branch = _inspect(registry, gh, ref, registered) + noop = (f"{ref.full_name} は登録済みです ({registered.name})。何もしません" + if registered is not None else '') + return CreationPlan( + kind=KIND_REPO, ref=ref, name=ref.repo, state=state, + default_branch=default_branch, public=public, registered=registered, + noop_reason=noop, + ) + + +def _reflect_repository(gh: GhClient, plan: CreationPlan) -> None: + """リポジトリの分岐の分を既定ブランチへ入れる""" + files = {scaffold.REGISTRY_FILE: scaffold.registry_yml(plan.ref.repo)} + if plan.state in (RepoState.ABSENT, RepoState.EMPTY): + publish.push_initial(plan.ref, files, + title=publish.pr_title(KIND_REPO, plan.ref.repo)) + elif plan.state is RepoState.NO_REGISTRY: + publish.publish_change(gh, plan.ref, kind=KIND_REPO, name=plan.ref.repo, files=files) + + +def _follow_up(plan: CreationPlan) -> str: + """マージの後に手で打つコマンド""" + if plan.registered is None: + commands = [f"devbase plugin repo add {plan.ref.clone_url}"] + else: + commands = [f"devbase plugin repo refresh {plan.registered.name}"] + return '\n'.join(f" {command}" for command in commands) + + +def execute(registry: PluginRegistry, gh: GhClient, plan: CreationPlan) -> None: + """計画どおりに GitHub と手元へ書く。途中で止まったら、次のコマンドを例外の本文に載せる""" + if plan.state is RepoState.ABSENT: + gh.create_repo(plan.ref, public=plan.public) + logger.info("リポジトリを作りました: %s", plan.ref.full_name) + try: + _reflect_repository(gh, plan) + except publish.MergeFailed as e: + raise RepositoryError(f"{e}\nマージの後に打つコマンド:\n{_follow_up(plan)}") from e + except DevbaseError as e: + if plan.state is RepoState.ABSENT: + raise RepositoryError( + f"{e}\n{plan.ref.full_name} は作成済みです。" + "同じコマンドを打ち直すと続きから進みます" + ) from e + raise + _apply_locally(registry, plan) + + +def _apply_locally(registry: PluginRegistry, plan: CreationPlan) -> None: + """既定ブランチへの反映の後の、手元の取り込みと登録""" + try: + if plan.registered is None: + add_repository(registry, plan.ref.clone_url) + else: + _pull_ff_only(registry.devbase_root / plan.registered.local_path) + refresh_repository(registry, plan.registered.name) + except DevbaseError as e: + if not plan.writes_github: + raise + raise RepositoryError( + f"{e}\n既定ブランチへの反映は済んでいます。続けて打つコマンド:\n{_follow_up(plan)}" + ) from e diff --git a/tests/plugin/test_create_repo.py b/tests/plugin/test_create_repo.py new file mode 100644 index 00000000..e273703c --- /dev/null +++ b/tests/plugin/test_create_repo.py @@ -0,0 +1,267 @@ +"""``devbase plugin repo new`` のテスト (#514 の受け入れ条件 1〜5・14・15・17)。""" + +from __future__ import annotations + +import os + +import pytest +import yaml + +from devbase.plugin.models import RegisteredRepository +from devbase.plugin.registry import PluginRegistry + +FULL = "owner/repo" +REGISTRY = "name: repo\nplugins: []\n" + + +def _registered(root): + return PluginRegistry(root).list_repositories() + + +def _plugins_yml(root): + path = root / "plugins.yml" + return path.read_text() if path.exists() else None + + +def _visibility(github): + return github.state()["repos"][FULL]["visibility"] + + +# ── 分岐の表 ───────────────────────────────────────────────────── + + +def test_absent_repo_is_created_private_and_registered(github, root, run_cli): + github.add_org("owner", role="admin") + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert _visibility(github) == "private" + assert yaml.safe_load(github.file(FULL, "registry.yml")) == { + "name": "repo", "description": "", "plugins": []} + assert github.pushed_refs(FULL) == ["refs/heads/main"] + assert github.prs() == [] + repo = _registered(root)[0] + assert repo.url == "https://github.com/owner/repo.git" + assert (root / repo.local_path / "registry.yml").is_file() + assert repo.plugins == [], "プラグイン 0 件でも登録する" + + +def test_public_flag_makes_it_public(github, root, run_cli): + github.add_org("owner", role="admin") + assert run_cli("plugin", "repo", "new", FULL, "--public", "--yes") == 0 + assert _visibility(github) == "public" + + +def test_empty_repo_gets_first_commit_directly(github, root, run_cli): + github.add_repo(FULL) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert github.pushed_refs(FULL) == ["refs/heads/main"] + assert github.prs() == [] + assert [c for c in github.write_calls() if c[:2] == ["repo", "create"]] == [] + assert len(_registered(root)) == 1 + + +def test_repo_without_registry_goes_through_a_pr(github, root, run_cli): + github.add_repo(FULL, {"README.md": "x\n"}) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + pr = github.prs()[0] + assert pr["head"] == "devbase/new-repo-repo" + assert pr["state"] == "MERGED" + assert github.pushed_refs(FULL) == ["refs/heads/devbase/new-repo-repo"] + assert github.file(FULL, "registry.yml") is not None + assert len(_registered(root)) == 1 + + +def test_repo_with_registry_is_only_registered(github, root, run_cli): + github.add_repo(FULL, {"registry.yml": REGISTRY}) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert github.write_calls() == [] + assert github.pushed_refs(FULL) == [] + assert len(_registered(root)) == 1 + + +@pytest.mark.parametrize("registered_url", [ + "https://github.com/owner/repo.git", + "https://github.com/owner/repo", + "git@github.com:owner/repo.git", +]) +def test_registered_is_left_alone(github, root, run_cli, caplog, registered_url): + github.add_repo(FULL, {"registry.yml": REGISTRY}) + PluginRegistry(root).add_repository(RegisteredRepository(name="r", url=registered_url)) + before = _plugins_yml(root) + assert run_cli("plugin", "repo", "new", FULL) == 0, "確認も --yes も要らない" + assert _plugins_yml(root) == before + assert github.write_calls() == [] + assert "登録済み" in caplog.text + + +def test_registered_without_push_stops_with_1(github, root, run_cli): + github.add_repo(FULL, {"registry.yml": REGISTRY}, permission="READ") + PluginRegistry(root).add_repository(RegisteredRepository(name="r", url=f"git@github.com:{FULL}.git")) + before = _plugins_yml(root) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert _plugins_yml(root) == before + assert github.write_calls() == [] + + +def test_registered_with_empty_local_path_still_ends_0(github, root, run_cli): + github.add_repo(FULL, {"registry.yml": REGISTRY}) + PluginRegistry(root).add_repository(RegisteredRepository( + name="r", url=f"https://github.com/{FULL}.git", local_path="")) + assert run_cli("plugin", "repo", "new", FULL) == 0 + + +def test_no_push_stops_without_writing(github, root, run_cli, caplog): + github.add_repo(FULL, {"README.md": "x\n"}, permission="READ") + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert github.write_calls() == [] + assert github.pushed_refs(FULL) == [] + assert _plugins_yml(root) is None + assert not (root / "repos").exists() + assert FULL in caplog.text + + +def test_absent_and_cannot_create_stops(github, root, run_cli): + github.add_org("owner", role="member", can_create=False) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert github.write_calls() == [] + assert not github.exists(FULL) + assert _plugins_yml(root) is None + + +def test_absent_in_own_account_can_be_created(github, root, run_cli): + assert run_cli("plugin", "repo", "new", "me/repo", "--yes") == 0 + assert github.exists("me/repo") + + +def test_absent_in_org_where_members_can_create(github, root, run_cli): + github.add_org("owner", role="member", can_create=True) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + + +def test_unreadable_private_stops_at_create_with_gh_output(github, root, run_cli, caplog): + github.add_org("owner", role="admin") + github.add_repo(FULL, {"README.md": "x\n"}, hidden=True) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert "Name already exists" in caplog.text + assert _plugins_yml(root) is None + + +def test_stale_clone_directory_stops_before_writing(github, root, run_cli, caplog): + github.add_org("owner", role="admin") + (root / "repos" / "github.com--owner--repo").mkdir(parents=True) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert github.write_calls() == [] + assert "github.com--owner--repo" in caplog.text + + +# ── 引数の形 ───────────────────────────────────────────────────── + + +@pytest.mark.parametrize("value, url", [ + ("owner/repo", "https://github.com/owner/repo.git"), + ("https://github.com/owner/repo", "https://github.com/owner/repo.git"), + ("https://github.com/owner/repo.git", "https://github.com/owner/repo.git"), + ("git@github.com:owner/repo.git", "git@github.com:owner/repo.git"), +]) +def test_all_forms_reach_the_same_repo(github, root, run_cli, value, url): + github.add_repo(FULL, {"registry.yml": REGISTRY}) + assert run_cli("plugin", "repo", "new", value, "--yes") == 0 + assert _registered(root)[0].url == url + + +def test_non_github_url_stops(github, root, run_cli): + assert run_cli("plugin", "repo", "new", "https://gitlab.com/owner/repo", "--yes") == 1 + assert github.calls() == [], "gh を呼ぶ前に止まる" + + +def test_prefix_of_new_resolves(github, root, run_cli): + github.add_repo(FULL, {"registry.yml": REGISTRY}) + assert run_cli("pl", "repo", "n", FULL, "--yes") == 0 + + +# ── gh の前提 ──────────────────────────────────────────────────── + + +def test_without_gh_nothing_changes(github, root, run_cli, monkeypatch, caplog): + git_only = github.world / "git-only" + git_only.mkdir() + import shutil + (git_only / "git").symlink_to(shutil.which("git")) + monkeypatch.setenv("PATH", str(git_only)) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert "cli.github.com" in caplog.text + assert github.calls() == [] + assert _plugins_yml(root) is None + + +def test_unauthenticated_nothing_changes(github, root, run_cli, caplog): + github.update(authed=False) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert "gh auth login" in caplog.text + assert github.write_calls() == [] + assert _plugins_yml(root) is None + + +# ── 確認 ───────────────────────────────────────────────────────── + + +def test_no_tty_without_yes_stops_after_showing_the_plan(github, root, run_cli, capsys, caplog): + github.add_org("owner", role="admin") + assert run_cli("plugin", "repo", "new", FULL) == 1 + out = capsys.readouterr().out + assert FULL in out and "private" in out + assert "--yes" in caplog.text + assert github.write_calls() == [] + assert _plugins_yml(root) is None + + +def test_tty_decline_changes_nothing(github, root, run_cli): + github.add_org("owner", role="admin") + assert run_cli("plugin", "repo", "new", FULL, tty=True, answers=["n"]) == 1 + assert github.write_calls() == [] + assert _plugins_yml(root) is None + + +def test_tty_accept_goes_on(github, root, run_cli): + github.add_org("owner", role="admin") + assert run_cli("plugin", "repo", "new", FULL, tty=True, answers=["y"]) == 0 + assert github.exists(FULL) + assert len(_registered(root)) == 1 + + +def test_nothing_is_written_before_the_confirmation(github, root, run_cli, monkeypatch): + """確認の時点では GitHub にも手元にも書いていない (I1)。""" + from devbase.commands import plugin as commands + + github.add_org("owner", role="admin") + seen = {} + + def _record(): + seen.update(writes=github.write_calls(), registered=_plugins_yml(root)) + return False + + monkeypatch.setattr(commands, "_confirmed", _record) + assert run_cli("plugin", "repo", "new", FULL) == 1 + assert seen == {"writes": [], "registered": None} + + +# ── マージの失敗 ───────────────────────────────────────────────── + + +def test_merge_failure_leaves_plugins_yml_and_shows_pr(github, root, run_cli, caplog): + github.add_repo(FULL, {"README.md": "x\n"}, merge_error="required reviews") + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + pr = github.prs()[0] + assert pr["url"] in caplog.text + assert "devbase plugin repo add" in caplog.text + assert _plugins_yml(root) is None + assert not (root / "repos").exists() + + +# ── コンテナに触らない ─────────────────────────────────────────── + + +def test_never_touches_docker(github, root, run_cli): + github.add_org("owner", role="admin") + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert github.docker_calls() == [] + assert os.environ["PATH"].startswith(str(github.bin)) From 848ed15a16c962982ebdb1601df50ab6f9e810ad Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:49:21 +0000 Subject: [PATCH 07/18] =?UTF-8?q?Feat:=20#514=20devbase=20plugin=20new=20?= =?UTF-8?q?=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/devbase/cli.py | 12 +- lib/devbase/commands/plugin.py | 15 ++ lib/devbase/plugin/creator.py | 78 +++++++++ lib/devbase/plugin/scaffold.py | 5 + tests/plugin/test_create_plugin.py | 244 +++++++++++++++++++++++++++++ 5 files changed, 353 insertions(+), 1 deletion(-) create mode 100644 tests/plugin/test_create_plugin.py diff --git a/lib/devbase/cli.py b/lib/devbase/cli.py index ae37f8be..4435dd76 100644 --- a/lib/devbase/cli.py +++ b/lib/devbase/cli.py @@ -64,7 +64,8 @@ ('env',): ['init', 'sync', 'list', 'set', 'get', 'delete', 'edit', 'project', 'keygen', 'exec', 'token', 'encrypt', 'decrypt', 'rekey', 'doctor', 'export', 'import', 'backend'], - ('plugin', 'pl'): ['list', 'install', 'uninstall', 'update', 'info', 'sync', 'repo', 'migrate'], + ('plugin', 'pl'): ['list', 'install', 'uninstall', 'update', 'info', 'sync', 'repo', 'migrate', + 'new'], ('snapshot', 'ss'): ['create', 'list', 'restore', 'copy', 'delete', 'rotate'], } @@ -711,6 +712,15 @@ def _add_plugin_parser(subparsers): pl_sub.add_parser('migrate', help='Migrate legacy plugins/ installs to repos/ clones') + p_new = pl_sub.add_parser( + 'new', help='Add a new plugin to a repository on GitHub and install it') + _add_new_target_arg(p_new) + p_new.add_argument('--name', default=None, + help='Plugin name (default: the repository name)') + p_new.add_argument('--public', action='store_true', + help='Make the repository public when it is created (default: private)') + _add_yes_arg(p_new) + # Plugin repo sub-subcommands pl_repo = pl_sub.add_parser('repo', help='Manage plugin repositories') pl_repo_sub = pl_repo.add_subparsers(dest='repo_command') diff --git a/lib/devbase/commands/plugin.py b/lib/devbase/commands/plugin.py index 3d25090e..02b7f3da 100644 --- a/lib/devbase/commands/plugin.py +++ b/lib/devbase/commands/plugin.py @@ -40,6 +40,7 @@ def cmd_plugin(devbase_root: Path, args) -> int: 'sync': lambda: cmd_sync(devbase_root), 'migrate': lambda: cmd_plugin_migrate(devbase_root), 'repo': lambda: cmd_repo(devbase_root, args), + 'new': lambda: cmd_plugin_new(devbase_root, args), } handler = handlers.get(subcmd) @@ -199,6 +200,20 @@ def _confirmed() -> bool: return False +def cmd_plugin_new(devbase_root: Path, args) -> int: + """`plugin new`: リポジトリへプラグインを足して導入する""" + registry = PluginRegistry(devbase_root) + gh = GhClient() + try: + plan = creator.plan_plugin(registry, gh, args.repo, + name=getattr(args, 'name', None), + public=getattr(args, 'public', False)) + return run_creation(registry, gh, plan, getattr(args, 'yes', False)) + except DevbaseError as e: + logger.error("%s", e) + return 1 + + def cmd_repo_new(devbase_root: Path, args) -> int: """`plugin repo new`: プラグインリポジトリを用意して登録する""" registry = PluginRegistry(devbase_root) diff --git a/lib/devbase/plugin/creator.py b/lib/devbase/plugin/creator.py index ff56dd62..292993f9 100644 --- a/lib/devbase/plugin/creator.py +++ b/lib/devbase/plugin/creator.py @@ -14,6 +14,7 @@ from devbase.errors import DevbaseError, RepositoryError from devbase.log import get_logger +from devbase.utils import names from . import publish, scaffold from .github import GhClient, GitHubRef @@ -31,6 +32,7 @@ logger = get_logger("devbase.plugin.creator") KIND_REPO = 'repo' +KIND_PLUGIN = 'plugin' class RepoState(Enum): @@ -139,6 +141,70 @@ def plan_repo( ) +def _checked_name(name: str, what: str) -> str: + """プラグインとプロジェクトの名前を 名前の形 で確かめる (不変条件 I9)""" + if not names.is_single_segment_name(name): + raise RepositoryError( + f"{what}の名前にできません: '{name}' ({names.NAME_FORM_HINT})") + return name + + +def _require_clone(registry: PluginRegistry, repo: RegisteredRepository) -> None: + """登録の clone があることを確かめる。無ければ何も書かずに止める (読むだけ) + + ``local_path`` が空のまま進むと ``devbase_root`` そのものを指し、devbase 本体を取り込む。 + """ + if repo.local_path and (registry.devbase_root / repo.local_path).is_dir(): + return + raise RepositoryError( + f"登録 {repo.name} の手元の clone がありません。次のコマンドで登録し直してください:\n" + f" devbase plugin repo remove {repo.name}\n" + f" devbase plugin repo add {repo.url}\n" + "repo remove はこのリポジトリから導入したプラグインも外すので、" + "devbase plugin install も打ち直してください" + ) + + +def plan_plugin( + registry: PluginRegistry, gh: GhClient, value: str, *, + name: Optional[str] = None, public: bool = False, +) -> CreationPlan: + """``plugin new`` の計画 (読むだけ)。未登録ならリポジトリの分岐も計画に入る""" + ref = GitHubRef.parse(value) + gh.ensure_ready() + plugin = _checked_name(name or ref.repo, "プラグイン") + registered = _find_registered(registry, ref.clone_url) + if registered is not None: + _require_clone(registry, registered) + state, default_branch = _inspect(registry, gh, ref, registered) + if registered is not None and state is not RepoState.HAS_REGISTRY: + raise RepositoryError( + f"{ref.full_name} は登録済みですが、既定ブランチに {scaffold.REGISTRY_FILE} が" + "ありません") + _reject_duplicate_plugin(registry, gh, ref, plugin, state) + return CreationPlan( + kind=KIND_PLUGIN, ref=ref, name=plugin, state=state, + default_branch=default_branch, public=public, registered=registered, + files=scaffold.plugin_files(plugin), registry_entry=plugin, + ) + + +def _reject_duplicate_plugin( + registry: PluginRegistry, gh: GhClient, ref: GitHubRef, plugin: str, state: RepoState, +) -> None: + if registry.get(plugin) is not None: + raise RepositoryError(f"プラグイン {plugin} は既に導入されています") + if state in (RepoState.ABSENT, RepoState.EMPTY): + return + if state is RepoState.HAS_REGISTRY: + text = gh.read_file(ref, scaffold.REGISTRY_FILE) or '' + if plugin in scaffold.registry_plugin_names(text): + raise RepositoryError( + f"プラグイン {plugin} は {ref.full_name} の {scaffold.REGISTRY_FILE} に既にあります") + if gh.read_file(ref, plugin) is not None: + raise RepositoryError(f"{ref.full_name} に {plugin} が既にあります") + + def _reflect_repository(gh: GhClient, plan: CreationPlan) -> None: """リポジトリの分岐の分を既定ブランチへ入れる""" files = {scaffold.REGISTRY_FILE: scaffold.registry_yml(plan.ref.repo)} @@ -149,12 +215,19 @@ def _reflect_repository(gh: GhClient, plan: CreationPlan) -> None: publish.publish_change(gh, plan.ref, kind=KIND_REPO, name=plan.ref.repo, files=files) +def _source_url(plan: CreationPlan) -> str: + """手元の呼び出しへ渡す URL。登録済みなら登録の値 (決定 9)""" + return plan.ref.clone_url if plan.registered is None else plan.registered.url + + def _follow_up(plan: CreationPlan) -> str: """マージの後に手で打つコマンド""" if plan.registered is None: commands = [f"devbase plugin repo add {plan.ref.clone_url}"] else: commands = [f"devbase plugin repo refresh {plan.registered.name}"] + if plan.kind == KIND_PLUGIN: + commands.append(f"devbase plugin install {_source_url(plan)}:{plan.name}") return '\n'.join(f" {command}" for command in commands) @@ -165,6 +238,9 @@ def execute(registry: PluginRegistry, gh: GhClient, plan: CreationPlan) -> None: logger.info("リポジトリを作りました: %s", plan.ref.full_name) try: _reflect_repository(gh, plan) + if plan.kind != KIND_REPO: + publish.publish_change(gh, plan.ref, kind=plan.kind, name=plan.name, + files=plan.files, registry_entry=plan.registry_entry) except publish.MergeFailed as e: raise RepositoryError(f"{e}\nマージの後に打つコマンド:\n{_follow_up(plan)}") from e except DevbaseError as e: @@ -185,6 +261,8 @@ def _apply_locally(registry: PluginRegistry, plan: CreationPlan) -> None: else: _pull_ff_only(registry.devbase_root / plan.registered.local_path) refresh_repository(registry, plan.registered.name) + if plan.kind == KIND_PLUGIN: + install_plugin(registry, f"{_source_url(plan)}:{plan.name}") except DevbaseError as e: if not plan.writes_github: raise diff --git a/lib/devbase/plugin/scaffold.py b/lib/devbase/plugin/scaffold.py index 6ba560d0..6a86fd3a 100644 --- a/lib/devbase/plugin/scaffold.py +++ b/lib/devbase/plugin/scaffold.py @@ -105,6 +105,11 @@ def add_registry_entry(text: str, name: str) -> str: return added +def registry_plugin_names(text: str) -> List[str]: + """``registry.yml`` の ``plugins`` の名前""" + return [entry.get('name', '') for entry in _load_registry(text).get('plugins') or []] + + def _load_registry(text: str) -> dict: try: data = yaml.safe_load(text) diff --git a/tests/plugin/test_create_plugin.py b/tests/plugin/test_create_plugin.py new file mode 100644 index 00000000..19d5a76a --- /dev/null +++ b/tests/plugin/test_create_plugin.py @@ -0,0 +1,244 @@ +"""``devbase plugin new`` のテスト (#514 の受け入れ条件 6〜8・16・17、決定 8・9)。""" + +from __future__ import annotations + +import subprocess + +import pytest +import yaml + +from devbase.commands.plugin import cmd_plugin_list +from devbase.plugin.models import RegisteredRepository +from devbase.plugin.registry import PluginRegistry +from devbase.plugin.repo_manager import add_repository + +FULL = "owner/repo" +URL = "https://github.com/owner/repo.git" +REGISTRY = "# 説明\nname: repo\nplugins: []\n" + + +def _plugins_yml(root): + path = root / "plugins.yml" + return path.read_text() if path.exists() else None + + +def _registry_names(github): + return [e["name"] for e in yaml.safe_load(github.file(FULL, "registry.yml"))["plugins"]] + + +@pytest.fixture +def registered(github, root): + github.add_repo(FULL, {"registry.yml": REGISTRY}) + add_repository(PluginRegistry(root), URL) + return root / "repos" / "github.com--owner--repo" + + +def _assert_installed(root, name="team-a", source=URL): + registry = PluginRegistry(root) + plugin = registry.get(name) + assert plugin is not None + assert plugin.source == source + assert (root / plugin.path / "plugin.yml").is_file() + return plugin + + +def test_registered_repo_gets_a_plugin(github, root, registered, run_cli, capsys): + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + pr = github.prs()[0] + assert pr["head"] == "devbase/new-plugin-team-a" + assert pr["state"] == "MERGED" + assert github.file(FULL, "team-a/plugin.yml") is not None + assert github.file(FULL, "team-a/projects/.gitkeep") is not None + text = github.file(FULL, "registry.yml") + assert text.startswith("# 説明\n"), "registry.yml のコメントが残る" + assert _registry_names(github) == ["team-a"] + assert (registered / "team-a" / "plugin.yml").is_file(), "手元へ取り込む" + _assert_installed(root) + capsys.readouterr() + cmd_plugin_list(root) + assert "team-a" in capsys.readouterr().out + + +def test_default_name_is_the_repo_name(github, root, registered, run_cli): + assert run_cli("plugin", "new", FULL, "--yes") == 0 + _assert_installed(root, "repo") + + +@pytest.mark.parametrize("prepare, first_pushes, first_titles", [ + ("absent", ["refs/heads/main"], ["devbase: repo repo を足す"]), + ("empty", ["refs/heads/main"], ["devbase: repo repo を足す"]), + ("no-registry", ["refs/heads/devbase/new-repo-repo"], ["seed", "devbase: repo repo を足す"]), + ("registry", [], ["seed"]), +]) +def test_unregistered_goes_through_the_repo_branch_first( + github, root, run_cli, prepare, first_pushes, first_titles): + github.add_org("owner", role="admin") + if prepare == "empty": + github.add_repo(FULL) + elif prepare == "no-registry": + github.add_repo(FULL, {"README.md": "x\n"}) + elif prepare == "registry": + github.add_repo(FULL, {"registry.yml": REGISTRY}) + + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + + assert github.pushed_refs(FULL) == [*first_pushes, "refs/heads/devbase/new-plugin-team-a"] + assert github.subjects(FULL) == [*first_titles, "devbase: plugin team-a を足す"], \ + "リポジトリの分岐 → プラグインの PR の順に別の変更で入る (決定 8)" + _assert_installed(root) + + +def test_absent_is_private_unless_public(github, root, run_cli): + github.add_org("owner", role="admin") + assert run_cli("plugin", "new", FULL, "--public", "--yes") == 0 + assert github.state()["repos"][FULL]["visibility"] == "public" + + +def test_public_does_not_change_an_existing_repo(github, root, registered, run_cli): + assert run_cli("plugin", "new", FULL, "--public", "--yes") == 0 + assert [c for c in github.write_calls() if c[:2] == ["repo", "create"]] == [] + + +@pytest.mark.parametrize("setup", ["no-push", "cannot-create"]) +def test_repo_branch_that_ends_writes_nothing(github, root, run_cli, setup): + if setup == "no-push": + github.add_repo(FULL, {"README.md": "x\n"}, permission="READ") + else: + github.add_org("owner", role="member") + assert run_cli("plugin", "new", FULL, "--yes") == 1 + assert github.write_calls() == [] + assert _plugins_yml(root) is None + + +def test_duplicate_in_registry_changes_nothing(github, root, run_cli, caplog): + text = "name: repo\nplugins:\n - name: team-a\n path: other\n" + github.add_repo(FULL, {"registry.yml": text}) + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert github.write_calls() == [] + assert _plugins_yml(root) is None + assert "team-a" in caplog.text + + +def test_duplicate_directory_changes_nothing(github, root, run_cli): + github.add_repo(FULL, {"registry.yml": REGISTRY, "team-a/README.md": "x\n"}) + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert github.write_calls() == [] + + +def test_duplicate_installed_name_changes_nothing(github, root, registered, run_cli): + other = "other/repo" + github.add_repo(other, { + "registry.yml": "name: other\nplugins:\n - name: team-a\n path: team-a\n", + "team-a/plugin.yml": "name: team-a\n", + }) + registry = PluginRegistry(root) + add_repository(registry, f"https://github.com/{other}.git") + from devbase.plugin.installer import install_plugin + install_plugin(registry, f"https://github.com/{other}.git:team-a") + before = _plugins_yml(root) + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert _plugins_yml(root) == before + assert github.write_calls() == [] + + +@pytest.mark.parametrize("name", ["../up", "a/b", "-x", ".hidden", "a b"]) +def test_bad_name_form_stops_before_gh_writes(github, root, registered, run_cli, name): + assert run_cli("plugin", "new", FULL, f"--name={name}", "--yes") == 1 + assert github.write_calls() == [] + + +@pytest.mark.parametrize("registered_url, value", [ + ("git@github.com:owner/repo.git", "owner/repo"), + ("https://github.com/owner/repo", "git@github.com:owner/repo.git"), + ("https://github.com/owner/repo", "https://github.com/owner/repo.git"), +]) +def test_url_form_difference_uses_the_registered_path( + github, root, run_cli, registered_url, value): + github.add_repo(FULL, {"registry.yml": REGISTRY}) + add_repository(PluginRegistry(root), registered_url) + assert run_cli("plugin", "new", value, "--name", "team-a", "--yes") == 0 + urls = [r.url for r in PluginRegistry(root).list_repositories()] + assert urls == [registered_url], "plugins.yml の url は変わらない" + _assert_installed(root, source=registered_url) + # 同じ入力の repo new は何もしない + calls = len(github.write_calls()) + assert run_cli("plugin", "repo", "new", value) == 0 + assert len(github.write_calls()) == calls + + +@pytest.mark.parametrize("state", ["empty-path", "missing-dir"]) +def test_registration_without_clone_stops_before_writing(github, root, run_cli, caplog, state): + github.add_repo(FULL, {"registry.yml": REGISTRY}) + local_path = "" if state == "empty-path" else "repos/github.com--owner--repo" + PluginRegistry(root).add_repository(RegisteredRepository( + name="r", url=URL, local_path=local_path)) + before = _plugins_yml(root) + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert github.write_calls() == [] + assert _plugins_yml(root) == before + assert "plugin repo remove r" in caplog.text + assert f"plugin repo add {URL}" in caplog.text + # 同じ登録へ repo new は何もせず 0 + assert run_cli("plugin", "repo", "new", FULL) == 0 + + +def test_uncommitted_changes_survive(github, root, registered, run_cli): + (registered / "note.txt").write_text("mine\n") + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + assert (registered / "note.txt").read_text() == "mine\n" + status = subprocess.run(["git", "status", "--porcelain"], cwd=registered, + check=True, capture_output=True, text=True).stdout + assert status.strip() == "?? note.txt", "clone の作業ツリーを汚さない" + + +def test_colliding_change_stops_and_is_kept(github, root, registered, run_cli, caplog): + edited = REGISTRY + "# 手元の編集\n" + (registered / "registry.yml").write_text(edited) + before = _plugins_yml(root) + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert (registered / "registry.yml").read_text() == edited + assert _plugins_yml(root) == before + assert "git -C" in caplog.text + + +def test_diverged_clone_stops_with_commands(github, root, registered, run_cli, caplog): + subprocess.run(["git", "commit", "--allow-empty", "-m", "local"], cwd=registered, check=True, + capture_output=True) + before = _plugins_yml(root) + head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=registered, check=True, + capture_output=True, text=True).stdout + github.commit(FULL, {"other.txt": "x\n"}) + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert _plugins_yml(root) == before + assert subprocess.run(["git", "rev-parse", "HEAD"], cwd=registered, check=True, + capture_output=True, text=True).stdout == head + assert "git -C" in caplog.text + assert "devbase plugin repo refresh" in caplog.text + assert "devbase plugin install" in caplog.text + + +@pytest.mark.parametrize("prepare", ["registered", "unregistered"]) +def test_merge_failure_keeps_plugins_yml(github, root, run_cli, caplog, prepare): + github.add_repo(FULL, {"registry.yml": REGISTRY}, merge_error="required reviews") + if prepare == "registered": + add_repository(PluginRegistry(root), URL) + before = _plugins_yml(root) + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert _plugins_yml(root) == before + assert github.prs()[0]["url"] in caplog.text + assert "devbase plugin install" in caplog.text + assert "devbase plugin repo" in caplog.text + + +def test_never_touches_docker(github, root, registered, run_cli): + assert run_cli("plugin", "new", FULL, "--yes") == 0 + assert github.docker_calls() == [] + + +def test_prefix_of_new_resolves(github, root, registered, run_cli): + assert run_cli("pl", "n", FULL, "--yes") == 0 + + +def test_no_tty_without_yes_stops(github, root, registered, run_cli): + assert run_cli("plugin", "new", FULL) == 1 + assert github.write_calls() == [] From cfc70333473997c31b8d97b8547f766b56203f61 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:51:09 +0000 Subject: [PATCH 08/18] =?UTF-8?q?Feat:=20#514=20devbase=20project=20new=20?= =?UTF-8?q?=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/devbase/cli.py | 19 +- lib/devbase/commands/project.py | 47 ++++ lib/devbase/plugin/creator.py | 179 ++++++++++++- tests/cli/test_project_new_dispatch.py | 62 +++++ tests/plugin/test_create_project.py | 338 +++++++++++++++++++++++++ 5 files changed, 641 insertions(+), 4 deletions(-) create mode 100644 tests/cli/test_project_new_dispatch.py create mode 100644 tests/plugin/test_create_project.py diff --git a/lib/devbase/cli.py b/lib/devbase/cli.py index 4435dd76..ba7f3ef2 100644 --- a/lib/devbase/cli.py +++ b/lib/devbase/cli.py @@ -58,7 +58,7 @@ # Subcommand map for prefix resolution: {(aliases...): [subcmds]} SUBCMD_MAP = { ('project',): ['up', 'down', 'ps', 'login', 'logs', 'scale', 'build', 'rebuild', 'list', - 'profile', 'open', 'post-start'], + 'profile', 'open', 'post-start', 'new'], ('container', 'ct'): ['up', 'down', 'ps', 'login', 'logs', 'scale', 'build', 'rebuild', 'profile', 'open'], ('env',): ['init', 'sync', 'list', 'set', 'get', 'delete', 'edit', 'project', 'keygen', @@ -346,6 +346,17 @@ def _add_project_parser(subparsers): # 取らない (wrapper の _PROJECT_NAME_SUBCOMMANDS にも含めない)。 _add_list_subparser(pj_sub) + # `new` はプラグインへプロジェクトを足す作成フロー (#514)。lifecycle ではなく、引数は + # GitHub のリポジトリなので wrapper の _PROJECT_NAME_SUBCOMMANDS には含めない。 + pj_new = pj_sub.add_parser( + 'new', help='Add a project for a GitHub repository to a plugin (does not start it)') + _add_new_target_arg(pj_new) + pj_new.add_argument('--plugin', default=None, help='Plugin to add the project to') + pj_new.add_argument('--group', default=None, help='Account group of the project') + pj_new.add_argument('--name', default=None, + help='Project name (default: the repository name)') + _add_yes_arg(pj_new) + # `migrate-config` は旧 env 形式から project.yml への変換 (PLAN32)。lifecycle # ではないため wrapper の _PROJECT_NAME_SUBCOMMANDS には含めない。 pj_migrate = pj_sub.add_parser( @@ -970,6 +981,8 @@ def main(): # コンテナの bao へ token を届けるだけで、機密の値は要らない。注入するとサーバへの # 往復が増える (PLAN54)。 ('env', 'token'), + # プラグインへファイルを足すだけで機密を使わない。lifecycle の分岐より先に抜ける (#514)。 + ('project', 'new'), }) @@ -1120,6 +1133,10 @@ def _dispatch(cmd, args): from devbase.commands.project import cmd_project_list return cmd_project_list(devbase_root, args) # `project migrate-config` も lifecycle ではなく projects/ 全体の変換。 + if getattr(args, 'subcommand', None) == 'new': + devbase_root = _require_devbase_root() + from devbase.commands.project import cmd_project_new + return cmd_project_new(devbase_root, args) if getattr(args, 'subcommand', None) == 'migrate-config': devbase_root = _require_devbase_root() from devbase.commands.project import cmd_project_migrate_config diff --git a/lib/devbase/commands/project.py b/lib/devbase/commands/project.py index 096e526e..4dffefd7 100644 --- a/lib/devbase/commands/project.py +++ b/lib/devbase/commands/project.py @@ -63,6 +63,53 @@ def _resolve_plugin_name(entry: Path) -> str | None: return None +class _TtyPrompter: + """入れ先とグループを端末で聞く (creator.Prompter)""" + + def choose(self, message: str, options: list[str]) -> str | None: + print(message) + for number, option in enumerate(options, start=1): + print(f" {number}. {option}") + answer = self.ask("番号") + if answer and answer.isdecimal() and 1 <= int(answer) <= len(options): + return options[int(answer) - 1] + return None + + def ask(self, message: str) -> str | None: + try: + return input(f"{message}: ").strip() or None + except (EOFError, KeyboardInterrupt): + return None + + +def cmd_project_new(devbase_root: Path, args) -> int: + """`project new`: 入れ先のプラグインへプロジェクトを足し、手元へ反映する。 + + コンテナは起動しない (``devbase up`` は打たない)。 + """ + from devbase.commands.plugin import run_creation + from devbase.errors import DevbaseError + from devbase.plugin import creator + from devbase.plugin.github import GhClient + from devbase.plugin.registry import PluginRegistry + + registry = PluginRegistry(devbase_root) + gh = GhClient() + prompter = _TtyPrompter() if sys.stdin.isatty() else None + try: + plan = creator.plan_project( + registry, gh, args.repo, + plugin=getattr(args, 'plugin', None), + group=getattr(args, 'group', None), + name=getattr(args, 'name', None), + prompter=prompter, + ) + return run_creation(registry, gh, plan, getattr(args, 'yes', False)) + except DevbaseError as e: + logger.error("%s", e) + return 1 + + def list_projects(projects_dir: Path) -> list[dict]: """projects/ 配下のプロジェクトを NAME / PLUGIN / STATUS で列挙する。 diff --git a/lib/devbase/plugin/creator.py b/lib/devbase/plugin/creator.py index 292993f9..7d477442 100644 --- a/lib/devbase/plugin/creator.py +++ b/lib/devbase/plugin/creator.py @@ -8,16 +8,20 @@ from __future__ import annotations -from dataclasses import dataclass, field +import os +from collections import Counter +from dataclasses import dataclass, field, replace from enum import Enum -from typing import Dict, List, Optional +from typing import Dict, List, Optional, Protocol, Tuple +from devbase.env import groups from devbase.errors import DevbaseError, RepositoryError from devbase.log import get_logger from devbase.utils import names +from devbase.volume.manager import validate_account_group from . import publish, scaffold -from .github import GhClient, GitHubRef +from .github import GhClient, GitHubRef, RepoView from .installer import install_plugin from .models import RegisteredRepository from .registry import PluginRegistry @@ -33,6 +37,17 @@ KIND_REPO = 'repo' KIND_PLUGIN = 'plugin' +KIND_PROJECT = 'project' + + +class Prompter(Protocol): + """入れ先とグループを人へ聞く口。TTY が無いときは渡さない""" + + def choose(self, message: str, options: List[str]) -> Optional[str]: + """``options`` から 1 つ選ばせる。選ばなければ ``None``""" + + def ask(self, message: str) -> Optional[str]: + """1 行を入力させる。入れなければ ``None``""" class RepoState(Enum): @@ -55,6 +70,8 @@ class CreationPlan: registered: Optional[RegisteredRepository] = None files: Dict[str, str] = field(default_factory=dict) registry_entry: Optional[str] = None + #: 計画の文面に足す行 (入れ先のプラグインなど) + details: Tuple[str, ...] = () #: 空でなければ何もしないで終わる。その理由 noop_reason: str = '' @@ -67,6 +84,7 @@ def describe(self) -> str: target = self.default_branch or 'GitHub の既定ブランチ' lines = [f"作成の計画: {self.kind} {self.name}", f" リポジトリ: {self.ref.full_name}"] + lines.extend(f" {detail}" for detail in self.details) if self.state is RepoState.ABSENT: visibility = 'public' if self.public else 'private' lines.append(f" 作成: {self.ref.full_name} を {visibility} で作る") @@ -205,6 +223,161 @@ def _reject_duplicate_plugin( raise RepositoryError(f"{ref.full_name} に {plugin} が既にあります") +@dataclass(frozen=True) +class PluginTarget: + """プロジェクトの入れ先のプラグイン""" + plugin: str + repo: RegisteredRepository + ref: GitHubRef + path: str + default_branch: str = '' + + @property + def label(self) -> str: + return f"{self.plugin} ({self.ref.full_name})" + + +def _installed_targets(registry: PluginRegistry) -> List[PluginTarget]: + """導入済みで、登録済みの GitHub のリポジトリに項目があるプラグイン (GitHub を見ない)""" + targets = [] + for plugin in registry.list_installed(): + repo = None if plugin.linked else _find_registered(registry, plugin.source) + entry = repo.find_plugin(plugin.name) if repo else None + if entry is None: + continue + try: + ref = GitHubRef.parse(repo.url) + except RepositoryError: + continue + targets.append(PluginTarget(plugin.name, repo, ref, + (entry.path or plugin.name).rstrip('/'))) + return targets + + +def _pushable(gh: GhClient, target: PluginTarget, views: Dict[str, Optional[RepoView]], + ) -> Optional[PluginTarget]: + """push できる入れ先に既定ブランチを埋めて返す。``gh`` はリポジトリごとに 1 回""" + key = target.ref.full_name + if key not in views: + views[key] = gh.view_repo(target.ref) + view = views[key] + if view is None or view.empty or not view.can_push: + return None + return replace(target, default_branch=view.default_branch) + + +def plugin_candidates( + registry: PluginRegistry, gh: GhClient, ref: GitHubRef, +) -> List[PluginTarget]: + """入れ先の候補 (読むだけ)。対象と同じ owner の候補があれば、それに絞る""" + views: Dict[str, Optional[RepoView]] = {} + pushable = [found for target in _installed_targets(registry) + if (found := _pushable(gh, target, views)) is not None] + owner = ref.owner.lower() + same_owner = [t for t in pushable if t.ref.owner.lower() == owner] + return same_owner or pushable + + +def _named_target(registry: PluginRegistry, gh: GhClient, plugin: str) -> PluginTarget: + target = next((t for t in _installed_targets(registry) if t.plugin == plugin), None) + if target is None: + raise RepositoryError( + f"プラグイン {plugin} は、導入済みの GitHub のプラグインの中にありません") + found = _pushable(gh, target, {}) + if found is None: + raise RepositoryError(f"{target.ref.full_name} へ push する権限がありません") + return found + + +def _decide_target( + registry: PluginRegistry, gh: GhClient, ref: GitHubRef, + plugin: Optional[str], prompter: Optional[Prompter], +) -> PluginTarget: + """入れ先のプラグインを決める (受け入れ条件 10)""" + if plugin: + return _named_target(registry, gh, plugin) + candidates = plugin_candidates(registry, gh, ref) + if not candidates: + raise RepositoryError( + "入れ先のプラグインがありません。push できるプラグインを導入するか、" + "devbase plugin new で足してください" + ) + if len(candidates) == 1: + return candidates[0] + labels = [c.label for c in candidates] + if prompter is None: + listed = '\n'.join(f" {label}" for label in labels) + raise RepositoryError(f"入れ先のプラグインを --plugin で指定してください:\n{listed}") + chosen = prompter.choose("入れ先のプラグインを選んでください", labels) + if chosen is None: + raise RepositoryError("入れ先のプラグインが選ばれませんでした") + return candidates[labels.index(chosen)] + + +def suggest_group(registry: PluginRegistry, target: PluginTarget) -> Optional[str]: + """入れ先の既存プロジェクトで最多のグループ (読むだけ)。無い・同数なら ``None``""" + projects = registry.devbase_root / target.repo.local_path / target.path / 'projects' + counts: Counter = Counter() + for project in names.project_dirs(projects): + try: + found = groups._read_declaration(project / groups.ENV_FILENAME) + except DevbaseError as e: + logger.debug("グループの案から外します (%s): %s", project.name, e) + continue + if found is not None and found[0].strip(): + counts[found[0].strip()] += 1 + ranked = counts.most_common(2) + if not ranked or (len(ranked) == 2 and ranked[0][1] == ranked[1][1]): + return None + return ranked[0][0] + + +def _decide_group( + registry: PluginRegistry, target: PluginTarget, + group: Optional[str], prompter: Optional[Prompter], +) -> str: + """グループを決めて ``validate_account_group`` を通す (受け入れ条件 11・不変条件 I9)""" + value = group or suggest_group(registry, target) + if not value and prompter is not None: + value = prompter.ask("アカウントグループを入力してください") + if not value: + raise RepositoryError( + f"アカウントグループを決められません。--group で指定してください ({target.plugin})") + return validate_account_group(value) + + +def plan_project( + registry: PluginRegistry, gh: GhClient, value: str, *, + plugin: Optional[str] = None, group: Optional[str] = None, + name: Optional[str] = None, prompter: Optional[Prompter] = None, +) -> CreationPlan: + """``project new`` の計画 (読むだけ)""" + ref = GitHubRef.parse(value) + gh.ensure_ready() + project = _checked_name(name or ref.repo, "プロジェクト") + if gh.view_repo(ref) is None: + raise RepositoryError(f"{ref.full_name} が見つからないか読めません") + local = registry.get_projects_dir() / project + if os.path.lexists(local): + raise RepositoryError(f"{local} が既にあります") + + target = _decide_target(registry, gh, ref, plugin, prompter) + _require_clone(registry, target.repo) + destination = f"{target.path}/projects/{project}" + if gh.read_file(target.ref, destination) is not None: + raise RepositoryError(f"{target.ref.full_name} に {destination} が既にあります") + decided_group = _decide_group(registry, target, group, prompter) + + return CreationPlan( + kind=KIND_PROJECT, ref=target.ref, name=project, state=RepoState.HAS_REGISTRY, + default_branch=target.default_branch, registered=target.repo, + files=scaffold.project_files(target.path, project, ref, decided_group), + details=(f"対象: {ref.full_name}", + f"入れ先のプラグイン: {target.plugin}", + f"アカウントグループ: {decided_group}"), + ) + + def _reflect_repository(gh: GhClient, plan: CreationPlan) -> None: """リポジトリの分岐の分を既定ブランチへ入れる""" files = {scaffold.REGISTRY_FILE: scaffold.registry_yml(plan.ref.repo)} diff --git a/tests/cli/test_project_new_dispatch.py b/tests/cli/test_project_new_dispatch.py new file mode 100644 index 00000000..4a3446e5 --- /dev/null +++ b/tests/cli/test_project_new_dispatch.py @@ -0,0 +1,62 @@ +"""``devbase project new`` の入口のテスト (#514 の受け入れ条件 22)。""" + +from __future__ import annotations + +import sys + +import pytest + +from devbase import cli + +from .conftest import python_args, stdout_field + + +@pytest.mark.parametrize("target", ["owner/repo", "myapp"]) +def test_wrapper_does_not_resolve_the_argument_as_a_project(exec_wrapper, target): + """同じ名前のプロジェクトがあっても、引数をプロジェクト名として解決しない。""" + exec_wrapper.project("myapp") + (exec_wrapper.root / "projects" / "owner").mkdir() + r = exec_wrapper(["project", "new", target]) + assert "/projects/" not in stdout_field(r, "PWD:"), r.stdout + assert python_args(r) == f"project new {target}", r.stdout + + +def test_new_is_in_the_prefix_map(): + assert "new" in cli.SUBCMD_MAP[("project",)] + assert "new" in cli.SUBCMD_MAP[("plugin", "pl")] + + +def test_prefix_resolves_to_new(monkeypatch): + monkeypatch.setattr(sys, "argv", ["devbase", "project", "n", "owner/repo"]) + cli._expand_argv() + assert sys.argv == ["devbase", "project", "new", "owner/repo"] + + +def test_secrets_are_not_injected(): + assert cli._skip_secret_injection("project", "new") + + +def test_parser_arguments(): + args = cli._create_parser().parse_args( + ["project", "new", "owner/repo", "--plugin", "p", "--group", "g", + "--name", "n", "--yes"]) + assert (args.repo, args.plugin, args.group, args.name, args.yes) == ( + "owner/repo", "p", "g", "n", True) + + +def test_dispatch_does_not_reach_the_lifecycle(monkeypatch, tmp_path): + seen = {} + monkeypatch.setenv("DEVBASE_ROOT", str(tmp_path)) + + def _fake(root, args): + seen["root"] = root + seen["repo"] = args.repo + return 0 + + from devbase.commands import container, project + monkeypatch.setattr(project, "cmd_project_new", _fake) + monkeypatch.setattr(container, "cmd_project", + lambda *_a: pytest.fail("lifecycle へ流れた")) + args = cli._create_parser().parse_args(["project", "new", "owner/repo"]) + assert cli._dispatch("project", args) == 0 + assert seen == {"root": tmp_path, "repo": "owner/repo"} diff --git a/tests/plugin/test_create_project.py b/tests/plugin/test_create_project.py new file mode 100644 index 00000000..53f54ce8 --- /dev/null +++ b/tests/plugin/test_create_project.py @@ -0,0 +1,338 @@ +"""``devbase project new`` のテスト (#514 の受け入れ条件 9〜13)。""" + +from __future__ import annotations + +import pytest +import yaml + +from devbase.commands.project import list_projects +from devbase.plugin import creator +from devbase.plugin.github import GhClient, GitHubRef +from devbase.plugin.installer import install_plugin +from devbase.plugin.models import AvailablePlugin, InstalledPlugin, RegisteredRepository +from devbase.plugin.registry import PluginRegistry +from devbase.plugin.repo_manager import add_repository +from devbase.project.config import parse_project_config + +APP = "owner/app" + + +def _plugins_yml(root): + path = root / "plugins.yml" + return path.read_text() if path.exists() else None + + +def _plugin_repo(github, root, full, plugin="team-a", groups=(), install=True, **values): + """プラグインを 1 つ収めたリポジトリを用意して登録・導入する。""" + files = { + "registry.yml": f"name: {full.split('/')[1]}\nplugins:\n" + f" - name: {plugin}\n path: {plugin}\n", + f"{plugin}/plugin.yml": f"name: {plugin}\nversion: '1.0.0'\n", + f"{plugin}/projects/.gitkeep": "", + } + for index, group in enumerate(groups): + files[f"{plugin}/projects/p{index}/project.yml"] = "version: 1\n" + files[f"{plugin}/projects/p{index}/env"] = f"DEVBASE_ACCOUNT_GROUP={group}\n" + github.add_repo(full, files, **values) + registry = PluginRegistry(root) + url = f"https://github.com/{full}.git" + add_repository(registry, url) + if install: + install_plugin(registry, f"{url}:{plugin}") + return root / "repos" / f"github.com--{full.replace('/', '--')}" + + +@pytest.fixture +def app(github): + github.add_repo(APP, {"README.md": "x\n"}, permission="READ") + return APP + + +def test_project_is_added_and_reflected(github, root, app, run_cli): + clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", APP, "--yes") == 0 + + pr = github.prs()[0] + assert pr["head"] == "devbase/new-project-app" + assert pr["state"] == "MERGED" + base = "team-a/projects/app" + full = "owner/plugins" + config = parse_project_config( + yaml.safe_load(github.file(full, f"{base}/project.yml")), "project.yml") + assert (config.primary.owner, config.primary.repo) == ("owner", "app") + assert "dev" in yaml.safe_load(github.file(full, f"{base}/compose.yml"))["services"] + assert github.file(full, f"{base}/env") == "DEVBASE_ACCOUNT_GROUP=acme\n" + + assert (clone / base / "project.yml").is_file(), "手元へ取り込む" + assert (root / "projects" / "app" / "project.yml").is_file(), "projects/ へ反映する" + names = [row["name"] for row in list_projects(root / "projects")] + assert names.count("app") == 1 + + +def test_name_option(github, root, app, run_cli): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", APP, "--name", "web", "--yes") == 0 + assert (root / "projects" / "web").is_dir() + assert not (root / "projects" / "app").exists() + assert github.file("owner/plugins", "team-a/projects/web/project.yml") is not None + + +def test_plan_shows_target_and_group(github, root, app, run_cli, capsys): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", APP) == 1, "TTY が無く --yes も無い" + out = capsys.readouterr().out + assert "team-a" in out and "acme" in out and "owner/plugins" in out and "main" in out + assert github.write_calls() == [] + + +# ── 入れ先の決定 ──────────────────────────────────────────────── + + +def test_plugin_option_wins(github, root, app, run_cli): + _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"]) + _plugin_repo(github, root, "owner/two", plugin="two", groups=["acme"]) + assert run_cli("project", "new", APP, "--plugin", "two", "--yes") == 0 + assert github.file("owner/two", "two/projects/app/env") is not None + + +def test_plugin_option_requires_install(github, root, app, run_cli, caplog): + _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"], install=False) + assert run_cli("project", "new", APP, "--plugin", "one", "--yes") == 1 + assert "one" in caplog.text + assert github.write_calls() == [] + + +def test_plugin_option_requires_push(github, root, app, run_cli): + _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"], permission="READ") + assert run_cli("project", "new", APP, "--plugin", "one", "--yes") == 1 + assert github.write_calls() == [] + + +def test_same_owner_narrows_the_candidates(github, root, app, run_cli): + _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"]) + _plugin_repo(github, root, "other/two", plugin="two", groups=["acme"]) + assert run_cli("project", "new", APP, "--yes") == 0 + assert github.file("owner/one", "one/projects/app/env") is not None + + +def test_no_same_owner_keeps_all_candidates(github, root, app, run_cli, caplog): + _plugin_repo(github, root, "other/one", plugin="one", groups=["acme"]) + _plugin_repo(github, root, "other/two", plugin="two", groups=["acme"]) + assert run_cli("project", "new", APP, "--yes") == 1 + assert "one" in caplog.text and "two" in caplog.text + assert github.write_calls() == [] + + +def test_unpushable_are_not_candidates(github, root, app, run_cli): + _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"], permission="READ") + _plugin_repo(github, root, "other/two", plugin="two", groups=["acme"]) + assert run_cli("project", "new", APP, "--yes") == 0 + assert github.file("other/two", "two/projects/app/env") is not None + + +def test_multiple_with_tty_asks(github, root, app, run_cli): + _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"]) + _plugin_repo(github, root, "owner/two", plugin="two", groups=["acme"]) + assert run_cli("project", "new", APP, "--yes", tty=True, answers=["2"]) == 0 + assert github.file("owner/two", "two/projects/app/env") is not None + + +def test_multiple_with_tty_bad_answer_stops(github, root, app, run_cli): + _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"]) + _plugin_repo(github, root, "owner/two", plugin="two", groups=["acme"]) + assert run_cli("project", "new", APP, "--yes", tty=True, answers=["9"]) == 1 + assert github.write_calls() == [] + + +def test_zero_candidates_stops(github, root, app, run_cli): + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + + +def test_linked_and_non_github_plugins_are_not_candidates(github, root, app): + registry = PluginRegistry(root) + registry.add_repository(RegisteredRepository( + name="local", url="/some/path", + plugins=[AvailablePlugin(name="here", path="here")])) + registry.add(InstalledPlugin(name="here", version="1.0", source="/some/path", + installed_at="", path="repos/local/here")) + registry.add_repository(RegisteredRepository( + name="gitlab", url="https://gitlab.com/owner/g.git", + plugins=[AvailablePlugin(name="there", path="there")])) + registry.add(InstalledPlugin(name="there", version="1.0", + source="https://gitlab.com/owner/g.git", + installed_at="", path="repos/g/there")) + github.add_repo("owner/linked", {"README.md": "x\n"}) + registry.add_repository(RegisteredRepository( + name="linked", url="https://github.com/owner/linked.git", + plugins=[AvailablePlugin(name="dev", path="dev")])) + registry.add(InstalledPlugin(name="dev", version="1.0", + source="https://github.com/owner/linked.git", + installed_at="", path="plugins/dev", linked=True)) + ref = GitHubRef.parse(APP) + assert creator.plugin_candidates(registry, GhClient(), ref) == [] + + +def test_gh_is_called_once_per_repository(github, root, app): + clone = _plugin_repo(github, root, "owner/multi", plugin="one", groups=["acme"]) + assert clone.is_dir() + registry = PluginRegistry(root) + # 同じリポジトリの 2 つ目のプラグイン + github.commit("owner/multi", { + "registry.yml": "name: multi\nplugins:\n - name: one\n path: one\n" + " - name: two\n path: two\n", + "two/plugin.yml": "name: two\n", + }) + from devbase.plugin.repo_manager import refresh_repository + refresh_repository(registry, registry.list_repositories()[0].name) + install_plugin(registry, "https://github.com/owner/multi.git:two") + before = len(github.calls()) + assert len(creator.plugin_candidates(registry, GhClient(), GitHubRef.parse(APP))) == 2 + views = [c for c in github.calls()[before:] if c[:2] == ["repo", "view"]] + assert len(views) == 1 + + +# ── グループの決定 ────────────────────────────────────────────── + + +@pytest.mark.parametrize("groups, expected", [ + (["acme", "acme", "other"], "acme"), + (["solo"], "solo"), +]) +def test_group_is_the_most_common(github, root, app, run_cli, groups, expected): + _plugin_repo(github, root, "owner/plugins", groups=groups) + assert run_cli("project", "new", APP, "--yes") == 0 + assert github.file("owner/plugins", "team-a/projects/app/env") \ + == f"DEVBASE_ACCOUNT_GROUP={expected}\n" + + +def test_group_option_wins(github, root, app, run_cli): + _plugin_repo(github, root, "owner/plugins", groups=["acme", "acme"]) + assert run_cli("project", "new", APP, "--group", "mine", "--yes") == 0 + assert github.file("owner/plugins", "team-a/projects/app/env") \ + == "DEVBASE_ACCOUNT_GROUP=mine\n" + + +@pytest.mark.parametrize("groups", [["a", "b"], []], ids=["tie", "none"]) +def test_undecided_group_without_tty_stops(github, root, app, run_cli, groups): + _plugin_repo(github, root, "owner/plugins", groups=groups) + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + + +@pytest.mark.parametrize("groups", [["a", "b"], []], ids=["tie", "none"]) +def test_undecided_group_with_tty_asks(github, root, app, run_cli, groups): + _plugin_repo(github, root, "owner/plugins", groups=groups) + assert run_cli("project", "new", APP, "--yes", tty=True, answers=["typed"]) == 0 + assert github.file("owner/plugins", "team-a/projects/app/env") \ + == "DEVBASE_ACCOUNT_GROUP=typed\n" + + +@pytest.mark.parametrize("bad", ["default", "ubuntu", "123", "a b"]) +def test_bad_group_from_option_stops(github, root, app, run_cli, bad): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", APP, f"--group={bad}", "--yes") == 1 + assert github.write_calls() == [] + + +def test_bad_group_from_most_common_stops(github, root, app, run_cli): + _plugin_repo(github, root, "owner/plugins", groups=["default"]) + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + + +def test_bad_group_from_tty_stops(github, root, app, run_cli): + _plugin_repo(github, root, "owner/plugins") + assert run_cli("project", "new", APP, "--yes", tty=True, answers=["default"]) == 1 + assert github.write_calls() == [] + + +# ── 止まるとき ────────────────────────────────────────────────── + + +def test_unreadable_target_stops(github, root, run_cli): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + + +def test_existing_in_projects_stops(github, root, app, run_cli): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + (root / "projects" / "app").mkdir() + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + + +def test_broken_symlink_in_projects_stops(github, root, app, run_cli): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + (root / "projects" / "app").symlink_to("../gone") + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + + +def test_existing_in_the_plugin_stops(github, root, app, run_cli): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + github.commit("owner/plugins", {"team-a/projects/app/project.yml": "version: 1\n"}) + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + + +@pytest.mark.parametrize("name", ["../up", "a/b", "-x"]) +def test_bad_name_stops(github, root, app, run_cli, name): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", APP, f"--name={name}", "--yes") == 1 + assert github.write_calls() == [] + + +@pytest.mark.parametrize("state", ["empty-path", "missing-dir"]) +def test_registration_without_clone_stops(github, root, app, run_cli, caplog, state): + import shutil + + clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + registry = PluginRegistry(root) + repo = registry.list_repositories()[0] + if state == "empty-path": + from dataclasses import replace + registry.add_repository(replace(repo, local_path="")) + else: + shutil.rmtree(clone) + before = _plugins_yml(root) + assert run_cli("project", "new", APP, "--plugin", "team-a", "--yes") == 1 + assert github.write_calls() == [] + assert _plugins_yml(root) == before + assert "plugin repo remove" in caplog.text + assert "plugin repo add" in caplog.text + + +def test_merge_failure_leaves_the_local_side(github, root, app, run_cli, caplog): + _plugin_repo(github, root, "owner/plugins", groups=["acme"], + merge_error="required reviews") + before = _plugins_yml(root) + assert run_cli("project", "new", APP, "--yes") == 1 + assert _plugins_yml(root) == before + assert not (root / "projects" / "app").exists() + assert github.prs()[0]["url"] in caplog.text + assert "devbase plugin repo refresh" in caplog.text + + +def test_tty_decline_changes_nothing(github, root, app, run_cli): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", APP, tty=True, answers=["n"]) == 1 + assert github.write_calls() == [] + + +def test_unauthenticated(github, root, app, run_cli, caplog): + github.update(authed=False) + assert run_cli("project", "new", APP, "--yes") == 1 + assert "gh auth login" in caplog.text + + +def test_non_github_url_stops(github, root, run_cli): + assert run_cli("project", "new", "https://gitlab.com/owner/app", "--yes") == 1 + assert github.calls() == [] + + +def test_never_touches_docker(github, root, app, run_cli): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", APP, "--yes") == 0 + assert github.docker_calls() == [] From 49db5f3ed01e9d618596b5c7beae3a5b9bda099b Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:51:49 +0000 Subject: [PATCH 09/18] =?UTF-8?q?Feat:=20#514=20=E6=96=B0=E3=81=97?= =?UTF-8?q?=E3=81=84=E3=82=B3=E3=83=9E=E3=83=B3=E3=83=89=E3=81=AE=E3=82=B7?= =?UTF-8?q?=E3=82=A7=E3=83=AB=E8=A3=9C=E5=AE=8C=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- etc/_devbase | 24 ++++++++++++++++++++++++ etc/devbase-completion.bash | 26 ++++++++++++++++++++++---- tests/cli/test_completion.py | 18 ++++++++++++++++-- 3 files changed, 62 insertions(+), 6 deletions(-) diff --git a/etc/_devbase b/etc/_devbase index 937eb480..cbb79eef 100644 --- a/etc/_devbase +++ b/etc/_devbase @@ -99,6 +99,7 @@ _devbase() { 'profile:Start / stop compose profile services' 'open:Open the editor attached to the dev container' 'post-start:Redo the post-start steps on running instances' + 'new:Add a project for a GitHub repository to a plugin' ) container_subcommands=( @@ -143,9 +144,11 @@ _devbase() { 'info:Show plugin details' 'sync:Resync project symlinks' 'repo:Manage plugin repositories' + 'new:Add a new plugin to a repository on GitHub' ) repo_subcommands=( + 'new:Create (if needed) and register a repository on GitHub' 'add:Register a repository' 'remove:Unregister a repository' 'list:List registered repositories' @@ -276,6 +279,14 @@ _devbase() { '--context[Docker context]:context:' \ '1:name:_devbase_project_names' ;; + new) + _devbase_arguments 3 \ + '1:repository:' \ + '--plugin[Plugin to add the project to]:plugin:' \ + '--group[Account group of the project]:group:' \ + '--name[Project name]:name:' \ + '--yes[Proceed without confirming the plan]' + ;; *) _describe -t project-commands 'project command' project_subcommands ;; @@ -441,8 +452,21 @@ _devbase() { uninstall|update|info) _devbase_plugin_names ;; + new) + _devbase_arguments 3 \ + '1:repository:' \ + '--name[Plugin name]:name:' \ + '--public[Make the repository public when it is created]' \ + '--yes[Proceed without confirming the plan]' + ;; repo) case "$words[4]" in + new) + _devbase_arguments 4 \ + '1:repository:' \ + '--public[Make the repository public when it is created]' \ + '--yes[Proceed without confirming the plan]' + ;; add) _devbase_arguments 4 \ '1:url:_urls' \ diff --git a/etc/devbase-completion.bash b/etc/devbase-completion.bash index 9de05c7c..3a00c375 100644 --- a/etc/devbase-completion.bash +++ b/etc/devbase-completion.bash @@ -42,16 +42,16 @@ _devbase_complete_flags() { } # 以下の _devbase_complete_* は引数を取らず、cur・prev・words・cword とフラグの一覧 -# (ctx_flags・ps_flags・logs_flags・open_flags) を _devbase_completions の local から読む。 +# (ctx_flags・ps_flags・logs_flags・open_flags・plugin_new_flags・project_new_flags) を _devbase_completions の local から読む。 # どの関数も最後の文を if / case にし、当たらないときも終了の状態を 0 に保つ。 # 位置 2: 1 語目ごとのサブコマンド・フラグ・プロジェクト名。 _devbase_complete_subcommands() { # project / container は同じサブコマンド群 (container は非推奨だが補完は維持)。 - local project_subcommands="up down ps login logs scale build rebuild list profile open post-start" + local project_subcommands="up down ps login logs scale build rebuild list profile open post-start new" local container_subcommands="up down ps login logs scale build rebuild profile open" local env_subcommands="init sync list set get delete edit project export import keygen exec token encrypt decrypt rekey doctor backend" - local plugin_subcommands="list install uninstall update info sync repo" + local plugin_subcommands="list install uninstall update info sync repo new" local snapshot_subcommands="create list restore copy delete rotate" case "$prev" in login) @@ -167,6 +167,10 @@ _devbase_complete_project_args() { post-start) _devbase_complete_flags "$ctx_flags" "$cur" names ;; + # new の引数は GitHub のリポジトリなので、プロジェクト名は出さない (#514) + new) + _devbase_complete_flags "$project_new_flags" "$cur" + ;; esac } @@ -224,7 +228,7 @@ _devbase_complete_env_args() { # plugin subcommand arguments _devbase_complete_plugin_args() { - local repo_subcommands="add remove list refresh" + local repo_subcommands="new add remove list refresh" case "$prev" in list) COMPREPLY=($(compgen -W "--available" -- "$cur")) @@ -232,6 +236,9 @@ _devbase_complete_plugin_args() { install) _devbase_complete_flags "--link --all" "$cur" ;; + new) + _devbase_complete_flags "$plugin_new_flags" "$cur" + ;; uninstall|update|info) local devbase_root _devbase_resolve_root @@ -295,6 +302,9 @@ _devbase_complete_project_flags() { up|down|rebuild|scale|post-start) _devbase_complete_flags "$ctx_flags" "$cur" ;; + new) + _devbase_complete_flags "$project_new_flags" "$cur" + ;; esac } @@ -315,12 +325,18 @@ _devbase_complete_plugin_after_args() { if [ "${words[2]}" = "install" ]; then _devbase_complete_flags "--link --all" "$cur" fi + if [ "${words[2]}" = "new" ]; then + _devbase_complete_flags "$plugin_new_flags" "$cur" + fi # plugin repo subcommand arguments if [ "${words[2]}" = "repo" ]; then case "$prev" in add) _devbase_complete_flags "--name" "$cur" ;; + new) + _devbase_complete_flags "--public --yes" "$cur" + ;; remove|refresh) local devbase_root _devbase_resolve_root @@ -359,6 +375,8 @@ _devbase_completions() { local ps_flags="--all -a --context" local logs_flags="--follow -f --tail --context" local open_flags="--open-index --context" + local plugin_new_flags="--name --public --yes" + local project_new_flags="--plugin --group --name --yes" # --context の値 (docker context の名前) は補完しない。 if [ "$prev" = "--context" ]; then diff --git a/tests/cli/test_completion.py b/tests/cli/test_completion.py index fe9ee8e8..ee7d36b4 100644 --- a/tests/cli/test_completion.py +++ b/tests/cli/test_completion.py @@ -213,6 +213,13 @@ def test_bash_open_completes_its_flags(fake_root, words, cword): assert set(_bash_complete(words, cword, fake_root)) == {"--open-index", "--context"} +def test_zsh_completion_mentions_new(): + text = ZSH_COMPLETION.read_text() + for flag in ("--plugin", "--group", "--public", "--yes"): + assert f"'{flag}[" in text + assert "'new:" in text + + def test_zsh_completion_mentions_open(): text = ZSH_COMPLETION.read_text() assert text.count("'open:") == 3 # トップレベル / project / container @@ -281,7 +288,7 @@ def test_bash_context_value_is_not_completed(fake_root, words, cword): _CONTAINER_SUBCOMMANDS = ["up", "down", "ps", "login", "logs", "scale", "build", "rebuild", "profile", "open"] _ENV_SUBCOMMANDS = ["init", "sync", "list", "set", "get", "delete", "edit", "project", "export", "import", "keygen", "exec", "token", "encrypt", "decrypt", "rekey", "doctor", "backend"] -_PLUGIN_SUBCOMMANDS = ["list", "install", "uninstall", "update", "info", "sync", "repo"] +_PLUGIN_SUBCOMMANDS = ["list", "install", "uninstall", "update", "info", "sync", "repo", "new"] _SNAPSHOT_SUBCOMMANDS = ["create", "list", "restore", "copy", "delete", "rotate"] @@ -353,7 +360,11 @@ def fake_root_with_plugins(fake_root): ("devbase plugin uninstall ''", 3, _PLUGINS), ("devbase pl update ''", 3, _PLUGINS), ("devbase plugin info ''", 3, _PLUGINS), - ("devbase plugin repo ''", 3, ["add", "remove", "list", "refresh"]), + ("devbase plugin repo ''", 3, ["new", "add", "remove", "list", "refresh"]), + ("devbase plugin new '-'", 3, ["--name", "--public", "--yes"]), + ("devbase pl new ''", 3, []), + ("devbase project new '-'", 3, ["--plugin", "--group", "--name", "--yes"]), + ("devbase project new ''", 3, []), # 位置 3: snapshot / ss ("devbase snapshot create '-'", 3, ["--name", "--full"]), ("devbase ss restore '-'", 3, ["--point"]), @@ -374,6 +385,9 @@ def fake_root_with_plugins(fake_root): ("devbase plugin install src '-'", 4, ["--link", "--all"]), ("devbase pl install src ''", 4, []), ("devbase plugin repo add '-'", 4, ["--name"]), + ("devbase plugin repo new '-'", 4, ["--public", "--yes"]), + ("devbase plugin new owner/repo '-'", 4, ["--name", "--public", "--yes"]), + ("devbase project new owner/repo '-'", 4, ["--plugin", "--group", "--name", "--yes"]), ("devbase env set KEY '-'", 4, []), ]) def test_bash_completion_branches(fake_root_with_plugins, words, cword, expected): From 0f06ff8e70a87ab807282a8e52c8127e7ca1b956 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:56:14 +0000 Subject: [PATCH 10/18] =?UTF-8?q?Feat:=20#514=20TUI=20=E3=81=AE=E3=83=97?= =?UTF-8?q?=E3=83=A9=E3=82=B0=E3=82=A4=E3=83=B3=E3=81=AE=E3=83=A1=E3=83=8B?= =?UTF-8?q?=E3=83=A5=E3=83=BC=E3=82=92=E7=94=A8=E9=80=94=E3=81=A7=E5=88=86?= =?UTF-8?q?=E3=81=91=E3=80=81=E6=96=B0=E8=A6=8F=E8=BF=BD=E5=8A=A0=E3=81=AE?= =?UTF-8?q?=E5=85=A5=E5=8F=A3=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/devbase/plugin/creator.py | 1 + lib/devbase/tui/actions_plugin.py | 274 ++++++++++++------ tests/cli/tui/test_actions_plugin.py | 401 ++++++++++++++++++++------- 3 files changed, 495 insertions(+), 181 deletions(-) diff --git a/lib/devbase/plugin/creator.py b/lib/devbase/plugin/creator.py index 7d477442..d1ded204 100644 --- a/lib/devbase/plugin/creator.py +++ b/lib/devbase/plugin/creator.py @@ -424,6 +424,7 @@ def execute(registry: PluginRegistry, gh: GhClient, plan: CreationPlan) -> None: ) from e raise _apply_locally(registry, plan) + logger.info("%s %s を足しました", plan.kind, plan.name) def _apply_locally(registry: PluginRegistry, plan: CreationPlan) -> None: diff --git a/lib/devbase/tui/actions_plugin.py b/lib/devbase/tui/actions_plugin.py index 01a26cd7..1651092d 100644 --- a/lib/devbase/tui/actions_plugin.py +++ b/lib/devbase/tui/actions_plugin.py @@ -1,7 +1,8 @@ """plugin カテゴリの TUI 操作フロー (PLAN31_2 PR4)。 -``devbase plugin`` の全サブコマンド (list/install/uninstall/update/info/sync/migrate) -と ``plugin repo`` のサブ階層 (add/remove/list/refresh) を TUI から実行できるようにする。 +``devbase plugin`` の全サブコマンド (list/install/uninstall/update/info/sync/migrate/new)、 +``plugin repo`` のサブコマンド (new/add/remove/list/refresh) と ``project new`` を、 +用途で分けた 2 階層のメニューから実行できるようにする (#514)。 引数は ``tui.menu`` の収集ヘルパで CLI parser と同じ属性値 (plan 2.3 契約表) を集め、 ``tui.dispatch.dispatch_group`` 経由で既存ハンドラ ``cmd_plugin`` へ委譲する (ロジック二重実装なし)。 @@ -25,29 +26,47 @@ logger = get_logger(__name__) -# plugin サブコマンド (表示順 = ハイライト既定順)。閲覧系の list を先頭に置き、 -# Enter 連打で安全な一覧表示へ到達できるようにする。value は cmd_plugin の subcommand 名 -# (repo のみサブ階層メニューへの分岐)。--available は y/N で聞かず独立した -# メニュー項目にする (非破壊操作の確認プロンプト廃止)。 -_PLUGIN_OPS: list[tuple[str, str]] = [ - ("導入済み一覧 (list)", "list"), - ("利用可能一覧 (list --available)", "list-available"), - ("インストール (install)", "install"), - ("アンインストール (uninstall)", "uninstall"), - ("更新 (update)", "update"), - ("詳細表示 (info)", "info"), - ("プロジェクトリンク再同期 (sync)", "sync"), - ("レガシー構成の移行 (migrate)", "migrate"), - ("リポジトリ管理 (repo)", "repo"), +# 第 1 階層は用途で分ける (表示順 = ハイライト既定順)。閲覧だけの「見る」を先頭に置き、 +# Enter 連打で安全な一覧表示へ到達できるようにする。 +_PLUGIN_GROUPS: list[tuple[str, str]] = [ + ("見る", "view"), + ("新規追加", "new"), + ("導入・更新", "install-update"), + ("削除", "remove"), + ("保守", "maintain"), ] -# plugin repo サブ階層 (表示順 = ハイライト既定順)。value は repo_command 名。 -_REPO_OPS: list[tuple[str, str]] = [ - ("リポジトリ一覧 (list)", "list"), - ("リポジトリ登録 (add)", "add"), - ("リポジトリ削除 (remove)", "remove"), - ("リポジトリ更新 (refresh)", "refresh"), -] +# 第 2 階層。value は ``_OP_HANDLERS`` のキー。--available は y/N で聞かず独立した +# メニュー項目にする (非破壊操作の確認プロンプト廃止)。 +_GROUP_OPS: dict[str, list[tuple[str, str]]] = { + "view": [ + ("導入済み一覧 (list)", "list"), + ("利用可能一覧 (list --available)", "list-available"), + ("詳細表示 (info)", "info"), + ("リポジトリ一覧 (repo list)", "repo-list"), + ], + "new": [ + ("プロジェクト (project new)", "new-project"), + ("プラグイン (plugin new)", "new-plugin"), + ("リポジトリ (plugin repo new)", "new-repo"), + ], + "install-update": [ + ("インストール (install)", "install"), + ("更新 (update)", "update"), + ("リポジトリ登録 (repo add)", "repo-add"), + ("リポジトリ更新 (repo refresh)", "repo-refresh"), + ], + "remove": [ + ("アンインストール (uninstall)", "uninstall"), + ("リポジトリ削除 (repo remove)", "repo-remove"), + ], + "maintain": [ + ("プロジェクトリンク再同期 (sync)", "sync"), + ("レガシー構成の移行 (migrate)", "migrate"), + ], +} + +_NEW_REPOSITORY_PROMPT = "GitHub のリポジトリ (URL か owner/repo)" # 中止系番兵は flow と同一オブジェクトを再公開する (呼び出し側・テストの契約)。 _ARG_CANCEL = flow.ARG_CANCEL @@ -128,23 +147,22 @@ def _select_repository(devbase_root: Path, message: str, *, # --------------------------------------------------------------------------- def _select_operation(): - """plugin 操作を選ぶサブメニュー。 + """第 1 階層 (用途) を選ぶメニュー。 - 戻り値: サブコマンド文字列 / ``MENU_BACK`` (Esc・← → トップへ戻る) / ``None`` - (Ctrl-C 中止)。 + 戻り値: 用途の値 / ``MENU_BACK`` (Esc・← → トップへ戻る) / ``None`` (Ctrl-C 中止)。 """ return menu.select(f"plugin 操作を選択 {menu.HINT_BACK}:", - list(_PLUGIN_OPS), back=True, search=False) + list(_PLUGIN_GROUPS), back=True, search=False) -def _select_repo_operation(): - """plugin repo 操作を選ぶサブ階層メニュー。 +def _select_group_operation(group: str): + """第 2 階層 (用途の中の操作) を選ぶメニュー。 - 戻り値: repo_command 文字列 / ``MENU_BACK`` (Esc・← → plugin メニューへ戻る) / - ``None`` (Ctrl-C 中止)。 + 戻り値: 操作の値 / ``MENU_BACK`` (Esc・← → 第 1 階層へ戻る) / ``None`` (Ctrl-C 中止)。 """ - return menu.select(f"リポジトリ操作を選択 {menu.HINT_BACK}:", - list(_REPO_OPS), back=True, search=False) + label = next(text for text, value in _PLUGIN_GROUPS if value == group) + return menu.select(f"{label}: 操作を選択 {menu.HINT_BACK}:", + list(_GROUP_OPS[group]), back=True, search=False) # --------------------------------------------------------------------------- @@ -180,36 +198,6 @@ def _op_info(devbase_root: Path): return _dispatch(devbase_root, "info", name=name) -_OP_HANDLERS = { - # list 系は引数収集なしで即実行 (--available はメニュー項目で分岐)。 - "list": lambda root: _dispatch(root, "list", available=False), - "list-available": lambda root: _dispatch(root, "list", available=True), - "install": _op_install, - "uninstall": _op_uninstall, - "update": _op_update, - "info": _op_info, - # sync / migrate は引数なし (plan 2.3: 属性なし)。即実行。 - "sync": lambda root: _dispatch(root, "sync"), - "migrate": lambda root: _dispatch(root, "migrate"), -} - - -@flow.collect_args -def _run_operation(devbase_root: Path, op: str): - """選択された plugin 操作の引数を収集して ``cmd_plugin`` へ委譲する。 - - 戻り値: dispatch の rc (``int``) / ``_ARG_CANCEL`` (Esc・確認拒否で引数収集を - 中止 = サブメニューへ戻る) / ``None`` (選択・入力中の Ctrl-C → 全体中止)。 - 破壊的な uninstall は実行前に確認する (plan 3.4)。 - """ - handler = _OP_HANDLERS.get(op) - if handler is None: - # 到達しない (メニュー値は _PLUGIN_OPS に限定される)。保守的に no-op。 - logger.error("未知の操作です: %s", op) - raise flow.BackOut - return handler(devbase_root) - - def _op_repo_add(devbase_root: Path): url = flow.need(menu.text( "登録するリポジトリの URL (GitHub は owner/repo 短縮形も可)", @@ -262,40 +250,158 @@ def _run_repo_operation(devbase_root: Path, op: str): return handler(devbase_root) +# --------------------------------------------------------------------------- +# 新規追加: 値を集めて計画を確かめ、CLI のハンドラへ --yes 相当で渡す (#514 の決定 5) +# --------------------------------------------------------------------------- + +def _creation_context(devbase_root: Path): + from devbase.plugin.github import GhClient + from devbase.plugin.registry import PluginRegistry + + return PluginRegistry(Path(devbase_root)), GhClient() + + +def _confirm_plan(plan) -> None: + """作成の計画を示して確認する。拒否 / Esc なら ``BackOut`` で戻る。""" + print(plan.describe()) + flow.confirm_or_back("この計画で進めますか?") + + +def _op_new_repo(devbase_root: Path): + from devbase.plugin import creator + + repo = flow.need(menu.text(_NEW_REPOSITORY_PROMPT, allow_empty=False)) + public = flow.need(menu.confirm( + "新しく作るときに公開しますか (--public)?", default=False)) + registry, gh = _creation_context(devbase_root) + try: + plan = creator.plan_repo(registry, gh, repo, public=public) + except DevbaseError as e: + logger.error("%s", e) + return 1 + if not plan.noop_reason: + _confirm_plan(plan) + return _dispatch(devbase_root, "repo", repo_command="new", + repo=repo, public=public, yes=True) + + +def _op_new_plugin(devbase_root: Path): + from devbase.plugin import creator + + repo = flow.need(menu.text(_NEW_REPOSITORY_PROMPT, allow_empty=False)) + name = flow.need(menu.text("プラグインの名前 (空でリポジトリ名)", allow_empty=True)) or None + registry, gh = _creation_context(devbase_root) + try: + plan = creator.plan_plugin(registry, gh, repo, name=name) + except DevbaseError as e: + logger.error("%s", e) + return 1 + _confirm_plan(plan) + return _dispatch(devbase_root, "new", repo=repo, name=name, public=False, yes=True) + + +def _select_target(candidates): + """入れ先の候補から 1 件選ばせる。候補が 1 件なら選択を出さない。""" + if len(candidates) == 1: + return candidates[0].plugin + choices = [(c.label, c.plugin) for c in candidates] + return flow.back_as_cancel(menu.select( + f"入れ先のプラグインを選択 {menu.HINT_BACK}:", choices, back=True, search=False)) + + +def _op_new_project(devbase_root: Path): + from devbase.commands.project import cmd_project_new + from devbase.plugin import creator + from devbase.plugin.github import GitHubRef + + repo = flow.need(menu.text(_NEW_REPOSITORY_PROMPT, allow_empty=False)) + name = flow.need(menu.text("プロジェクトの名前 (空でリポジトリ名)", allow_empty=True)) or None + registry, gh = _creation_context(devbase_root) + try: + ref = GitHubRef.parse(repo) + gh.ensure_ready() + candidates = creator.plugin_candidates(registry, gh, ref) + if not candidates: + logger.error("入れ先のプラグインがありません。push できるプラグインを導入してください") + return 1 + plugin = flow.need(_select_target(candidates)) + target = next(c for c in candidates if c.plugin == plugin) + group = flow.need(menu.text("アカウントグループ", + default=creator.suggest_group(registry, target), + allow_empty=False)) + plan = creator.plan_project(registry, gh, repo, plugin=plugin, group=group, name=name) + except DevbaseError as e: + logger.error("%s", e) + return 1 + _confirm_plan(plan) + return dispatch_group(cmd_project_new, devbase_root, "new", repo=repo, name=name, + plugin=plugin, group=group, yes=True) + + +_OP_HANDLERS = { + # list 系は引数収集なしで即実行 (--available はメニュー項目で分岐)。 + "list": lambda root: _dispatch(root, "list", available=False), + "list-available": lambda root: _dispatch(root, "list", available=True), + "install": _op_install, + "uninstall": _op_uninstall, + "update": _op_update, + "info": _op_info, + # sync / migrate は引数なし (plan 2.3: 属性なし)。即実行。 + "sync": lambda root: _dispatch(root, "sync"), + "migrate": lambda root: _dispatch(root, "migrate"), + "new-project": _op_new_project, + "new-plugin": _op_new_plugin, + "new-repo": _op_new_repo, + "repo-list": lambda root: _run_repo_operation(root, "list"), + "repo-add": lambda root: _run_repo_operation(root, "add"), + "repo-remove": lambda root: _run_repo_operation(root, "remove"), + "repo-refresh": lambda root: _run_repo_operation(root, "refresh"), +} + + +@flow.collect_args +def _run_operation(devbase_root: Path, op: str): + """選択された plugin 操作の引数を収集して ``cmd_plugin`` へ委譲する。 + + 戻り値: dispatch の rc (``int``) / ``_ARG_CANCEL`` (Esc・確認拒否で引数収集を + 中止 = サブメニューへ戻る) / ``None`` (選択・入力中の Ctrl-C → 全体中止)。 + 破壊的な uninstall は実行前に確認する (plan 3.4)。 + """ + handler = _OP_HANDLERS.get(op) + if handler is None: + # 到達しない (メニュー値は _GROUP_OPS に限定される)。保守的に no-op。 + logger.error("未知の操作です: %s", op) + raise flow.BackOut + return handler(devbase_root) + + # --------------------------------------------------------------------------- # メニューループ # --------------------------------------------------------------------------- -def _repo_menu(devbase_root: Path): - """plugin repo のサブ階層メニューを回す。 +def _group_menu(devbase_root: Path, group: str): + """用途のメニューを回す。 - 戻り値 (``flow.menu_loop`` のプロトコル): ``menu.MENU_BACK`` (Esc・← で plugin - メニューへ戻る) / ``None`` (Ctrl-C 全体中止)。操作実行後は (出力確認の一時停止 - 後) サブ階層メニューに留まり、引数収集を中止 (``_ARG_CANCEL``) した場合も再表示する。 + 戻り値 (``flow.menu_loop`` のプロトコル): ``menu.MENU_BACK`` (Esc・← で第 1 階層へ + 戻る) / ``None`` (Ctrl-C 全体中止)。操作の実行後は (出力確認の一時停止後) 用途の + メニューに留まり、引数収集を中止 (``_ARG_CANCEL``) した場合も再表示する。 """ - return flow.menu_loop(_select_repo_operation, - lambda op: _run_repo_operation(devbase_root, op)) + return flow.menu_loop(lambda: _select_group_operation(group), + lambda op: _run_operation(devbase_root, op)) def run(devbase_root: Path): - """プラグイン操作カテゴリ。操作選択 → 引数収集 → ``cmd_plugin`` へ委譲。 + """プラグイン操作カテゴリ。用途 → 操作 → 引数収集 → ``cmd_plugin`` へ委譲。 戻り値プロトコル (トップループが ``is`` 同一性で判定する。actions_project と同じ): - - ``menu.MENU_BACK``: plugin メニューで Esc/← (トップメニューへ戻る)。操作を - 実行しても (出力確認の一時停止後) plugin メニューに留まり、Esc/← で初めて - トップへ戻る。 + - ``menu.MENU_BACK``: 第 1 階層で Esc/← (トップメニューへ戻る)。 - ``None``: Ctrl-C による全体中止。 - repo はサブ階層メニュー (``_repo_menu``) へ分岐する。repo 側も実行後はそこに - 留まり、Esc/← (``MENU_BACK``) で plugin メニューへ戻る (``_ARG_CANCEL`` 相当に - 読み替えて再表示する)。 + 用途のメニューは自身で操作を完結し、Esc/← (``MENU_BACK``) で戻ったら第 1 階層を + 再表示する (``_ARG_CANCEL`` 相当に読み替える)。 """ - def _run(op): - if op == "repo": - rc = _repo_menu(devbase_root) - # repo 階層は自身で操作を完結する。Esc/← (MENU_BACK) で戻ったら plugin - # メニューを再表示し、Ctrl-C (None) はそのまま全体中止へ伝搬する。 - return _ARG_CANCEL if rc is menu.MENU_BACK else rc - return _run_operation(devbase_root, op) + def _run(group): + rc = _group_menu(devbase_root, group) + return _ARG_CANCEL if rc is menu.MENU_BACK else rc return flow.menu_loop(_select_operation, _run) diff --git a/tests/cli/tui/test_actions_plugin.py b/tests/cli/tui/test_actions_plugin.py index ffc616ed..05fde2b5 100644 --- a/tests/cli/tui/test_actions_plugin.py +++ b/tests/cli/tui/test_actions_plugin.py @@ -84,21 +84,36 @@ def _no_dispatch(monkeypatch): # run(): plugin メニューのループと戻り値プロトコル # --------------------------------------------------------------------------- +def _in_group(monkeypatch, group, *ops): + """第 1 階層で ``group`` を選び、第 2 階層で ``ops`` を順に選ぶスタブを置く。""" + monkeypatch.setattr(actions_plugin, "_select_operation", _seq(group, menu.MENU_BACK)) + seen = [] + select = _seq(*ops, menu.MENU_BACK) + + def _select_group(chosen): + seen.append(chosen) + return select() + + monkeypatch.setattr(actions_plugin, "_select_group_operation", _select_group) + return seen + + def test_run_executes_then_stays_in_submenu(monkeypatch, tmp_path): - """操作を実行 → plugin メニューに留まり、Esc/← (MENU_BACK) で初めてトップへ戻る。""" + """操作を実行 → 用途のメニューに留まり、Esc/← (MENU_BACK) で 1 つずつ戻る。""" captured = _capture_dispatch(monkeypatch) - monkeypatch.setattr(actions_plugin, "_select_operation", _seq("sync", menu.MENU_BACK)) + seen = _in_group(monkeypatch, "maintain", "sync") assert actions_plugin.run(tmp_path) is menu.MENU_BACK assert captured["subcommand"] == "sync" assert captured["devbase_root"] == tmp_path + assert seen == ["maintain", "maintain"], "実行の後は同じ用途のメニューを再表示する" def test_run_executes_nonzero_then_back(monkeypatch, tmp_path): - """非0 を返す操作でも実行後は plugin メニューに留まり、戻りは MENU_BACK。""" + """非0 を返す操作でも実行後はメニューに留まり、戻りは MENU_BACK。""" from devbase.commands import plugin as plugin_mod calls = [] monkeypatch.setattr(plugin_mod, "cmd_plugin", lambda root, args: calls.append(1) or 1) - monkeypatch.setattr(actions_plugin, "_select_operation", _seq("sync", menu.MENU_BACK)) + _in_group(monkeypatch, "maintain", "sync") assert actions_plugin.run(tmp_path) is menu.MENU_BACK assert calls == [1], "操作は実行される (rc は終了コードへは伝搬しない)" @@ -120,13 +135,8 @@ def test_run_ctrl_c_aborts(monkeypatch, tmp_path): def test_run_arg_cancel_reshows_menu(monkeypatch, tmp_path): - """引数収集を中止 (_ARG_CANCEL) すると plugin メニューを再表示し、再選択で実行する。""" - # 1 回目: install (→ 引数収集中止) / 2 回目: sync (→ 実行) / 3 回目: MENU_BACK - select = _seq("install", "sync", menu.MENU_BACK) - select_calls = [] - monkeypatch.setattr(actions_plugin, "_select_operation", - lambda: select_calls.append(1) or select()) - + """引数収集を中止 (_ARG_CANCEL) すると同じ用途のメニューを再表示し、再選択で実行する。""" + seen = _in_group(monkeypatch, "install-update", "install", "update") run_calls = [] def fake_run_op(root, op): @@ -136,78 +146,322 @@ def fake_run_op(root, op): monkeypatch.setattr(actions_plugin, "_run_operation", fake_run_op) assert actions_plugin.run(tmp_path) is menu.MENU_BACK - assert run_calls == ["install", "sync"] - assert len(select_calls) == 3, "引数中止と実行後に plugin メニューが再表示される" + assert run_calls == ["install", "update"] + assert len(seen) == 3, "引数中止と実行後に用途のメニューが再表示される" -def test_run_repo_back_reshows_plugin_menu(monkeypatch, tmp_path): - """repo サブ階層で Esc/← (MENU_BACK) を押すと plugin メニューへ戻る。""" +def test_run_group_back_reshows_plugin_menu(monkeypatch, tmp_path): + """用途のメニューで Esc/← (MENU_BACK) を押すと第 1 階層へ戻る。""" select_calls = [] monkeypatch.setattr(actions_plugin, "_select_operation", lambda: (select_calls.append(1), - "repo" if len(select_calls) == 1 else menu.MENU_BACK)[1]) - monkeypatch.setattr(actions_plugin, "_repo_menu", lambda root: menu.MENU_BACK) + "view" if len(select_calls) == 1 else menu.MENU_BACK)[1]) + monkeypatch.setattr(actions_plugin, "_group_menu", lambda root, group: menu.MENU_BACK) assert actions_plugin.run(tmp_path) is menu.MENU_BACK - assert len(select_calls) == 2, "repo から戻ると plugin メニューが再表示される" + assert len(select_calls) == 2, "用途のメニューから戻ると第 1 階層が再表示される" -def test_run_repo_back_then_plugin_back(monkeypatch, tmp_path): - """repo サブ階層は自身で操作を完結し、戻ると plugin メニューを再表示する。 - - 新仕様では repo サブ階層 (``_repo_menu``) は操作実行後もそこに留まり、戻りは - MENU_BACK のみ (rc を上位へ伝搬しない)。plugin 側はそれを受けてメニューを - 再表示し、さらに MENU_BACK でトップへ戻る。 - """ - repo_calls = [] - monkeypatch.setattr(actions_plugin, "_select_operation", _seq("repo", menu.MENU_BACK)) - monkeypatch.setattr(actions_plugin, "_repo_menu", - lambda root: repo_calls.append(1) or menu.MENU_BACK) - assert actions_plugin.run(tmp_path) is menu.MENU_BACK - assert repo_calls == [1], "repo サブ階層へ 1 度遷移してから plugin メニューへ戻る" +def test_run_group_ctrl_c_aborts(monkeypatch, tmp_path): + """用途のメニューで Ctrl-C (None) を受けたら全体中止を伝搬する。""" + monkeypatch.setattr(actions_plugin, "_select_operation", lambda: "view") + monkeypatch.setattr(actions_plugin, "_group_menu", lambda root, group: None) + assert actions_plugin.run(tmp_path) is None -def test_run_repo_ctrl_c_aborts(monkeypatch, tmp_path): - """repo サブ階層で Ctrl-C (None) を受けたら全体中止を伝搬する。""" - monkeypatch.setattr(actions_plugin, "_select_operation", lambda: "repo") - monkeypatch.setattr(actions_plugin, "_repo_menu", lambda root: None) +def test_ctrl_c_inside_an_operation_aborts_everything(monkeypatch, tmp_path): + """引数収集の Ctrl-C は 2 階層を抜けて全体中止になる。""" + called = _no_dispatch(monkeypatch) + _in_group(monkeypatch, "install-update", "install") + monkeypatch.setattr(menu, "text", lambda *a, **k: None) assert actions_plugin.run(tmp_path) is None + assert called == [] # --------------------------------------------------------------------------- -# _select_operation / _select_repo_operation: menu.select への委譲 +# メニューの構成 # --------------------------------------------------------------------------- -def test_select_operation_lists_all_ops(monkeypatch): +def test_select_operation_lists_the_purposes(monkeypatch): captured = {} def fake_select(message, choices, *, back, search): - captured.update(back=back, search=search, - values=[c[1] for c in choices]) - return "list" + captured.update(back=back, search=search, labels=[c[0] for c in choices]) + return choices[0][1] monkeypatch.setattr(menu, "select", fake_select) - assert actions_plugin._select_operation() == "list" + assert actions_plugin._select_operation() == "view" assert captured["back"] is True assert captured["search"] is False - # 閲覧系の list 2 種を先頭にしつつ全 9 操作 (repo 含む) を提示する。 - # --available は y/N で聞かず独立したメニュー項目で提供する。 - assert captured["values"] == [ - "list", "list-available", "install", "uninstall", "update", "info", - "sync", "migrate", "repo"] + assert captured["labels"] == ["見る", "新規追加", "導入・更新", "削除", "保守"] -def test_select_repo_operation_lists_all_ops(monkeypatch): +@pytest.mark.parametrize("group, values", [ + ("view", ["list", "list-available", "info", "repo-list"]), + ("new", ["new-project", "new-plugin", "new-repo"]), + ("install-update", ["install", "update", "repo-add", "repo-refresh"]), + ("remove", ["uninstall", "repo-remove"]), + ("maintain", ["sync", "migrate"]), +]) +def test_select_group_operation_lists_the_ops(monkeypatch, group, values): captured = {} def fake_select(message, choices, *, back, search): captured.update(back=back, values=[c[1] for c in choices]) - return "add" + return choices[0][1] monkeypatch.setattr(menu, "select", fake_select) - assert actions_plugin._select_repo_operation() == "add" + assert actions_plugin._select_group_operation(group) == values[0] assert captured["back"] is True - assert captured["values"] == ["list", "add", "remove", "refresh"] + assert captured["values"] == values + + +def test_every_menu_item_has_a_handler(): + items = [value for ops in actions_plugin._GROUP_OPS.values() for _, value in ops] + assert sorted(items) == sorted(actions_plugin._OP_HANDLERS) + + +@pytest.mark.parametrize("op, repo_command", [ + ("repo-list", "list"), ("repo-add", "add"), ("repo-remove", "remove"), + ("repo-refresh", "refresh"), +]) +def test_repo_items_reach_the_repo_operation(monkeypatch, tmp_path, op, repo_command): + seen = [] + monkeypatch.setattr(actions_plugin, "_run_repo_operation", + lambda root, value: seen.append(value) or 0) + assert actions_plugin._run_operation(tmp_path, op) == 0 + assert seen == [repo_command] + + +# --------------------------------------------------------------------------- +# 新規追加: 値を集めて CLI のハンドラへ渡す +# --------------------------------------------------------------------------- + +class _Plan: + def __init__(self, noop_reason=""): + self.noop_reason = noop_reason + + def describe(self): + return "作成の計画: テスト" + + +class _Target: + def __init__(self, plugin): + self.plugin = plugin + self.label = f"{plugin} (owner/r)" + + +def _texts(monkeypatch, *values): + monkeypatch.setattr(menu, "text", _seq(*values)) + + +def _capture_project(monkeypatch): + from devbase.commands import project as project_mod + captured = {} + + def _spy(root, args): + captured.update(vars(args)) + return 0 + + monkeypatch.setattr(project_mod, "cmd_project_new", _spy) + return captured + + +@pytest.fixture +def creation(monkeypatch): + """gh に触らないよう creator の読むだけの関数を差し替える。""" + from devbase.plugin import creator + from devbase.plugin.github import GhClient + + calls = {} + monkeypatch.setattr(GhClient, "ensure_ready", lambda self: None) + monkeypatch.setattr(creator, "plugin_candidates", lambda *a: [_Target("one")]) + monkeypatch.setattr(creator, "suggest_group", lambda *a: "acme") + + def _plan(kind): + def _record(registry, gh, value, **kwargs): + calls[kind] = (value, kwargs) + return _Plan() + return _record + + for kind in ("repo", "plugin", "project"): + monkeypatch.setattr(creator, f"plan_{kind}", _plan(kind)) + return calls + + +def test_new_repo_passes_values_with_yes(monkeypatch, tmp_path, creation, capsys): + from devbase.commands import plugin as plugin_mod + captured = {} + monkeypatch.setattr(plugin_mod, "cmd_plugin", + lambda root, args: captured.update(vars(args)) or 0) + _texts(monkeypatch, "owner/repo") + answers = _seq(True, True) + monkeypatch.setattr(menu, "confirm", lambda *a, **k: answers()) + assert actions_plugin._run_operation(tmp_path, "new-repo") == 0 + assert captured == {"subcommand": "repo", "repo_command": "new", "repo": "owner/repo", + "public": True, "yes": True} + assert creation["repo"] == ("owner/repo", {"public": True}) + assert "作成の計画" in capsys.readouterr().out + + +def test_new_repo_public_defaults_to_no(monkeypatch, tmp_path, creation): + _capture_dispatch(monkeypatch) + _texts(monkeypatch, "owner/repo") + defaults = [] + + def fake_confirm(message, *, default=False): + defaults.append(default) + return True + + monkeypatch.setattr(menu, "confirm", fake_confirm) + assert actions_plugin._run_operation(tmp_path, "new-repo") == 0 + assert defaults[0] is False + + +def test_new_repo_noop_skips_the_confirmation(monkeypatch, tmp_path): + from devbase.plugin import creator + from devbase.plugin.github import GhClient + monkeypatch.setattr(GhClient, "ensure_ready", lambda self: None) + monkeypatch.setattr(creator, "plan_repo", lambda *a, **k: _Plan("登録済み")) + captured = _capture_dispatch(monkeypatch) + _texts(monkeypatch, "owner/repo") + answers = [] + monkeypatch.setattr(menu, "confirm", lambda *a, **k: answers.append(1) or False) + assert actions_plugin._run_operation(tmp_path, "new-repo") == 0 + assert len(answers) == 1, "公開の確認だけで、計画の確認は出さない" + assert captured["repo_command"] == "new" + + +def test_new_plugin_passes_values(monkeypatch, tmp_path, creation): + from devbase.commands import plugin as plugin_mod + captured = {} + monkeypatch.setattr(plugin_mod, "cmd_plugin", + lambda root, args: captured.update(vars(args)) or 0) + _texts(monkeypatch, "owner/repo", "team-a") + monkeypatch.setattr(menu, "confirm", lambda *a, **k: True) + assert actions_plugin._run_operation(tmp_path, "new-plugin") == 0 + assert captured == {"subcommand": "new", "repo": "owner/repo", "name": "team-a", + "public": False, "yes": True} + + +def test_new_plugin_empty_name_is_none(monkeypatch, tmp_path, creation): + captured = _capture_dispatch(monkeypatch) + _texts(monkeypatch, "owner/repo", "") + monkeypatch.setattr(menu, "confirm", lambda *a, **k: True) + assert actions_plugin._run_operation(tmp_path, "new-plugin") == 0 + assert captured["name"] is None + assert creation["plugin"][1]["name"] is None + + +def test_new_project_single_candidate_shows_no_select(monkeypatch, tmp_path, creation): + captured = _capture_project(monkeypatch) + prompts = [] + + def fake_text(message, *, default=None, allow_empty=True): + prompts.append((message, default)) + return {0: "owner/app", 1: "web", 2: "typed"}[len(prompts) - 1] + + monkeypatch.setattr(menu, "text", fake_text) + monkeypatch.setattr(menu, "select", lambda *a, **k: pytest.fail("候補 1 件で選択を出した")) + monkeypatch.setattr(menu, "confirm", lambda *a, **k: True) + assert actions_plugin._run_operation(tmp_path, "new-project") == 0 + assert captured == {"subcommand": "new", "repo": "owner/app", "name": "web", + "plugin": "one", "group": "typed", "yes": True} + assert prompts[2][1] == "acme", "グループは案を既定値にする" + assert creation["project"] == ("owner/app", {"plugin": "one", "group": "typed", + "name": "web"}) + + +def test_new_project_multiple_candidates_select(monkeypatch, tmp_path, creation): + from devbase.plugin import creator + monkeypatch.setattr(creator, "plugin_candidates", + lambda *a: [_Target("one"), _Target("two")]) + captured = _capture_project(monkeypatch) + _texts(monkeypatch, "owner/app", "", "acme") + offered = {} + + def fake_select(message, choices, *, back, search): + offered.update(values=[c[1] for c in choices], back=back) + return "two" + + monkeypatch.setattr(menu, "select", fake_select) + monkeypatch.setattr(menu, "confirm", lambda *a, **k: True) + assert actions_plugin._run_operation(tmp_path, "new-project") == 0 + assert offered == {"values": ["one", "two"], "back": True} + assert captured["plugin"] == "two" + assert captured["name"] is None + + +def test_new_project_without_candidates_reports(monkeypatch, tmp_path, creation, caplog): + from devbase.plugin import creator + monkeypatch.setattr(creator, "plugin_candidates", lambda *a: []) + captured = _capture_project(monkeypatch) + _texts(monkeypatch, "owner/app", "") + assert actions_plugin._run_operation(tmp_path, "new-project") == 1 + assert captured == {} + assert "入れ先" in caplog.text + + +@pytest.mark.parametrize("op", ["new-project", "new-plugin", "new-repo"]) +def test_new_esc_at_the_repository_goes_back(monkeypatch, tmp_path, creation, op): + called = _no_dispatch(monkeypatch) + monkeypatch.setattr(menu, "text", lambda *a, **k: menu.MENU_BACK) + assert actions_plugin._run_operation(tmp_path, op) is actions_plugin._ARG_CANCEL + assert called == [] + + +@pytest.mark.parametrize("op", ["new-project", "new-plugin", "new-repo"]) +def test_new_ctrl_c_at_the_repository_aborts(monkeypatch, tmp_path, creation, op): + called = _no_dispatch(monkeypatch) + monkeypatch.setattr(menu, "text", lambda *a, **k: None) + assert actions_plugin._run_operation(tmp_path, op) is None + assert called == [] + + +@pytest.mark.parametrize("answer, expected", [ + (False, actions_plugin._ARG_CANCEL), + (menu.MENU_BACK, actions_plugin._ARG_CANCEL), + (None, None), +]) +def test_new_plan_confirmation_refused(monkeypatch, tmp_path, creation, answer, expected): + called = _no_dispatch(monkeypatch) + captured = _capture_project(monkeypatch) + _texts(monkeypatch, "owner/app", "", "acme") + monkeypatch.setattr(menu, "confirm", lambda *a, **k: answer) + assert actions_plugin._run_operation(tmp_path, "new-project") is expected + assert called == [] + assert captured == {} + + +@pytest.mark.parametrize("step", ["select", "group"]) +def test_new_project_esc_in_the_middle_goes_back(monkeypatch, tmp_path, creation, step): + from devbase.plugin import creator + monkeypatch.setattr(creator, "plugin_candidates", + lambda *a: [_Target("one"), _Target("two")]) + captured = _capture_project(monkeypatch) + if step == "select": + _texts(monkeypatch, "owner/app", "") + monkeypatch.setattr(menu, "select", lambda *a, **k: menu.MENU_BACK) + else: + _texts(monkeypatch, "owner/app", "", menu.MENU_BACK) + monkeypatch.setattr(menu, "select", lambda *a, **k: "one") + assert actions_plugin._run_operation(tmp_path, "new-project") is actions_plugin._ARG_CANCEL + assert captured == {} + + +def test_new_plan_error_is_reported_with_rc_1(monkeypatch, tmp_path, creation, caplog): + from devbase.errors import RepositoryError + from devbase.plugin import creator + + def _boom(*_a, **_k): + raise RepositoryError("push する権限がありません") + + monkeypatch.setattr(creator, "plan_plugin", _boom) + called = _no_dispatch(monkeypatch) + _texts(monkeypatch, "owner/repo", "") + assert actions_plugin._run_operation(tmp_path, "new-plugin") == 1 + assert called == [] + assert "push する権限がありません" in caplog.text # --------------------------------------------------------------------------- @@ -489,53 +743,6 @@ def test_run_repo_operation_remove_ctrl_c_aborts(monkeypatch, tmp_path): assert called == [] -# --------------------------------------------------------------------------- -# _repo_menu: サブ階層メニューのループ -# --------------------------------------------------------------------------- - -def test_repo_menu_back_returns_menu_back(monkeypatch, tmp_path): - monkeypatch.setattr(actions_plugin, "_select_repo_operation", - lambda: menu.MENU_BACK) - assert actions_plugin._repo_menu(tmp_path) is menu.MENU_BACK - - -def test_repo_menu_ctrl_c_aborts(monkeypatch, tmp_path): - monkeypatch.setattr(actions_plugin, "_select_repo_operation", lambda: None) - assert actions_plugin._repo_menu(tmp_path) is None - - -def test_repo_menu_arg_cancel_reshows_submenu(monkeypatch, tmp_path): - """引数収集を中止 (_ARG_CANCEL) するとサブ階層メニューを再表示し、再選択で実行する。""" - # 1 回目: add (→ 引数収集中止) / 2 回目: list (→ 実行) / 3 回目: MENU_BACK - select = _seq("add", "list", menu.MENU_BACK) - select_calls = [] - monkeypatch.setattr(actions_plugin, "_select_repo_operation", - lambda: select_calls.append(1) or select()) - - run_calls = [] - - def fake_run_op(root, op): - run_calls.append(op) - return actions_plugin._ARG_CANCEL if op == "add" else 0 - - monkeypatch.setattr(actions_plugin, "_run_repo_operation", fake_run_op) - - assert actions_plugin._repo_menu(tmp_path) is menu.MENU_BACK - assert run_calls == ["add", "list"] - assert len(select_calls) == 3, "引数中止と実行後にサブ階層メニューが再表示される" - - -def test_repo_menu_executes_then_stays(monkeypatch, tmp_path): - """repo 操作を実行 → サブ階層に留まり、Esc/← (MENU_BACK) で plugin メニューへ。""" - monkeypatch.setattr(actions_plugin, "_select_repo_operation", - _seq("list", menu.MENU_BACK)) - calls = [] - monkeypatch.setattr(actions_plugin, "_run_repo_operation", - lambda root, op: calls.append(op) or 1) - assert actions_plugin._repo_menu(tmp_path) is menu.MENU_BACK - assert calls == ["list"], "操作は実行される (rc は終了コードへは伝搬しない)" - - # --------------------------------------------------------------------------- # 名前選択ヘルパ (_select_name / _select_installed_plugin / _select_repository) # --------------------------------------------------------------------------- From 58a20dda614a10fe019cf8022e4a330628e6343c Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 02:59:57 +0000 Subject: [PATCH 11/18] =?UTF-8?q?Docs:=20#514=20=E6=96=B0=E3=81=97?= =?UTF-8?q?=E3=81=84=E3=82=B3=E3=83=9E=E3=83=B3=E3=83=89=E3=81=AE=E6=96=87?= =?UTF-8?q?=E6=9B=B8=E3=81=A8=E5=A4=89=E6=9B=B4=E5=B1=A5=E6=AD=B4=E3=82=92?= =?UTF-8?q?=E6=9B=B8=E3=81=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit プラグインリポジトリの定義(0 件でもよい)を plugin-yml-reference に入れる。 用語集の 3 語は設計の工程で入っており、glossary.md は render --check で一致している。 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 ++++++ docs/developer/architecture.md | 4 ++ docs/plugin-dev/plugin-yml-reference.md | 3 +- docs/plugin-dev/quickstart.md | 14 ++++++ docs/user/cli-reference/02-project.md | 46 +++++++++++++++++-- docs/user/cli-reference/04-plugin.md | 60 +++++++++++++++++++++++++ docs/user/cli-reference/README.md | 4 +- 7 files changed, 138 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 239eaeb4..127b309b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ ## [Unreleased] +### Added +- **リポジトリ・プラグイン・プロジェクトを新規に足すコマンドを足しました(#514)。** + `devbase plugin repo new `・`devbase plugin new `・`devbase project new ` は、GitHub の URL か + `owner/repo` を受け、権限の確認からファイルの配置・PR・マージ・手元への取り込み・登録までを 1 回で行います。 + 新しいリポジトリは private で作り、`--public` のときだけ公開します。`project new` は入れ先のプラグインとアカウントグループを + 引数か既存の値から決め、決まらないときは端末で聞きます。変更の前に作成の計画を示して確認し、端末が無いときは `--yes` が要ります。 + コンテナは起動しません。`gh` が要るのはこの 3 つのコマンドだけです。 + +### Changed +- **`devbase list` の TUI のプラグインのメニューを、用途で分けた 2 階層に組み直しました(#514)。** + 第 1 階層は「見る」「新規追加」「導入・更新」「削除」「保守」で、これまでの操作はすべてこの下にあります。 + 「新規追加」から上の 3 つの操作を実行できます。 + ## [4.1.1] - 2026-10-31 派生イメージ(`general`・`php`・`php85`)の言語サーバ(#236)は、`devbase build` でイメージを建て直した後に届きます。 diff --git a/docs/developer/architecture.md b/docs/developer/architecture.md index 4886f9a0..14e66244 100644 --- a/docs/developer/architecture.md +++ b/docs/developer/architecture.md @@ -154,6 +154,10 @@ flowchart LR | `registry.py` | `plugins.yml` の読み書き | | `installer.py` | プラグインの install / uninstall。Git clone やローカルリンクに対応 | | `repo_manager.py` | リポジトリの add / remove / list / refresh | +| `github.py` | GitHub の参照の解決と `gh` の呼び出し(権限・作成・PR・マージ) | +| `scaffold.py` | 作成フローの雛形の生成と `registry.yml` への追記 | +| `publish.py` | 一時の浅い clone から既定ブランチへ変更を入れる | +| `creator.py` | 作成フローの計画(読むだけ)と実行。入れ先とグループの決定 | | `updater.py` | プラグインの update とマイグレーション | | `syncer.py` | `plugins/*/projects/*` から `projects/` へのシンボリックリンク同期 | | `info.py` | プラグイン詳細情報の表示 | diff --git a/docs/plugin-dev/plugin-yml-reference.md b/docs/plugin-dev/plugin-yml-reference.md index ec2828a3..f8159d4c 100644 --- a/docs/plugin-dev/plugin-yml-reference.md +++ b/docs/plugin-dev/plugin-yml-reference.md @@ -285,7 +285,8 @@ ecommerce/ `plugin.yml` は Plugin ごとに 1 ファイルです。1 つのリポジトリで複数の Plugin を配布する場合は、 Plugin ごとにディレクトリを分けてそれぞれに `plugin.yml` を置き、リポジトリルートの -`registry.yml` に一覧を記述します。 +`registry.yml` に一覧を記述します。リポジトリの直下に `registry.yml` があればプラグインリポジトリとして登録でき、 +収めたプラグインは 0 件(`plugins: []`)でもかまいません。 ``` my-registry/ diff --git a/docs/plugin-dev/quickstart.md b/docs/plugin-dev/quickstart.md index 9ceb366d..ddecd551 100644 --- a/docs/plugin-dev/quickstart.md +++ b/docs/plugin-dev/quickstart.md @@ -12,6 +12,20 @@ devbase用のPluginを作成し、公開するまでの手順を解説します --- +## コマンドで足す + +GitHub で公開するプラグインは、`gh` が使えればコマンド 1 つで足せます。ファイルの配置・PR・マージ・手元への取り込みまで終わります。 + +```bash +devbase plugin repo new your-user/my-plugins # プラグインリポジトリを用意して登録する +devbase plugin new your-user/my-plugins --name my-plugin # プラグインを足して導入する +devbase project new your-user/my-app --plugin my-plugin --group personal # プロジェクトを足す +``` + +詳しくは [plugin グループ](../user/cli-reference/04-plugin.md#作成フローplugin-new--plugin-repo-new--project-new-に共通)を参照してください。この後の節は、手でファイルを置くときの手順です。 + +--- + ## 1. Pluginリポジトリの作成 ### 1.1 Gitリポジトリの初期化 diff --git a/docs/user/cli-reference/02-project.md b/docs/user/cli-reference/02-project.md index 404d97e7..37307122 100644 --- a/docs/user/cli-reference/02-project.md +++ b/docs/user/cli-reference/02-project.md @@ -447,6 +447,34 @@ devbase rebuild [name] |-----------|------|------| | `name` | いいえ | 対象プロジェクト名(省略時はカレント) | +## `devbase project new` + +GitHub のリポジトリのプロジェクトをプラグインへ足し、手元へ反映します。コンテナは起動しません。 + +``` +devbase project new [--plugin <名前>] [--group <名前>] [--name <名前>] [--yes] +``` + +| パラメータ | 必須 | 説明 | +|-----------|------|------| +| `repo` | はい | 対象の GitHub のリポジトリ(`owner/repo`・URL。[作成フロー](04-plugin.md#作成フローplugin-new--plugin-repo-new--project-new-に共通)) | +| `--plugin` | いいえ | 入れ先のプラグイン | +| `--group` | いいえ | アカウントグループ | +| `--name` | いいえ | プロジェクトの名前(既定: リポジトリ名) | +| `--yes` | いいえ | 計画の確認を省く。端末が無いときは必須 | + +入れ先のプラグインの `projects/<名前>/` に `project.yml`・`compose.yml`・`env` を足す PR を作ってマージし、手元へ取り込んで `projects/` へ反映します。`` はプロジェクト名として解決されません。 + +入れ先のプラグインは次の順で決まります。 + +1. `--plugin` があればそれを使います(導入済みで push できることを確かめます) +2. 無ければ、導入済みで push できるプラグインを候補にし、対象と同じ owner の候補があれば、それに絞ります +3. 候補が 1 件ならそれを計画に示します。複数なら端末で選びます。端末が無ければ候補を出して終了コード 1 で止まります。候補が 0 件のときも終了コード 1 で止まります + +アカウントグループは、`--group`、入れ先の既存プロジェクトの最多の値の順で決まります。最多が同数か値が無いときは端末で聞き、端末が無ければ終了コード 1 で止まります。どの出所の値も `DEVBASE_ACCOUNT_GROUP` の規則(`default` などの予約語は使えません)を通します。 + +対象のリポジトリを読めないとき、同じ名前のプロジェクトが `projects/` か入れ先にあるときは、何も変えずに終了コード 1 で止まります。 + ## `devbase project list` `$DEVBASE_ROOT/projects/` 配下のプロジェクトを `NAME` / `PLUGIN` / `STATUS` の一覧で @@ -494,16 +522,28 @@ build / rebuild を選べます。先頭(Enter 1 回で決まる位置)は * | カテゴリ | 選べる操作 | |---------|-----------| | 環境変数 | キーの一覧と編集 / sync / init / OpenBao の接続設定 | -| プラグイン | 導入済み一覧 / 利用可能一覧 / install / uninstall / update / info / sync / migrate / repo 管理 | +| プラグイン | 用途で分けたメニューから選びます(下の表) | | スナップショット | list / create / restore / copy / delete / rotate | | ステータス | 環境全体の状態を表示(`devbase status` 相当) | +プラグインのメニューは第 1 階層が用途で、各項目の中に操作があります。 + +| 用途 | 選べる操作 | +|------|-----------| +| 見る | 導入済み一覧 / 利用可能一覧 / 詳細 / リポジトリ一覧 | +| 新規追加 | プロジェクト / プラグイン / リポジトリ | +| 導入・更新 | インストール / 更新 / リポジトリ登録 / リポジトリ更新 | +| 削除 | アンインストール / リポジトリ削除 | +| 保守 | リンクの再同期 / レガシー構成の移行 | + +新規追加は、CLI の `project new`・`plugin new`・`plugin repo new` と同じ値を順に聞きます。入れ先のプラグインは候補が 2 件以上のときに選択肢で出し、グループは入れ先の案を既定値にします。最後に作成の計画を示して確認します。 + - 確認プロンプト (y/N) が出るのは破壊的操作(plugin uninstall / plugin repo remove / - snapshot restore / snapshot delete / 環境変数のキーの削除)のみで、その他は CLI 既定値で即実行します + snapshot restore / snapshot delete / 環境変数のキーの削除)と新規追加の計画だけで、その他は CLI 既定値で即実行します - 操作の出力後は Enter キーで一覧へ戻ります(出力が流れて読めなくなるのを防ぐため) - 環境変数の「キーの一覧と編集」と「OpenBao の接続設定」は [環境変数の TUI](03-env.md#tui-でのキーの編集と-openbao-の接続設定) を参照してください - TUI が提供しない細かいオプション(`env get/export/import`、 - `plugin install --link/--all`、`snapshot create --full`、`logs --follow` 等)は + `plugin install --link/--all`、`plugin new --public`、`snapshot create --full`、`logs --follow` 等)は CLI を使用してください - questionary 未導入時は従来の番号入力(選択 → up)にフォールバックします diff --git a/docs/user/cli-reference/04-plugin.md b/docs/user/cli-reference/04-plugin.md index f6350567..e55bcc8c 100644 --- a/docs/user/cli-reference/04-plugin.md +++ b/docs/user/cli-reference/04-plugin.md @@ -87,6 +87,66 @@ devbase plugin migrate `--link` でインストールしたプラグインは移行対象外です。 +## 作成フロー(`plugin new` / `plugin repo new` / `project new` に共通) + +リポジトリ・プラグイン・プロジェクトを足すコマンドは、権限の確認からマージ、手元への取り込み、登録までを 1 回で行います。 + +- **対象は GitHub だけです。** 引数は `owner/repo`・`https://github.com/owner/repo[.git]`・`git@github.com:owner/repo[.git]` のどれかです。`git@` の形で渡すと clone の URL も `git@` になります +- **`gh` が要ります。** 入っていない・ログインしていないときは、何も変えずに次の操作を出して終了コード 1 で止まります。認証は `gh` と `git` の設定に任せます +- **変更の前に作成の計画を示します。** 端末があれば確認を取り、断ると何も変えません(終了コード 1)。端末が無いときは `--yes` が要ります +- **作業は一時の浅い clone で行います。** 手元の `repos/` の clone に未コミットの変更があっても失われません。手元への取り込みは早送りだけで、できないときは変更を残したまま止まります +- **マージは 1 回だけ試します。** CI を待たず、`--auto` と `--admin` を使いません。必須のレビューや検査でマージできないときは、PR の URL とマージの後に打つコマンドを出して終了コード 1 で止まり、`plugins.yml` は変わりません +- **コンテナは起動しません。** 起動は `devbase up` を別に打ちます + +作業ブランチは `devbase/new-<種類>-<名前>` で、マージのときに消えます。同じブランチが既にあると止まり、開いている PR があればその URL を出します。 + +## `devbase plugin new` + +GitHub のリポジトリへプラグインを足して導入します。 + +``` +devbase plugin new [--name <名前>] [--public] [--yes] +``` + +| パラメータ | 必須 | 説明 | +|-----------|------|------| +| `repo` | はい | GitHub のリポジトリ([作成フロー](#作成フローplugin-new--plugin-repo-new--project-new-に共通)) | +| `--name` | いいえ | プラグインの名前(既定: リポジトリ名)。英数字で始まり英数字・`.`・`-`・`_` だけからなる形 | +| `--public` | いいえ | リポジトリを新しく作るときに公開する(既定: private)。既存のリポジトリの公開範囲は変えない | +| `--yes` | いいえ | 計画の確認を省く。端末が無いときは必須 | + +`<名前>/plugin.yml`・`<名前>/projects/.gitkeep`・`registry.yml` の項目を足す PR を作ってマージし、手元へ取り込んで導入します。 + +未登録のリポジトリは、先に `plugin repo new` と同じ分岐を通します。リポジトリの分の変更とプラグインの PR は別の変更として順に入り、登録はプラグインの PR のマージの後です。 + +同じ名前のプラグインが `registry.yml` か導入済みの中にあるとき、同じ名前のパスがリポジトリにあるときは、何も変えずに終了コード 1 で止まります。登録の手元の clone が無いときは、登録し直すコマンドを出して止まります。 + +## `devbase plugin repo new` + +プラグインリポジトリを用意して登録します。 + +``` +devbase plugin repo new [--public] [--yes] +``` + +| パラメータ | 必須 | 説明 | +|-----------|------|------| +| `repo` | はい | GitHub のリポジトリ([作成フロー](#作成フローplugin-new--plugin-repo-new--project-new-に共通)) | +| `--public` | いいえ | リポジトリを新しく作るときに公開する(既定: private) | +| `--yes` | いいえ | 計画の確認を省く。端末が無いときは必須 | + +| リポジトリ | push | `registry.yml` | 動作 | 終了コード | +|-----------|------|----------------|------|-----------| +| 無い | owner に作れる | — | 作る → 最初のコミットを既定ブランチへ直接入れる → 登録 | `0` | +| 無い | owner に作れない | — | 何もしない | `1` | +| 空 | できる | — | 最初のコミットを既定ブランチへ直接入れる → 登録 | `0` | +| ある | できる | 無い | `registry.yml` を足す PR → マージ → 登録 | `0` | +| ある | できる | ある | 登録だけ | `0` | +| 登録済み | できる | — | 何もしない(確認も出ない) | `0` | +| ある・空・登録済み | できない | — | 何もしない | `1` | + +最初のコミットを直接入れるのは、GitHub が空のリポジトリに PR を作れないためです。読めない private のリポジトリは「無い」と同じに見えるので、`gh repo create` の失敗の出力を示して止まります。 + ## `devbase plugin repo add` プラグインリポジトリを登録します。 diff --git a/docs/user/cli-reference/README.md b/docs/user/cli-reference/README.md index 1b77e959..b65e6a3e 100644 --- a/docs/user/cli-reference/README.md +++ b/docs/user/cli-reference/README.md @@ -5,9 +5,9 @@ devbase の全コマンドの構文、オプション、使用例をまとめた | ファイル | 内容 | |---------|------| | [トップレベルコマンド](01-toplevel.md) | `init` / `status` / `bin/rc` | -| [project グループ](02-project.md) | コンテナのライフサイクル管理・一覧(`up` / `down` / `login` / `ps` / `logs` / `scale` / `build` / `rebuild` / `open` / `post-start` / `profile` / `list`)と非推奨の `container` グループ | +| [project グループ](02-project.md) | コンテナのライフサイクル管理・一覧(`up` / `down` / `login` / `ps` / `logs` / `scale` / `build` / `rebuild` / `open` / `post-start` / `profile` / `list` / `new`)と非推奨の `container` グループ | | [env グループ](03-env.md) | 環境変数の管理(`init` / `sync` / `list` / `set` / `get` / `delete` / `edit` / `project` / `keygen` / `encrypt` / `decrypt` / `exec` / `token` / `rekey` / `doctor` / `export` / `import`) | -| [plugin グループ](04-plugin.md) | プラグインの管理(`list` / `install` / `uninstall` / `update` / `info` / `sync` / `migrate` / `repo *`) | +| [plugin グループ](04-plugin.md) | プラグインの管理(`list` / `install` / `uninstall` / `update` / `info` / `sync` / `migrate` / `new` / `repo *`) | | [snapshot グループ](05-snapshot.md) | スナップショットの管理(`create` / `list` / `restore` / `copy` / `delete` / `rotate`) | ## コマンド体系 From ba2b2560a84a6185424b04f2f9985cf72f3d48f1 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 03:05:21 +0000 Subject: [PATCH 12/18] =?UTF-8?q?Docs:=20#514=20=E5=90=8D=E5=89=8D?= =?UTF-8?q?=E3=81=AE=E5=BD=A2=E3=81=A8=E3=83=97=E3=83=AD=E3=82=B8=E3=82=A7?= =?UTF-8?q?=E3=82=AF=E3=83=88=E3=81=AE=E8=B5=B0=E6=9F=BB=E3=81=AE=E4=BB=95?= =?UTF-8?q?=E6=A7=98=E3=81=B8=E4=BD=9C=E6=88=90=E3=83=95=E3=83=AD=E3=83=BC?= =?UTF-8?q?=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 作成フローのプラグイン名とプロジェクト名の確認、`project new` のグループの案が 名前の規則を使うので、確定仕様の使う場所と走査の表へ足す。 Co-Authored-By: Claude Opus 5.5 --- docs/specifications/cli-argument-resolution.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/specifications/cli-argument-resolution.md b/docs/specifications/cli-argument-resolution.md index b553f61d..7105a2e0 100644 --- a/docs/specifications/cli-argument-resolution.md +++ b/docs/specifications/cli-argument-resolution.md @@ -214,7 +214,7 @@ zsh(`etc/_devbase`)は、サブコマンドの分岐から `_arguments` を | 規則 | `[A-Za-z0-9][A-Za-z0-9._-]*` に**全体が**一致する。先頭が英数字なので `.`・`..`・`-x`・空文字は当たらない。`/`・`\`・空白・非 ASCII は含められない | | Python | `devbase.utils.names.is_single_segment_name(value)`。`re.fullmatch` で見るため、末尾の改行も不一致になる | | shell | `_SINGLE_SEGMENT_NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]*$'`。比較は関数の中で `local LC_ALL=C` にして行う | -| 使う場所 | shell: `maybe_cd_project`、`build` の衝突の判定。Python: `_resolve_project_name`、`_named_lifecycle_project`、`_build_single_image` | +| 使う場所 | shell: `maybe_cd_project`、`build` の衝突の判定。Python: `_resolve_project_name`、`_named_lifecycle_project`、`_build_single_image`、作成フローのプラグイン名とプロジェクト名の確認(`plugin/creator.py` の `_checked_name`) | プロジェクト名とイメージ名は同じ規則を使う。どちらも「決まった親ディレクトリ(`projects/` / `containers/`)の直下の 1 つの名前」を表すためである。`/` と `..` だけを弾く拒否リストは採らない @@ -283,8 +283,8 @@ shell が Python を呼ばずに同じ正規表現を文字列で持つのは、 プラグインの同期(`discover_projects`・実ディレクトリの知らせ)、`plugin info` と `status` の プラグインのプロジェクト数(どちらも `discover_projects` を通す)、`status` のコンテナの状態、 `project list`、見つからない名前での `up` の候補、`project migrate-config`、`env export`、 -`env doctor`、`env encrypt` / `env decrypt`、`env backend status` と backend の移行が、`projects/` を -走査するときの名前の条件としてこの述語を呼ぶ。ディレクトリの条件(`is_dir()`・壊れた symlink を +`env doctor`、`env encrypt` / `env decrypt`、`env backend status` と backend の移行、`project new` の +グループの案が、`projects/` を走査するときの名前の条件としてこの述語を呼ぶ。ディレクトリの条件(`is_dir()`・壊れた symlink を 拾う `is_symlink()`・`compose.yml` の有無)は走査ごとに持つ。名前の条件はディレクトリの条件より 先に見る(壊れた symlink を名前だけで外せ、`stat` を打たないため)。同期が張った symlink の掃除と、 別名の衝突を見るための実ディレクトリの集合は、プロジェクトを数えないため述語を通さない。 @@ -302,6 +302,7 @@ shell が Python を呼ばずに同じ正規表現を文字列で持つのは、 | `env doctor` の重なりと除外設定の確認 | `commands/env_ops.py` | `names.project_dirs` | `is_dir()` | | `env encrypt` / `env decrypt` の対象 | `commands/env_migrate.py` | `names.project_dirs` | `is_dir()` | | `env backend status` と backend の移行の対象 | `commands/env_backend.py` | `names.project_dirs` の後に `SecretRef.for_project`(拒まれた名前は黙って外す) | `is_dir()` | +| `project new` のグループの案(入れ先のプラグインの `projects/` を数える `suggest_group`) | `plugin/creator.py` | `names.project_dirs` | `is_dir()` | `plugin info` と `status` のプラグインのプロジェクト数は、述語を個別に持たず `discover_projects` を 通す。同期と同じ関数を呼ぶことで、ディレクトリの条件まで同期と構造的に一致する。 From ca8047739e893755200bd79d0e750ac9dcd81890 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 03:51:07 +0000 Subject: [PATCH 13/18] =?UTF-8?q?Fix:=20#514=20=E4=BD=9C=E6=88=90=E3=83=95?= =?UTF-8?q?=E3=83=AD=E3=83=BC=E3=81=AE=E3=83=AC=E3=83=93=E3=83=A5=E3=83=BC?= =?UTF-8?q?=E3=81=AE=E6=8C=87=E6=91=98=207=20=E4=BB=B6=E3=82=92=E7=9B=B4?= =?UTF-8?q?=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - plugin new の registry.yml の PR がマージできないときは、打ち直しを案内する - 組織の members_can_create_repositories が返らないときは判定不能として進める - plugin new・plugin repo new と TUI も機密を注入せず、gh を利用者の設定で動かす - 一時の clone と push は登録の URL で行う - 一時の clone の外を指す書き込みを止める - project new は登録の path が既定ブランチと違えば書き込む前に止める - 取り込みの前にプロジェクト一覧を控えて refresh の移行へ渡す 偽の gh も、組織の設定を owner にしか返さない形へ揃える。 Co-Authored-By: Claude Opus 5.5 --- issues/issue-514-design.md | 13 +++++-- lib/devbase/cli.py | 15 ++++++-- lib/devbase/plugin/creator.py | 37 +++++++++++++++++-- lib/devbase/plugin/github.py | 8 +++-- lib/devbase/plugin/publish.py | 19 ++++++++-- lib/devbase/plugin/repo_manager.py | 17 +++++++-- lib/devbase/plugin/scaffold.py | 8 +++++ lib/devbase/tui/actions_plugin.py | 3 ++ tests/cli/test_project_new_dispatch.py | 23 ++++++++++-- tests/cli/tui/test_actions_plugin.py | 10 ++++++ tests/plugin/creation_harness.py | 28 +++++++++++---- tests/plugin/test_create_plugin.py | 50 +++++++++++++++++++++++++- tests/plugin/test_create_project.py | 25 +++++++++++++ tests/plugin/test_create_repo.py | 12 +++++-- tests/plugin/test_github.py | 2 ++ tests/plugin/test_publish.py | 46 ++++++++++++++++++++++++ 16 files changed, 290 insertions(+), 26 deletions(-) diff --git a/issues/issue-514-design.md b/issues/issue-514-design.md index ba154cc4..8488eddc 100644 --- a/issues/issue-514-design.md +++ b/issues/issue-514-design.md @@ -206,7 +206,8 @@ graph TD - push できるのは `viewerPermission` が `ADMIN`・`MAINTAIN`・`WRITE` のとき - owner に作れるのは次のどちらかのとき: - owner が `gh api user` の `login` と同じである - - `gh api user/memberships/orgs/` の `state` が `active` で、`role` が `admin` か、組織の `members_can_create_repositories` が真である + - `gh api user/memberships/orgs/` の `state` が `active` で、`role` が `admin` か、組織の `members_can_create_repositories` が偽でない + - `members_can_create_repositories` は組織の owner にしか返らない。値が無いときは判定できないので計画へ進め、作れなければ `gh repo create` の出力を示して終了する(書き込みは起きない) - 読めない private のリポジトリは「無い」と同じに見える。`gh repo create` が失敗するので、その出力を示して終了する ### 経路ごとの反映と登録 @@ -222,6 +223,7 @@ graph TD | `_pull_ff_only` | 登録の `repo.local_path` の clone | | `refresh_repository` | 登録の `repo.name` | | `install_plugin` | `:<プラグイン名>`(登録の `repo.url`) | +| 一時の clone と push | 登録の `repo.url`(SSH の認証だけの利用者が https で止まらない) | `plugin new` と `project new` は、計画の確定の前に、登録の clone を確かめる。対象は `plugin new` では `_find_registered` が見つけた登録、`project new` では入れ先のプラグインの登録である。 @@ -235,6 +237,12 @@ graph TD - **案内**: `devbase plugin repo remove ` の後に `devbase plugin repo add ` を打つ。`repo remove` はそのリポジトリから導入したプラグインもアンインストールするので、`devbase plugin install` を打ち直すことも案内に書く - **`plugin repo new` は確かめない**: 登録済みの経路は clone に触らないので、`local_path` が空でも push できれば何もせず 0 で終わる +`project new` は、計画の確定の前に、入れ先のプラグインの登録の `path` を既定ブランチの `registry.yml` と比べる。項目が無いか違うときは、GitHub にも手元にも書かず終了コード 1 で止まり、`devbase plugin repo refresh ` を案内する。古い `path` へマージすると、続く取り込みが新しい `path` を登録し、足したプロジェクトが `projects/` に現れないまま 0 で終わるためである。 + +一時の clone へ書くパスは、symlink と `..` を解決して clone の中に収まることを確かめ、外を指すものがあれば 1 ファイルも書かずに止まる。clone の中身は他人が書いたもので、書き込みが利用者の手元のファイルへ届かないようにする。 + +登録済みの経路の `_pull_ff_only` の前に、導入済みのプラグインのプロジェクト一覧を控え、`refresh_repository` へ渡す。取り込みにプラグインの改名や移動が入っていても、移行先を見つけられる。 + | コマンド | リポジトリ | 既定ブランチへの反映 | 登録と反映(反映の後に行う) | | --- | --- | --- | --- | | `plugin repo new` | 無い・空 | 最初のコミットの直接の push | `add_repository` | @@ -334,6 +342,7 @@ sequenceDiagram | push | リポジトリを作った後なら、そのリポジトリ | 同じコマンドの再実行 | | 同じブランチが既にある | 既存のブランチと PR | 開いている PR の URL | | マージ | PR とブランチ | PR の URL。マージの後に打つコマンド(`plugin repo add`・`plugin repo refresh`・`plugin install`) | +| `plugin new` の `registry.yml` の PR | PR とブランチ。プラグインの PR はまだ無い。`plugins.yml` は元のまま | PR の URL。この PR をマージした後に同じ `plugin new` を打ち直す案内 | | 未登録のリポジトリへの `plugin new` のプラグインの PR | 先に反映した最初のコミットか `registry.yml` は既定ブランチに残る。`plugins.yml` は元のまま | 上の行に同じ | | 取り込み | マージ済み。手元は元のまま | 原因と `git -C status`、続けて打つコマンド | | 登録 | マージと取り込み済み | 既存のコマンドのエラーと、続けて打つコマンド | @@ -434,7 +443,7 @@ TUI は `creator` の読むだけの関数(候補とグループの案)を ### 決定 11: トークンをアプリで扱わないため、GitHub の操作は `gh` に任せる -権限の確認・リポジトリの作成・PR・マージを `gh` の呼び出しで行う。認証は利用者の `gh` の設定に任せる。 +権限の確認・リポジトリの作成・PR・マージを `gh` の呼び出しで行う。認証は利用者の `gh` の設定に任せる。機密の `GH_TOKEN` が環境変数に載ると `gh` がそのトークンで動くので、3 つのコマンドは機密を注入せず、TUI は `gh` を呼ぶ前に注入を取り除く。 採らなかった案: PyGithub を使う。トークンをアプリが受け取ることになる。 diff --git a/lib/devbase/cli.py b/lib/devbase/cli.py index ba7f3ef2..84bf92eb 100644 --- a/lib/devbase/cli.py +++ b/lib/devbase/cli.py @@ -954,7 +954,7 @@ def main(): cmd = args.command - _load_secret_env(cmd, getattr(args, 'subcommand', None), name=getattr(args, 'name', None)) + _load_secret_env(cmd, _injection_subcommand(args), name=getattr(args, 'name', None)) try: return _dispatch(cmd, args) @@ -981,8 +981,11 @@ def main(): # コンテナの bao へ token を届けるだけで、機密の値は要らない。注入するとサーバへの # 往復が増える (PLAN54)。 ('env', 'token'), - # プラグインへファイルを足すだけで機密を使わない。lifecycle の分岐より先に抜ける (#514)。 + # 作成フローの認証は利用者の gh の設定に任せる (#514 の決定 11)。機密の GH_TOKEN が + # 環境変数に載ると、gh は利用者のログインではなくそのトークンで作成・マージする。 ('project', 'new'), + ('plugin', 'new'), + ('plugin', 'repo new'), }) @@ -1030,7 +1033,15 @@ def _undeclared_current_project(root: Path) -> bool: return False +def _injection_subcommand(args) -> Optional[str]: + """注入の判定に使うサブコマンド。``plugin repo new`` は ``repo new`` の形で渡す""" + subcommand = getattr(args, 'subcommand', None) + repo_command = getattr(args, 'repo_command', None) + return f"{subcommand} {repo_command}" if repo_command else subcommand + + def _skip_secret_injection(cmd: str, subcommand: Optional[str]) -> bool: + cmd = GROUP_ALIASES.get(cmd, cmd) return ((cmd, None) in _NO_SECRET_INJECTION or (cmd, subcommand) in _NO_SECRET_INJECTION) diff --git a/lib/devbase/plugin/creator.py b/lib/devbase/plugin/creator.py index d1ded204..98f4c358 100644 --- a/lib/devbase/plugin/creator.py +++ b/lib/devbase/plugin/creator.py @@ -28,6 +28,7 @@ from .repo_manager import ( _find_registered, _pull_ff_only, + _snapshot_repo_projects, _url_to_repos_dirname, add_repository, refresh_repository, @@ -194,6 +195,8 @@ def plan_plugin( registered = _find_registered(registry, ref.clone_url) if registered is not None: _require_clone(registry, registered) + # 一時の clone と push も登録の URL で行う。SSH の認証だけの利用者が https で止まらない + ref = replace(ref, clone_url=registered.url) state, default_branch = _inspect(registry, gh, ref, registered) if registered is not None and state is not RepoState.HAS_REGISTRY: raise RepositoryError( @@ -346,6 +349,24 @@ def _decide_group( return validate_account_group(value) +def _require_current_path(gh: GhClient, target: PluginTarget) -> None: + """手元の登録の ``path`` が既定ブランチの ``registry.yml`` と同じことを確かめる (読むだけ) + + 古い ``path`` へマージすると、続く取り込みが新しい ``path`` を登録し、足したプロジェクトが + ``projects/`` に現れないまま 0 で終わる。 + """ + text = gh.read_file(target.ref, scaffold.REGISTRY_FILE) or '' + current = scaffold.registry_plugin_path(text, target.plugin) + if current == target.path: + return + raise RepositoryError( + f"プラグイン {target.plugin} の path が、{target.ref.full_name} の既定ブランチ " + f"({current or '項目なし'}) と手元の登録 ({target.path}) で違います。" + "次のコマンドで取り込んでから打ち直してください:\n" + f" devbase plugin repo refresh {target.repo.name}" + ) + + def plan_project( registry: PluginRegistry, gh: GhClient, value: str, *, plugin: Optional[str] = None, group: Optional[str] = None, @@ -363,6 +384,7 @@ def plan_project( target = _decide_target(registry, gh, ref, plugin, prompter) _require_clone(registry, target.repo) + _require_current_path(gh, target) destination = f"{target.path}/projects/{project}" if gh.read_file(target.ref, destination) is not None: raise RepositoryError(f"{target.ref.full_name} に {destination} が既にあります") @@ -385,7 +407,16 @@ def _reflect_repository(gh: GhClient, plan: CreationPlan) -> None: publish.push_initial(plan.ref, files, title=publish.pr_title(KIND_REPO, plan.ref.repo)) elif plan.state is RepoState.NO_REGISTRY: - publish.publish_change(gh, plan.ref, kind=KIND_REPO, name=plan.ref.repo, files=files) + try: + publish.publish_change(gh, plan.ref, kind=KIND_REPO, name=plan.ref.repo, files=files) + except publish.MergeFailed as e: + if plan.kind != KIND_PLUGIN: + raise + # プラグインの PR はまだ無いので、登録と導入ではなく打ち直しを案内する + raise RepositoryError( + f"{e}\nこの PR をマージした後に、同じコマンドを打ち直してください:\n" + f" devbase plugin new {plan.ref.clone_url} --name {plan.name}" + ) from e def _source_url(plan: CreationPlan) -> str: @@ -433,8 +464,10 @@ def _apply_locally(registry: PluginRegistry, plan: CreationPlan) -> None: if plan.registered is None: add_repository(registry, plan.ref.clone_url) else: + # 取り込みに改名や移動が入っていても refresh が移行先を見つけられるよう、先に控える + pre_pull = _snapshot_repo_projects(registry, plan.registered) _pull_ff_only(registry.devbase_root / plan.registered.local_path) - refresh_repository(registry, plan.registered.name) + refresh_repository(registry, plan.registered.name, pre_pull_projects=pre_pull) if plan.kind == KIND_PLUGIN: install_plugin(registry, f"{_source_url(plan)}:{plan.name}") except DevbaseError as e: diff --git a/lib/devbase/plugin/github.py b/lib/devbase/plugin/github.py index a01a3517..bfdbf880 100644 --- a/lib/devbase/plugin/github.py +++ b/lib/devbase/plugin/github.py @@ -137,7 +137,11 @@ def view_repo(self, ref: GitHubRef) -> Optional[RepoView]: ) def can_create_in(self, owner: str) -> bool: - """``owner`` の下にリポジトリを作れるか (読むだけ)""" + """``owner`` の下にリポジトリを作れるか (読むだけ) + + 組織の ``members_can_create_repositories`` は組織の owner にしか返らないので、値が無い + ときは判定できない。作れると見て進め、作れなければ ``gh repo create`` の失敗で止める。 + """ if owner.lower() == self.login().lower(): return True membership = self._read_api(f'user/memberships/orgs/{owner}') @@ -146,7 +150,7 @@ def can_create_in(self, owner: str) -> bool: if membership.get('role') == 'admin': return True org = self._read_api(f'orgs/{owner}') - return bool(org and org.get('members_can_create_repositories')) + return (org or {}).get('members_can_create_repositories') is not False def _read_api(self, path: str) -> Optional[dict]: """権限が無い・無いものは ``None``、それ以外の失敗は例外にする""" diff --git a/lib/devbase/plugin/publish.py b/lib/devbase/plugin/publish.py index 1826bf09..4d373dd2 100644 --- a/lib/devbase/plugin/publish.py +++ b/lib/devbase/plugin/publish.py @@ -7,6 +7,7 @@ from __future__ import annotations +import os import tempfile from pathlib import Path from typing import Dict, Optional @@ -47,17 +48,29 @@ def _git(clone: Path, *args: str) -> str: return result.stdout.strip() +def _inside(clone: Path, relative: str) -> Path: + """clone の中のパスを返す。symlink や ``..`` をたどって外へ出るものは止める + + clone の中身は他人が書いたものなので、書き込みが利用者の手元のファイルへ届かないようにする。 + """ + target = clone / relative + if not target.resolve().is_relative_to(clone.resolve()): + raise RepositoryError(f"{relative} はリポジトリの外を指しているので、書き込みません") + return target + + def _write_files(clone: Path, files: Dict[str, str]) -> None: + targets = {relative: _inside(clone, relative) for relative in files} for relative, text in files.items(): - target = clone / relative - if target.exists(): + target = targets[relative] + if os.path.lexists(target): raise RepositoryError(f"{relative} は既にあります。上書きしません") target.parent.mkdir(parents=True, exist_ok=True) target.write_text(text) def _add_to_registry(clone: Path, name: str) -> None: - path = clone / scaffold.REGISTRY_FILE + path = _inside(clone, scaffold.REGISTRY_FILE) path.write_text(scaffold.add_registry_entry(path.read_text(), name)) diff --git a/lib/devbase/plugin/repo_manager.py b/lib/devbase/plugin/repo_manager.py index d8239394..a2738f83 100644 --- a/lib/devbase/plugin/repo_manager.py +++ b/lib/devbase/plugin/repo_manager.py @@ -405,11 +405,21 @@ def show_repositories(registry: PluginRegistry) -> None: logger.info("Total: %d repository(ies)", len(repos)) +def _snapshot_repo_projects( + registry: PluginRegistry, repo: RegisteredRepository, +) -> dict[str, set[str]]: + """このリポジトリから導入したプラグインのプロジェクト名を pull の前に控える""" + from .updater import _snapshot_plugin_projects + return _snapshot_plugin_projects(registry, [ + p for p in registry.list_installed() if p.source == repo.url and not p.linked]) + + def refresh_repository( registry: PluginRegistry, name: str, *, sync: bool = True, + pre_pull_projects: Optional[dict[str, set[str]]] = None, ) -> None: """Refresh plugin list for a registered repository (git pull + re-read registry.yml). @@ -417,6 +427,8 @@ def refresh_repository( sync: If True (default), call sync_projects after updating metadata. Set to False when refreshing multiple repositories in a batch to avoid redundant sync calls — the caller should sync once at the end. + pre_pull_projects: Snapshot from ``_snapshot_repo_projects``, for callers + that pulled the clone themselves. Default: snapshot here before pulling. Raises RepositoryError if not found. """ @@ -440,10 +452,9 @@ def refresh_repository( # Snapshot installed plugin project names BEFORE git pull so that # migration can still detect where old projects moved even after # the working tree is updated by pull. - from .updater import _snapshot_plugin_projects installed = registry.list_installed() - repo_installed = [p for p in installed if p.source == repo.url and not p.linked] - pre_pull_projects = _snapshot_plugin_projects(registry, repo_installed) + if pre_pull_projects is None: + pre_pull_projects = _snapshot_repo_projects(registry, repo) try: _git_pull(clone_dir) diff --git a/lib/devbase/plugin/scaffold.py b/lib/devbase/plugin/scaffold.py index 6a86fd3a..d5ce7734 100644 --- a/lib/devbase/plugin/scaffold.py +++ b/lib/devbase/plugin/scaffold.py @@ -110,6 +110,14 @@ def registry_plugin_names(text: str) -> List[str]: return [entry.get('name', '') for entry in _load_registry(text).get('plugins') or []] +def registry_plugin_path(text: str, name: str) -> Optional[str]: + """``registry.yml`` の ``name`` の項目の ``path``。項目が無ければ ``None``""" + for entry in _load_registry(text).get('plugins') or []: + if entry.get('name') == name: + return (entry.get('path') or name).rstrip('/') + return None + + def _load_registry(text: str) -> dict: try: data = yaml.safe_load(text) diff --git a/lib/devbase/tui/actions_plugin.py b/lib/devbase/tui/actions_plugin.py index 1651092d..6e317a93 100644 --- a/lib/devbase/tui/actions_plugin.py +++ b/lib/devbase/tui/actions_plugin.py @@ -255,9 +255,12 @@ def _run_repo_operation(devbase_root: Path, op: str): # --------------------------------------------------------------------------- def _creation_context(devbase_root: Path): + from devbase.env import runtime as _runtime from devbase.plugin.github import GhClient from devbase.plugin.registry import PluginRegistry + # TUI は起動時の注入が載ったまま動く。gh は利用者の設定で動かす (#514 の決定 11) + _runtime.clear_injected() return PluginRegistry(Path(devbase_root)), GhClient() diff --git a/tests/cli/test_project_new_dispatch.py b/tests/cli/test_project_new_dispatch.py index 4a3446e5..a023da1a 100644 --- a/tests/cli/test_project_new_dispatch.py +++ b/tests/cli/test_project_new_dispatch.py @@ -32,8 +32,27 @@ def test_prefix_resolves_to_new(monkeypatch): assert sys.argv == ["devbase", "project", "new", "owner/repo"] -def test_secrets_are_not_injected(): - assert cli._skip_secret_injection("project", "new") +@pytest.mark.parametrize("argv", [ + ["project", "new", "owner/repo"], + ["plugin", "new", "owner/repo"], + ["pl", "new", "owner/repo"], + ["plugin", "repo", "new", "owner/repo"], + ["pl", "repo", "new", "owner/repo"], +]) +def test_creation_flows_leave_gh_to_the_users_login(argv): + """機密の GH_TOKEN が載ると、gh は利用者のログインではなくそのトークンで動く (決定 11)。""" + args = cli._create_parser().parse_args(argv) + assert cli._skip_secret_injection(args.command, cli._injection_subcommand(args)) + + +@pytest.mark.parametrize("argv", [ + ["plugin", "list"], + ["plugin", "repo", "add", "owner/repo"], + ["pl", "repo", "refresh", "name"], +]) +def test_other_plugin_commands_still_inject(argv): + args = cli._create_parser().parse_args(argv) + assert not cli._skip_secret_injection(args.command, cli._injection_subcommand(args)) def test_parser_arguments(): diff --git a/tests/cli/tui/test_actions_plugin.py b/tests/cli/tui/test_actions_plugin.py index 05fde2b5..ff8de263 100644 --- a/tests/cli/tui/test_actions_plugin.py +++ b/tests/cli/tui/test_actions_plugin.py @@ -826,3 +826,13 @@ def test_select_repository_empty_is_cancel(monkeypatch, tmp_path): assert actions_plugin._select_repository(tmp_path, "選択") \ is actions_plugin._ARG_CANCEL assert selects == [] + + +def test_creation_drops_injected_secrets_before_gh(monkeypatch, tmp_path): + """TUI は起動時の注入が載ったまま動くので、gh を呼ぶ前に落とす (#514 の決定 11)。""" + from devbase.env import runtime + + cleared = [] + monkeypatch.setattr(runtime, "clear_injected", lambda: cleared.append(True)) + actions_plugin._creation_context(tmp_path) + assert cleared == [True] diff --git a/tests/plugin/creation_harness.py b/tests/plugin/creation_harness.py index 6a17fbc4..f089ff50 100644 --- a/tests/plugin/creation_harness.py +++ b/tests/plugin/creation_harness.py @@ -64,8 +64,9 @@ def _gh_api(world, state, argv): org = state['orgs'].get(path.split('/', 1)[1]) if org is None: raise _Fail('gh: Not Found (HTTP 404)') - return json.dumps({ - 'members_can_create_repositories': org.get('members_can_create_repositories')}) + # 実の GitHub はこの値を組織の owner にしか返さない + return json.dumps({'members_can_create_repositories': True} + if org['role'] == 'admin' else {'login': path.split('/', 1)[1]}) if path.startswith('repos/'): _, owner, repo, _, file_path = path.split('/', 4) bare = world / 'git' / owner / f'{repo}.git' @@ -97,6 +98,9 @@ def _gh_repo_create(world, state, argv): full_name = argv[0] if full_name in state['repos']: raise _Fail('GraphQL: Name already exists on this account (createRepository)') + org = state['orgs'].get(full_name.split('/')[0]) + if org is not None and org['role'] != 'admin' and not org['can_create']: + raise _Fail('GraphQL: owner cannot create repositories (createRepository)') state['repos'][full_name] = { 'permission': 'ADMIN', 'visibility': 'public' if '--public' in argv else 'private', @@ -224,6 +228,12 @@ def update(self, **values) -> None: state.update(values) self._state_file.write_text(json.dumps(state)) + def ssh_only(self) -> None: + """https の URL を使えなくする (SSH の認証だけの利用者)。""" + text = self.gitconfig.read_text().replace('\tinsteadOf = https://github.com/\n', '') + self.gitconfig.write_text( + f'{text}[url "file://{self.world}/no-https/"]\n\tinsteadOf = https://github.com/\n') + def update_repo(self, full_name: str, **values) -> None: state = self.state() state['repos'][full_name].update(values) @@ -231,8 +241,7 @@ def update_repo(self, full_name: str, **values) -> None: def add_org(self, name, *, state='active', role='member', can_create=False): orgs = self.state()['orgs'] - orgs[name] = {'state': state, 'role': role, - 'members_can_create_repositories': can_create} + orgs[name] = {'state': state, 'role': role, 'can_create': can_create} self.update(orgs=orgs) def add_repo(self, full_name: str, files=None, **values) -> Path: @@ -247,8 +256,8 @@ def add_repo(self, full_name: str, files=None, **values) -> Path: pushes.unlink(missing_ok=True) return bare - def commit(self, full_name: str, files: dict, message='change') -> None: - """既定ブランチへ別の人が入れたコミットを作る。""" + def commit(self, full_name: str, files: dict, message='change', remove=()) -> None: + """既定ブランチへ別の人が入れたコミットを作る。値が ``Path`` なら symlink にする。""" bare = self.world / 'git' / f'{full_name}.git' work = self.world / 'seed' env = {**os.environ, 'GIT_CONFIG_GLOBAL': str(self.gitconfig)} @@ -258,7 +267,12 @@ def commit(self, full_name: str, files: dict, message='change') -> None: for path, text in files.items(): target = work / path target.parent.mkdir(parents=True, exist_ok=True) - target.write_text(text) + if isinstance(text, Path): + target.symlink_to(text) + else: + target.write_text(text) + for path in remove: + subprocess.run(['git', 'rm', '-rqf', path], cwd=work, check=True, env=env) subprocess.run(['git', 'add', '-A'], cwd=work, check=True, env=env) subprocess.run(['git', 'commit', '-q', '-m', message], cwd=work, check=True, env=env) subprocess.run([*GIT, 'push', '-q', 'origin', 'main'], cwd=work, check=True, env=env, diff --git a/tests/plugin/test_create_plugin.py b/tests/plugin/test_create_plugin.py index 19d5a76a..c7cc83ce 100644 --- a/tests/plugin/test_create_plugin.py +++ b/tests/plugin/test_create_plugin.py @@ -8,6 +8,7 @@ import yaml from devbase.commands.plugin import cmd_plugin_list +from devbase.plugin.installer import install_plugin from devbase.plugin.models import RegisteredRepository from devbase.plugin.registry import PluginRegistry from devbase.plugin.repo_manager import add_repository @@ -104,7 +105,7 @@ def test_repo_branch_that_ends_writes_nothing(github, root, run_cli, setup): if setup == "no-push": github.add_repo(FULL, {"README.md": "x\n"}, permission="READ") else: - github.add_org("owner", role="member") + github.add_org("owner", role="member", state="pending") assert run_cli("plugin", "new", FULL, "--yes") == 1 assert github.write_calls() == [] assert _plugins_yml(root) is None @@ -230,6 +231,53 @@ def test_merge_failure_keeps_plugins_yml(github, root, run_cli, caplog, prepare) assert "devbase plugin repo" in caplog.text +def test_registry_pr_merge_failure_asks_to_rerun(github, root, run_cli, caplog): + """プラグインの PR がまだ無いので、登録と導入ではなく打ち直しを案内する。""" + github.add_repo(FULL, {"README.md": "x\n"}, merge_error="required reviews") + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert [pr["head"] for pr in github.prs()] == ["devbase/new-repo-repo"] + assert github.prs()[0]["url"] in caplog.text + assert f"devbase plugin new {URL} --name team-a" in caplog.text + assert "devbase plugin install" not in caplog.text + assert "devbase plugin repo add" not in caplog.text + assert _plugins_yml(root) is None + + +def test_ssh_registration_clones_and_pushes_over_ssh(github, root, run_cli): + """一時の clone と push は入力から作った https ではなく、登録の URL で走る。""" + url = "git@github.com:owner/repo.git" + github.add_repo(FULL, {"registry.yml": REGISTRY}) + add_repository(PluginRegistry(root), url) + github.ssh_only() + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + _assert_installed(root, source=url) + + +def test_rename_in_the_pulled_update_keeps_the_project(github, root, run_cli): + """取り込みでプラグインが移っても、移行先を導入してプロジェクトのリンクを残す。""" + github.add_repo(FULL, { + "registry.yml": "name: repo\nplugins:\n - name: old\n path: old\n", + "old/plugin.yml": "name: old\nversion: '1.0.0'\n", + "old/projects/p1/compose.yml": "services: {}\n", + }) + registry = PluginRegistry(root) + add_repository(registry, URL) + install_plugin(registry, f"{URL}:old") + assert (root / "projects" / "p1").is_dir() + + github.commit(FULL, { + "registry.yml": "name: repo\nplugins:\n - name: moved\n path: moved\n", + "moved/plugin.yml": "name: moved\nversion: '1.0.0'\n", + "moved/projects/p1/compose.yml": "services: {}\n", + }, remove=["old"]) + assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + + registry = PluginRegistry(root) + assert registry.get("old") is None + assert registry.get("moved") is not None + assert (root / "projects" / "p1").is_dir() + + def test_never_touches_docker(github, root, registered, run_cli): assert run_cli("plugin", "new", FULL, "--yes") == 0 assert github.docker_calls() == [] diff --git a/tests/plugin/test_create_project.py b/tests/plugin/test_create_project.py index 53f54ce8..15cccd52 100644 --- a/tests/plugin/test_create_project.py +++ b/tests/plugin/test_create_project.py @@ -315,6 +315,31 @@ def test_merge_failure_leaves_the_local_side(github, root, app, run_cli, caplog) assert "devbase plugin repo refresh" in caplog.text +MOVED_REGISTRY = "name: plugins\nplugins:\n - name: team-a\n path: moved\n" + + +def test_stale_plugin_path_stops_before_writing(github, root, app, run_cli, caplog): + """既定ブランチで path が変わっていたら、古い path へマージしない。""" + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + github.commit("owner/plugins", {"registry.yml": MOVED_REGISTRY, + "moved/plugin.yml": "name: team-a\nversion: '1.0.0'\n"}) + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + assert "devbase plugin repo refresh plugins" in caplog.text + + assert run_cli("plugin", "repo", "refresh", "plugins") == 0 + assert run_cli("project", "new", APP, "--group", "acme", "--yes") == 0 + assert github.file("owner/plugins", "moved/projects/app/project.yml") is not None + + +def test_plugin_gone_from_the_registry_stops(github, root, app, run_cli, caplog): + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + github.commit("owner/plugins", {"registry.yml": "name: plugins\nplugins: []\n"}) + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + assert "項目なし" in caplog.text + + def test_tty_decline_changes_nothing(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) assert run_cli("project", "new", APP, tty=True, answers=["n"]) == 1 diff --git a/tests/plugin/test_create_repo.py b/tests/plugin/test_create_repo.py index e273703c..42474300 100644 --- a/tests/plugin/test_create_repo.py +++ b/tests/plugin/test_create_repo.py @@ -119,14 +119,22 @@ def test_no_push_stops_without_writing(github, root, run_cli, caplog): assert FULL in caplog.text -def test_absent_and_cannot_create_stops(github, root, run_cli): - github.add_org("owner", role="member", can_create=False) +def test_absent_and_not_a_member_stops(github, root, run_cli): assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 assert github.write_calls() == [] assert not github.exists(FULL) assert _plugins_yml(root) is None +def test_org_forbids_creation_stops_at_create_with_gh_output(github, root, run_cli, caplog): + """非管理者には組織の設定が返らないので、gh repo create の失敗の出力で止まる。""" + github.add_org("owner", role="member", can_create=False) + assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert "cannot create repositories" in caplog.text + assert not github.exists(FULL) + assert _plugins_yml(root) is None + + def test_absent_in_own_account_can_be_created(github, root, run_cli): assert run_cli("plugin", "repo", "new", "me/repo", "--yes") == 0 assert github.exists("me/repo") diff --git a/tests/plugin/test_github.py b/tests/plugin/test_github.py index 257219b6..e2e57f9b 100644 --- a/tests/plugin/test_github.py +++ b/tests/plugin/test_github.py @@ -145,6 +145,8 @@ def test_view_repo_empty_has_no_default_branch(client): '{"members_can_create_repositories": true}', True), ("team-a", '{"state": "active", "role": "member"}', '{"members_can_create_repositories": false}', False), + # 値は組織の owner にしか返らない。判定できないので進め、gh repo create の失敗で止める + ("team-a", '{"state": "active", "role": "member"}', '{"login": "team-a"}', True), ("team-a", '{"state": "pending", "role": "admin"}', None, False), ("team-a", False, None, False), ]) diff --git a/tests/plugin/test_publish.py b/tests/plugin/test_publish.py index 6c91688a..b5a99e3e 100644 --- a/tests/plugin/test_publish.py +++ b/tests/plugin/test_publish.py @@ -67,6 +67,52 @@ def test_publish_change_refuses_to_overwrite(github, gh): assert github.pushed_refs(FULL) == [] +@pytest.mark.parametrize("link, written", [ + ("team-a/projects", "team-a/projects/p/env"), + ("team-a/env", "team-a/env"), +]) +def test_publish_change_stays_inside_the_clone(github, gh, tmp_path, link, written): + """既存リポジトリの symlink をたどって手元のファイルを作らない (既にあるディレクトリ・無い先)。""" + outside = tmp_path / "outside" + if link == "team-a/projects": + outside.mkdir() + github.add_repo(FULL, REGISTRY) + github.commit(FULL, {link: outside}) + with pytest.raises(RepositoryError, match="外を指して"): + publish.publish_change(gh, REF, kind="project", name="p", files={written: "X=1\n"}) + assert not outside.exists() or list(outside.iterdir()) == [] + assert github.branches(FULL) == ["main"] + + +def test_publish_change_checks_every_file_before_writing(github, gh, tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + github.add_repo(FULL, REGISTRY) + github.commit(FULL, {"links": outside}) + with pytest.raises(RepositoryError): + publish.publish_change(gh, REF, kind="project", name="p", + files={"inside/a": "1\n", "links/b": "2\n"}) + assert list(outside.iterdir()) == [] + + +def test_publish_change_does_not_write_through_a_registry_symlink(github, gh, tmp_path): + outside = tmp_path / "registry.yml" + outside.write_text("name: mine\nplugins: []\n") + github.add_repo(FULL, {"README.md": "x\n"}) + github.commit(FULL, {"registry.yml": outside}) + with pytest.raises(RepositoryError, match="外を指して"): + publish.publish_change(gh, REF, kind="plugin", name="team-a", + files={"team-a/plugin.yml": "name: team-a\n"}, + registry_entry="team-a") + assert outside.read_text() == "name: mine\nplugins: []\n" + + +def test_publish_change_rejects_a_path_above_the_clone(github, gh): + github.add_repo(FULL, REGISTRY) + with pytest.raises(RepositoryError, match="外を指して"): + publish.publish_change(gh, REF, kind="project", name="p", files={"../x": "1\n"}) + + def test_publish_change_stops_at_an_existing_branch_with_pr(github, gh): github.add_repo(FULL, REGISTRY) publish_branch = "devbase/new-plugin-team-a" From bec38cfd08cee5a971b7fc1322eebf5cb1270241 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 04:13:11 +0000 Subject: [PATCH 14/18] =?UTF-8?q?Fix:=20#514=20=E4=BD=9C=E6=88=90=E3=83=95?= =?UTF-8?q?=E3=83=AD=E3=83=BC=E3=81=AE=E3=83=AC=E3=83=93=E3=83=A5=E3=83=BC?= =?UTF-8?q?=E3=81=AE=E6=8C=87=E6=91=98=204=20=E4=BB=B6=E3=82=92=E7=9B=B4?= =?UTF-8?q?=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - registry.yml の項目に path が無いプラグインを導入と同じく直下として扱う - gh の操作先を GH_HOST で github.com に固定する - clone の既定ブランチを GitHub の値と比べ、書き込みの前に止める - 設計の途中で止まったときの表の案内を実装に揃える Co-Authored-By: Claude Opus 5.5 --- docs/user/cli-reference/02-project.md | 2 +- docs/user/cli-reference/04-plugin.md | 2 +- issues/issue-514-design.md | 10 +++- lib/devbase/plugin/creator.py | 49 +++++++++++++--- lib/devbase/plugin/github.py | 9 ++- lib/devbase/plugin/repo_manager.py | 41 ++++++++----- lib/devbase/plugin/scaffold.py | 26 +++++++-- tests/plugin/creation_harness.py | 10 +++- tests/plugin/test_create_project.py | 67 ++++++++++++++++++++++ tests/plugin/test_github.py | 14 ++++- tests/plugin/test_repo_manager_creation.py | 44 +++++++++++--- tests/plugin/test_scaffold.py | 18 ++++++ 12 files changed, 252 insertions(+), 40 deletions(-) diff --git a/docs/user/cli-reference/02-project.md b/docs/user/cli-reference/02-project.md index 37307122..f554738d 100644 --- a/docs/user/cli-reference/02-project.md +++ b/docs/user/cli-reference/02-project.md @@ -473,7 +473,7 @@ devbase project new [--plugin <名前>] [--group <名前>] [--name <名 アカウントグループは、`--group`、入れ先の既存プロジェクトの最多の値の順で決まります。最多が同数か値が無いときは端末で聞き、端末が無ければ終了コード 1 で止まります。どの出所の値も `DEVBASE_ACCOUNT_GROUP` の規則(`default` などの予約語は使えません)を通します。 -対象のリポジトリを読めないとき、同じ名前のプロジェクトが `projects/` か入れ先にあるときは、何も変えずに終了コード 1 で止まります。 +対象のリポジトリを読めないとき、同じ名前のプロジェクトが `projects/` か入れ先にあるときは、何も変えずに終了コード 1 で止まります。入れ先の手元の clone が GitHub の既定ブランチを追っていないときも、切り替えのコマンドを出して同じように止まります。 ## `devbase project list` diff --git a/docs/user/cli-reference/04-plugin.md b/docs/user/cli-reference/04-plugin.md index e55bcc8c..a3b59936 100644 --- a/docs/user/cli-reference/04-plugin.md +++ b/docs/user/cli-reference/04-plugin.md @@ -119,7 +119,7 @@ devbase plugin new [--name <名前>] [--public] [--yes] 未登録のリポジトリは、先に `plugin repo new` と同じ分岐を通します。リポジトリの分の変更とプラグインの PR は別の変更として順に入り、登録はプラグインの PR のマージの後です。 -同じ名前のプラグインが `registry.yml` か導入済みの中にあるとき、同じ名前のパスがリポジトリにあるときは、何も変えずに終了コード 1 で止まります。登録の手元の clone が無いときは、登録し直すコマンドを出して止まります。 +同じ名前のプラグインが `registry.yml` か導入済みの中にあるとき、同じ名前のパスがリポジトリにあるときは、何も変えずに終了コード 1 で止まります。登録の手元の clone が無いときは、登録し直すコマンドを出して止まります。登録の手元の clone が GitHub の既定ブランチを追っていないときは、切り替えのコマンドを出して止まります。 ## `devbase plugin repo new` diff --git a/issues/issue-514-design.md b/issues/issue-514-design.md index 8488eddc..291b5845 100644 --- a/issues/issue-514-design.md +++ b/issues/issue-514-design.md @@ -239,6 +239,10 @@ graph TD `project new` は、計画の確定の前に、入れ先のプラグインの登録の `path` を既定ブランチの `registry.yml` と比べる。項目が無いか違うときは、GitHub にも手元にも書かず終了コード 1 で止まり、`devbase plugin repo refresh ` を案内する。古い `path` へマージすると、続く取り込みが新しい `path` を登録し、足したプロジェクトが `projects/` に現れないまま 0 で終わるためである。 +入れ先のパスは、導入済みの `plugin.path` の `repo.local_path` からの相対で決める。`registry.yml` の項目に `path` が無いプラグインは、導入と同じくリポジトリの直下として扱い、書き込み先は `projects/<名前>` になる。 + +`plugin new` と `project new` は、計画の確定の前に、登録の clone が GitHub の既定ブランチにいて、`origin` の同じブランチを追っていることを確かめる。違うときは、GitHub にも手元にも書かず終了コード 1 で止まり、切り替えのコマンドを案内する。clone の `origin/HEAD` は既定ブランチを変えても追従せず、古いブランチが残っていると取り込みが成功して、足したものが手元に現れないまま 0 で終わるためである。 + 一時の clone へ書くパスは、symlink と `..` を解決して clone の中に収まることを確かめ、外を指すものがあれば 1 ファイルも書かずに止まる。clone の中身は他人が書いたもので、書き込みが利用者の手元のファイルへ届かないようにする。 登録済みの経路の `_pull_ff_only` の前に、導入済みのプラグインのプロジェクト一覧を控え、`refresh_repository` へ渡す。取り込みにプラグインの改名や移動が入っていても、移行先を見つけられる。 @@ -343,7 +347,7 @@ sequenceDiagram | 同じブランチが既にある | 既存のブランチと PR | 開いている PR の URL | | マージ | PR とブランチ | PR の URL。マージの後に打つコマンド(`plugin repo add`・`plugin repo refresh`・`plugin install`) | | `plugin new` の `registry.yml` の PR | PR とブランチ。プラグインの PR はまだ無い。`plugins.yml` は元のまま | PR の URL。この PR をマージした後に同じ `plugin new` を打ち直す案内 | -| 未登録のリポジトリへの `plugin new` のプラグインの PR | 先に反映した最初のコミットか `registry.yml` は既定ブランチに残る。`plugins.yml` は元のまま | 上の行に同じ | +| 未登録のリポジトリへの `plugin new` のプラグインの PR | 先に反映した最初のコミットか `registry.yml` は既定ブランチに残る。`plugins.yml` は元のまま | PR の URL。マージの後に打つコマンド(`plugin repo add`・`plugin install`) | | 取り込み | マージ済み。手元は元のまま | 原因と `git -C status`、続けて打つコマンド | | 登録 | マージと取り込み済み | 既存のコマンドのエラーと、続けて打つコマンド | @@ -443,7 +447,7 @@ TUI は `creator` の読むだけの関数(候補とグループの案)を ### 決定 11: トークンをアプリで扱わないため、GitHub の操作は `gh` に任せる -権限の確認・リポジトリの作成・PR・マージを `gh` の呼び出しで行う。認証は利用者の `gh` の設定に任せる。機密の `GH_TOKEN` が環境変数に載ると `gh` がそのトークンで動くので、3 つのコマンドは機密を注入せず、TUI は `gh` を呼ぶ前に注入を取り除く。 +権限の確認・リポジトリの作成・PR・マージを `gh` の呼び出しで行う。認証は利用者の `gh` の設定に任せる。操作先のホストだけは `GH_HOST=github.com` で固定する。`GitHubRef` が受けるのも `git` が操作するのも github.com だけで、`GH_HOST` が別のホストを指すと確認やリポジトリの作成が `git` と別のホストへ向かうためである。機密の `GH_TOKEN` が環境変数に載ると `gh` がそのトークンで動くので、3 つのコマンドは機密を注入せず、TUI は `gh` を呼ぶ前に注入を取り除く。 採らなかった案: PyGithub を使う。トークンをアプリが受け取ることになる。 @@ -468,7 +472,7 @@ TUI は `creator` の読むだけの関数(候補とグループの案)を | 13、I6 | 作成フローの全経路で `docker` と `compose` を呼ばない | 手順に `up` を足す | | 14 | `gh` なし・未認証で、書き込みの呼び出しが 0 回 | 確認を後回しにする | | 15、I1 | 確認の前は書き込みの呼び出しが 0 回。TTY なしで `--yes` なしは 1 | 確認を飛ばす | -| 16、I4、I8 | 手元に未コミットの変更がある clone で完走し、変更が残る。分岐した clone は止まる | `creator`・`publish` が手元の作業ツリーへ書く・マージコミットを作る | +| 16、I4、I8 | 手元に未コミットの変更がある clone で完走し、変更が残る。分岐した clone は止まる。GitHub の既定ブランチと違うブランチの clone は、書き込みの前に止まる | `creator`・`publish` が手元の作業ツリーへ書く・マージコミットを作る・`origin/HEAD` で既定ブランチを決める | | 17、I2 | マージの失敗で `plugins.yml` が同じで、URL が出る。未登録のリポジトリへの `plugin new` でも同じである。成功のとき作業場所が残らない | 先に登録する | | 18・19・20 | メニューの全項目が既存の操作へ届き、Esc と Ctrl-C の戻り値が既存どおりに伝わる | 項目の欠け・Esc の取り違え | | 21 | 既存のテストが変わらず通る | 既存の属性を変える | diff --git a/lib/devbase/plugin/creator.py b/lib/devbase/plugin/creator.py index 98f4c358..45759791 100644 --- a/lib/devbase/plugin/creator.py +++ b/lib/devbase/plugin/creator.py @@ -12,6 +12,7 @@ from collections import Counter from dataclasses import dataclass, field, replace from enum import Enum +from pathlib import PurePosixPath from typing import Dict, List, Optional, Protocol, Tuple from devbase.env import groups @@ -23,11 +24,12 @@ from . import publish, scaffold from .github import GhClient, GitHubRef, RepoView from .installer import install_plugin -from .models import RegisteredRepository +from .models import InstalledPlugin, RegisteredRepository from .registry import PluginRegistry from .repo_manager import ( _find_registered, _pull_ff_only, + _require_default_branch, _snapshot_repo_projects, _url_to_repos_dirname, add_repository, @@ -184,6 +186,16 @@ def _require_clone(registry: PluginRegistry, repo: RegisteredRepository) -> None ) +def _require_clone_on_default( + registry: PluginRegistry, repo: RegisteredRepository, default_branch: str, +) -> None: + """登録の clone が GitHub の既定ブランチを追っていることを確かめる (読むだけ) + + 書き込みの後に分かると、マージ済みのものを手元へ取り込めずに止まる。 + """ + _require_default_branch(registry.devbase_root / repo.local_path, default_branch) + + def plan_plugin( registry: PluginRegistry, gh: GhClient, value: str, *, name: Optional[str] = None, public: bool = False, @@ -202,6 +214,8 @@ def plan_plugin( raise RepositoryError( f"{ref.full_name} は登録済みですが、既定ブランチに {scaffold.REGISTRY_FILE} が" "ありません") + if registered is not None: + _require_clone_on_default(registry, registered, default_branch) _reject_duplicate_plugin(registry, gh, ref, plugin, state) return CreationPlan( kind=KIND_PLUGIN, ref=ref, name=plugin, state=state, @@ -240,20 +254,33 @@ def label(self) -> str: return f"{self.plugin} ({self.ref.full_name})" +def _path_in_repo(plugin: InstalledPlugin, repo: RegisteredRepository) -> Optional[str]: + """導入先のパスのリポジトリの直下からの相対 (直下は空の文字列)。clone の外なら ``None`` + + ``registry.yml`` の項目に ``path`` が無いプラグインも、導入先ならリポジトリの直下と分かる。 + """ + try: + relative = PurePosixPath(plugin.path).relative_to(repo.local_path) + except ValueError: + return None + return scaffold.normal_plugin_path(relative.as_posix()) + + def _installed_targets(registry: PluginRegistry) -> List[PluginTarget]: """導入済みで、登録済みの GitHub のリポジトリに項目があるプラグイン (GitHub を見ない)""" targets = [] for plugin in registry.list_installed(): repo = None if plugin.linked else _find_registered(registry, plugin.source) - entry = repo.find_plugin(plugin.name) if repo else None - if entry is None: + if repo is None or repo.find_plugin(plugin.name) is None: + continue + path = _path_in_repo(plugin, repo) + if path is None: continue try: ref = GitHubRef.parse(repo.url) except RepositoryError: continue - targets.append(PluginTarget(plugin.name, repo, ref, - (entry.path or plugin.name).rstrip('/'))) + targets.append(PluginTarget(plugin.name, repo, ref, path)) return targets @@ -349,6 +376,9 @@ def _decide_group( return validate_account_group(value) +_REPO_ROOT_LABEL = 'リポジトリの直下' + + def _require_current_path(gh: GhClient, target: PluginTarget) -> None: """手元の登録の ``path`` が既定ブランチの ``registry.yml`` と同じことを確かめる (読むだけ) @@ -359,9 +389,10 @@ def _require_current_path(gh: GhClient, target: PluginTarget) -> None: current = scaffold.registry_plugin_path(text, target.plugin) if current == target.path: return + remote = '項目なし' if current is None else current or _REPO_ROOT_LABEL raise RepositoryError( f"プラグイン {target.plugin} の path が、{target.ref.full_name} の既定ブランチ " - f"({current or '項目なし'}) と手元の登録 ({target.path}) で違います。" + f"({remote}) と手元の登録 ({target.path or _REPO_ROOT_LABEL}) で違います。" "次のコマンドで取り込んでから打ち直してください:\n" f" devbase plugin repo refresh {target.repo.name}" ) @@ -384,8 +415,9 @@ def plan_project( target = _decide_target(registry, gh, ref, plugin, prompter) _require_clone(registry, target.repo) + _require_clone_on_default(registry, target.repo, target.default_branch) _require_current_path(gh, target) - destination = f"{target.path}/projects/{project}" + destination = scaffold.project_dir(target.path, project) if gh.read_file(target.ref, destination) is not None: raise RepositoryError(f"{target.ref.full_name} に {destination} が既にあります") decided_group = _decide_group(registry, target, group, prompter) @@ -466,7 +498,8 @@ def _apply_locally(registry: PluginRegistry, plan: CreationPlan) -> None: else: # 取り込みに改名や移動が入っていても refresh が移行先を見つけられるよう、先に控える pre_pull = _snapshot_repo_projects(registry, plan.registered) - _pull_ff_only(registry.devbase_root / plan.registered.local_path) + _pull_ff_only(registry.devbase_root / plan.registered.local_path, + plan.default_branch) refresh_repository(registry, plan.registered.name, pre_pull_projects=pre_pull) if plan.kind == KIND_PLUGIN: install_plugin(registry, f"{_source_url(plan)}:{plan.name}") diff --git a/lib/devbase/plugin/github.py b/lib/devbase/plugin/github.py index bfdbf880..ebd770a1 100644 --- a/lib/devbase/plugin/github.py +++ b/lib/devbase/plugin/github.py @@ -8,6 +8,7 @@ from __future__ import annotations import json +import os import re import shutil import subprocess @@ -25,6 +26,9 @@ _REPO_RE = re.compile(r'[A-Za-z0-9._][A-Za-z0-9._-]*') _RESERVED_REPOS = frozenset({'.', '..', '.git'}) +#: ``gh`` の操作先。``GitHubRef`` が受けるのも git が操作するのも github.com だけである +_GITHUB_HOST = 'github.com' + _PUSH_PERMISSIONS = frozenset({'ADMIN', 'MAINTAIN', 'WRITE'}) _MISSING_REPO_MARK = 'Could not resolve to a Repository' _NOT_ACCESSIBLE_MARKS = ('HTTP 403', 'HTTP 404') @@ -91,7 +95,10 @@ def __init__(self) -> None: self._login: Optional[str] = None def _run(self, *args: str) -> subprocess.CompletedProcess: - return subprocess.run(['gh', *args], capture_output=True, text=True, check=False) + # GH_HOST が別のホストを指していても、git と同じ github.com の認証で操作する + env = {**os.environ, 'GH_HOST': _GITHUB_HOST} + return subprocess.run(['gh', *args], capture_output=True, text=True, check=False, + env=env) def _json(self, *args: str, what: str): result = self._run(*args) diff --git a/lib/devbase/plugin/repo_manager.py b/lib/devbase/plugin/repo_manager.py index a2738f83..348b3a21 100644 --- a/lib/devbase/plugin/repo_manager.py +++ b/lib/devbase/plugin/repo_manager.py @@ -179,26 +179,41 @@ def _git_pull(repo_dir: Path) -> None: ) -def _pull_ff_only(repo_dir: Path) -> None: - """既定ブランチの clone を早送りだけで取り込む (#514 の I4・I8)。 +def _require_default_branch(repo_dir: Path, default_branch: str) -> None: + """clone が既定ブランチにいて ``origin`` の同じブランチを追っていることを確かめる (読むだけ)。 - 既定ブランチ以外・detached HEAD・分岐した clone・作業ツリーの変更とぶつかる取り込みは - 何も変えずに止める。既定ブランチは clone の ``origin/HEAD`` で決める。 + ``default_branch`` は GitHub から得た値を渡す。clone の ``origin/HEAD`` は、既定ブランチを + 変えても追従しない。古いブランチが残っていると取り込みが成功し、既定ブランチへ入れたものが + 手元に現れないまま終わる。 Raises: - RepositoryError: 早送りで取り込めないとき + RepositoryError: 既定ブランチを追っていないとき """ current = _run_git(repo_dir, 'branch', '--show-current').stdout.strip() - head = _run_git(repo_dir, 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD') - default = head.stdout.strip().split('/', 1)[-1] if head.returncode == 0 else '' - if not current or (default and current != default): + upstream = _run_git(repo_dir, 'rev-parse', '--abbrev-ref', '@{u}') + if current == default_branch and upstream.returncode != 0: + raise RepositoryError(str(_missing_upstream_error(repo_dir))) + tracking = upstream.stdout.strip() if upstream.returncode == 0 else '' + if current != default_branch or tracking != f"origin/{default_branch}": raise RepositoryError( - f"{repo_dir} は既定ブランチ {default or '(不明)'} ではありません " - f"(今: {current or 'detached HEAD'})。\n" - f"確かめる: git -C {repo_dir} status" + f"{repo_dir} は既定ブランチ {default_branch} を追っていません " + f"(今: {current or 'detached HEAD'}、追跡先: {tracking or 'なし'})。\n" + f"確かめる: git -C {repo_dir} status\n" + f"切り替える: git -C {repo_dir} fetch origin && " + f"git -C {repo_dir} switch {default_branch}" ) - if _run_git(repo_dir, 'rev-parse', '--abbrev-ref', '@{u}').returncode != 0: - raise RepositoryError(str(_missing_upstream_error(repo_dir))) + + +def _pull_ff_only(repo_dir: Path, default_branch: str) -> None: + """既定ブランチの clone を早送りだけで取り込む (#514 の I4・I8)。 + + 既定ブランチ以外・detached HEAD・分岐した clone・作業ツリーの変更とぶつかる取り込みは + 何も変えずに止める。 + + Raises: + RepositoryError: 早送りで取り込めないとき + """ + _require_default_branch(repo_dir, default_branch) result = _run_git(repo_dir, 'pull', '--ff-only') if result.returncode != 0: diff --git a/lib/devbase/plugin/scaffold.py b/lib/devbase/plugin/scaffold.py index d5ce7734..2264e21d 100644 --- a/lib/devbase/plugin/scaffold.py +++ b/lib/devbase/plugin/scaffold.py @@ -6,6 +6,7 @@ from __future__ import annotations +from pathlib import PurePosixPath from typing import Dict, List, Optional import yaml @@ -45,8 +46,22 @@ def plugin_files(name: str) -> Dict[str, str]: return {f'{name}/plugin.yml': plugin_yml, f'{name}/projects/.gitkeep': ''} +def normal_plugin_path(path: str) -> str: + """リポジトリの直下からのプラグインのパスを比べられる形にする。直下は空の文字列""" + normal = PurePosixPath(path.rstrip('/')).as_posix() + return '' if normal == '.' else normal + + +def project_dir(plugin_path: str, name: str) -> str: + """プロジェクトのディレクトリ (リポジトリの直下からのパス)""" + return PurePosixPath(plugin_path, 'projects', name).as_posix() + + def project_files(plugin_path: str, name: str, ref: GitHubRef, group: str) -> Dict[str, str]: - """プロジェクトのファイル (リポジトリの直下からのパス → 中身)""" + """プロジェクトのファイル (リポジトリの直下からのパス → 中身)。 + + ``plugin_path`` が空なら、プラグインはリポジトリの直下にある。 + """ project_yml = ( 'version: 1\n' 'scale: 1\n' @@ -79,7 +94,7 @@ def project_files(plugin_path: str, name: str, ref: GitHubRef, group: str) -> Di devbase_net: external: true """ - base = f"{plugin_path.rstrip('/')}/projects/{name}" + base = project_dir(plugin_path, name) return { f'{base}/project.yml': project_yml, f'{base}/compose.yml': compose_yml, @@ -111,10 +126,13 @@ def registry_plugin_names(text: str) -> List[str]: def registry_plugin_path(text: str, name: str) -> Optional[str]: - """``registry.yml`` の ``name`` の項目の ``path``。項目が無ければ ``None``""" + """``registry.yml`` の ``name`` の項目の ``path``。項目が無ければ ``None``。 + + ``path`` が無い項目は、導入と同じくリポジトリの直下 (空の文字列) として扱う。 + """ for entry in _load_registry(text).get('plugins') or []: if entry.get('name') == name: - return (entry.get('path') or name).rstrip('/') + return normal_plugin_path(entry.get('path') or '') return None diff --git a/tests/plugin/creation_harness.py b/tests/plugin/creation_harness.py index f089ff50..10a4b66b 100644 --- a/tests/plugin/creation_harness.py +++ b/tests/plugin/creation_harness.py @@ -85,7 +85,8 @@ def _gh_repo_view(world, state, argv): allowed = entry.get('merge_methods', ['merge', 'squash', 'rebase']) values = { 'isEmpty': not has_commits, - 'defaultBranchRef': {'name': 'main'} if has_commits else None, + 'defaultBranchRef': ({'name': entry.get('default_branch', 'main')} + if has_commits else None), 'viewerPermission': entry.get('permission', 'ADMIN'), 'mergeCommitAllowed': 'merge' in allowed, 'squashMergeAllowed': 'squash' in allowed, @@ -239,6 +240,13 @@ def update_repo(self, full_name: str, **values) -> None: state['repos'][full_name].update(values) self._state_file.write_text(json.dumps(state)) + def set_default_branch(self, full_name: str, branch: str) -> None: + """既定ブランチを ``branch`` へ変える。今の main は残す。""" + bare = self._bare(full_name) + _bare_git(bare, 'update-ref', f'refs/heads/{branch}', 'refs/heads/main') + _bare_git(bare, 'symbolic-ref', 'HEAD', f'refs/heads/{branch}') + self.update_repo(full_name, default_branch=branch) + def add_org(self, name, *, state='active', role='member', can_create=False): orgs = self.state()['orgs'] orgs[name] = {'state': state, 'role': role, 'can_create': can_create} diff --git a/tests/plugin/test_create_project.py b/tests/plugin/test_create_project.py index 15cccd52..b2cac90b 100644 --- a/tests/plugin/test_create_project.py +++ b/tests/plugin/test_create_project.py @@ -2,6 +2,8 @@ from __future__ import annotations +import subprocess + import pytest import yaml @@ -340,6 +342,71 @@ def test_plugin_gone_from_the_registry_stops(github, root, app, run_cli, caplog) assert "項目なし" in caplog.text +ROOT_REGISTRY = "name: plugins\nplugins:\n - name: team-a\n description: x\n" + + +def _root_plugin_repo(github, root, full="owner/plugins"): + """registry.yml の項目に path が無い、リポジトリの直下のプラグインを導入する。""" + github.add_repo(full, { + "registry.yml": ROOT_REGISTRY, + "plugin.yml": "name: team-a\nversion: '1.0.0'\n", + "projects/.gitkeep": "", + }) + registry = PluginRegistry(root) + url = f"https://github.com/{full}.git" + add_repository(registry, url) + install_plugin(registry, f"{url}:team-a") + return root / "repos" / f"github.com--{full.replace('/', '--')}" + + +def test_plugin_at_the_repository_root(github, root, app, run_cli): + """path の無い項目は導入と同じく直下として扱い、projects/ へ現れる。""" + clone = _root_plugin_repo(github, root) + assert run_cli("project", "new", APP, "--group", "acme", "--yes") == 0 + assert github.file("owner/plugins", "projects/app/project.yml") is not None + assert github.file("owner/plugins", "team-a/projects/app/project.yml") is None + assert (clone / "projects" / "app" / "project.yml").is_file() + assert (root / "projects" / "app" / "project.yml").is_file(), "projects/ へ反映する" + + +def test_group_comes_from_the_repository_root(github, root, app, run_cli): + clone = _root_plugin_repo(github, root) + (clone / "projects" / "p0").mkdir() + (clone / "projects" / "p0" / "env").write_text("DEVBASE_ACCOUNT_GROUP=acme\n") + assert run_cli("project", "new", APP, "--yes") == 0 + assert github.file("owner/plugins", "projects/app/env") == "DEVBASE_ACCOUNT_GROUP=acme\n" + + +def test_plugin_moved_from_the_root_stops(github, root, app, run_cli, caplog): + _root_plugin_repo(github, root) + github.commit("owner/plugins", {"registry.yml": MOVED_REGISTRY}) + assert run_cli("project", "new", APP, "--group", "acme", "--yes") == 1 + assert github.write_calls() == [] + assert "リポジトリの直下" in caplog.text + + +def test_moved_default_branch_stops_before_writing(github, root, app, run_cli, caplog): + """既定ブランチを変えて main を残しても、古い main の clone のまま進めない。""" + _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + github.set_default_branch("owner/plugins", "develop") + before = _plugins_yml(root) + assert run_cli("project", "new", APP, "--yes") == 1 + assert github.write_calls() == [] + assert _plugins_yml(root) == before + assert "既定ブランチ develop" in caplog.text + assert "switch develop" in caplog.text + + +def test_clone_on_the_new_default_branch_completes(github, root, app, run_cli): + """切り替えた clone は、origin/HEAD が古いままでも進める。""" + clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + github.set_default_branch("owner/plugins", "develop") + subprocess.run(["git", "fetch", "origin"], cwd=clone, check=True, capture_output=True) + subprocess.run(["git", "switch", "develop"], cwd=clone, check=True, capture_output=True) + assert run_cli("project", "new", APP, "--yes") == 0 + assert (root / "projects" / "app" / "project.yml").is_file() + + def test_tty_decline_changes_nothing(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) assert run_cli("project", "new", APP, tty=True, answers=["n"]) == 1 diff --git a/tests/plugin/test_github.py b/tests/plugin/test_github.py index e2e57f9b..fb62a516 100644 --- a/tests/plugin/test_github.py +++ b/tests/plugin/test_github.py @@ -58,10 +58,12 @@ class _Script: def __init__(self, table): self.table = table self.calls = [] + self.envs = [] - def __call__(self, cmd, **_kwargs): + def __call__(self, cmd, **kwargs): assert cmd[0] == "gh" self.calls.append(cmd[1:]) + self.envs.append(kwargs.get("env")) for prefix, result in self.table: if cmd[1:len(prefix) + 1] == prefix: if callable(result): @@ -85,6 +87,16 @@ def _make(table): REF = GitHubRef("owner", "repo", "https://github.com/owner/repo.git") +def test_gh_always_targets_github_com(client, monkeypatch): + """GH_HOST が別のホストを指していても、git と同じ github.com を操作する。""" + monkeypatch.setenv("GH_HOST", "ghe.example.com") + monkeypatch.setenv("PATH", "/kept") + gh, script = client([(["api", "user"], (0, '{"login": "me"}', ""))]) + gh.login() + assert script.envs[0]["GH_HOST"] == "github.com" + assert script.envs[0]["PATH"] == "/kept" + + def test_ensure_ready_without_gh_tells_what_to_do(monkeypatch): monkeypatch.setattr(github.shutil, "which", lambda name: None) with pytest.raises(RepositoryError, match="gh"): diff --git a/tests/plugin/test_repo_manager_creation.py b/tests/plugin/test_repo_manager_creation.py index 117ca46b..30a90d4c 100644 --- a/tests/plugin/test_repo_manager_creation.py +++ b/tests/plugin/test_repo_manager_creation.py @@ -9,7 +9,11 @@ from devbase.errors import RepositoryError from devbase.plugin.models import RegisteredRepository from devbase.plugin.registry import PluginRegistry -from devbase.plugin.repo_manager import _find_registered, _pull_ff_only +from devbase.plugin.repo_manager import ( + _find_registered, + _pull_ff_only, + _require_default_branch, +) @pytest.fixture @@ -70,7 +74,7 @@ def _advance(writer, name="b.txt"): def test_pull_ff_only_advances(remote_and_clone): writer, clone = remote_and_clone _advance(writer) - _pull_ff_only(clone) + _pull_ff_only(clone, "main") assert (clone / "b.txt").is_file() @@ -79,7 +83,7 @@ def test_pull_ff_only_keeps_uncommitted_changes(remote_and_clone): _advance(writer) (clone / "a.txt").write_text("edited\n") (clone / "note.txt").write_text("untracked\n") - _pull_ff_only(clone) + _pull_ff_only(clone, "main") assert (clone / "b.txt").is_file() assert (clone / "a.txt").read_text() == "edited\n" assert (clone / "note.txt").read_text() == "untracked\n" @@ -90,7 +94,7 @@ def test_pull_ff_only_stops_when_changes_collide(remote_and_clone): _advance(writer, "note.txt") (clone / "note.txt").write_text("mine\n") with pytest.raises(RepositoryError, match="status"): - _pull_ff_only(clone) + _pull_ff_only(clone, "main") assert (clone / "note.txt").read_text() == "mine\n" @@ -102,7 +106,7 @@ def test_pull_ff_only_stops_when_diverged(remote_and_clone): _git(clone, "commit", "-m", "local") head = _git(clone, "rev-parse", "HEAD").stdout with pytest.raises(RepositoryError): - _pull_ff_only(clone) + _pull_ff_only(clone, "main") assert _git(clone, "rev-parse", "HEAD").stdout == head, "マージコミットを作らない" @@ -111,7 +115,7 @@ def test_pull_ff_only_stops_on_other_branch(remote_and_clone): _advance(writer) _git(clone, "checkout", "-b", "work") with pytest.raises(RepositoryError, match="work"): - _pull_ff_only(clone) + _pull_ff_only(clone, "main") assert not (clone / "b.txt").exists() @@ -119,4 +123,30 @@ def test_pull_ff_only_stops_on_detached_head(remote_and_clone): _, clone = remote_and_clone _git(clone, "checkout", "--detach") with pytest.raises(RepositoryError): - _pull_ff_only(clone) + _pull_ff_only(clone, "main") + + +def test_pull_ff_only_stops_when_default_branch_moved(remote_and_clone): + """origin/HEAD が古くても、GitHub の既定ブランチと比べて止める。""" + writer, clone = remote_and_clone + _advance(writer) + with pytest.raises(RepositoryError, match="develop"): + _pull_ff_only(clone, "develop") + assert not (clone / "b.txt").exists() + + +def test_require_default_branch_stops_on_other_upstream(remote_and_clone): + """同じ名前でも、別のブランチを追っていれば止める。""" + writer, clone = remote_and_clone + _git(writer, "push", "origin", "main:other") + _git(clone, "fetch", "origin") + _git(clone, "branch", "--set-upstream-to=origin/other", "main") + with pytest.raises(RepositoryError, match="origin/other"): + _require_default_branch(clone, "main") + + +def test_require_default_branch_stops_without_upstream(remote_and_clone): + _, clone = remote_and_clone + _git(clone, "branch", "--unset-upstream") + with pytest.raises(RepositoryError, match="upstream"): + _require_default_branch(clone, "main") diff --git a/tests/plugin/test_scaffold.py b/tests/plugin/test_scaffold.py index e34e79ac..472c3bfa 100644 --- a/tests/plugin/test_scaffold.py +++ b/tests/plugin/test_scaffold.py @@ -31,6 +31,24 @@ def test_plugin_files(): } +def test_project_files_at_the_repository_root(): + files = scaffold.project_files("", "app", REF, "acme") + assert set(files) == {"projects/app/project.yml", "projects/app/compose.yml", + "projects/app/env"} + + +@pytest.mark.parametrize("entry, expected", [ + ("- name: a\n", ""), + ("- name: a\n path: \"\"\n", ""), + ("- name: a\n path: ./\n", ""), + ("- name: a\n path: sub/a/\n", "sub/a"), + ("- name: a\n path: ./a\n", "a"), + ("- name: b\n", None), +]) +def test_registry_plugin_path(entry, expected): + assert scaffold.registry_plugin_path(f"plugins:\n{entry}", "a") == expected + + def test_project_files(): files = scaffold.project_files("team-a/", "My-App", REF, "acme") assert set(files) == { From 0ec169640d0067bea8a43c5c9a6e78cbd4a2ea10 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 04:25:30 +0000 Subject: [PATCH 15/18] =?UTF-8?q?Fix:=20#514=20=E4=BD=9C=E6=88=90=E3=81=99?= =?UTF-8?q?=E3=82=8B=E3=83=97=E3=83=AD=E3=82=B8=E3=82=A7=E3=82=AF=E3=83=88?= =?UTF-8?q?=E3=81=AE=E3=82=A4=E3=83=A1=E3=83=BC=E3=82=B8=E5=90=8D=E3=82=92?= =?UTF-8?q?=20Docker=20=E3=81=AE=E5=8F=82=E7=85=A7=E3=81=AE=E5=BD=A2?= =?UTF-8?q?=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `app-` のような名前は名前の形の検査を通るが、そのまま `app-:latest` を 書くと build と up が invalid reference format で止まる。 名前の検査は変えず、イメージ名を作るときに整える。末尾の区切り文字を 落とし、英数字の間に置けない区切り文字の並びを `-` にする。 Co-Authored-By: Claude Opus 5.5 --- issues/issue-514-design.md | 2 +- lib/devbase/plugin/scaffold.py | 20 +++++++++++++++++++- tests/plugin/test_create_project.py | 8 ++++++++ tests/plugin/test_scaffold.py | 27 +++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 2 deletions(-) diff --git a/issues/issue-514-design.md b/issues/issue-514-design.md index 291b5845..de0bb2ce 100644 --- a/issues/issue-514-design.md +++ b/issues/issue-514-design.md @@ -274,7 +274,7 @@ graph TD | ファイル | 中身 | | --- | --- | | `project.yml` | `version: 1`・`scale: 1`・`open_editor: true`・`repos`(`owner`・`repo`) | -| `compose.yml` | `containers/general` の `dev` 1 台。イメージ名は `<名前の小文字>:latest` | +| `compose.yml` | `containers/general` の `dev` 1 台。イメージ名は `<名前の小文字>:latest`。名前の形は Docker の参照より広いので、末尾の区切り文字を落とし、2 つの英数字の間に置けない区切り文字の並びを `-` にする(`app-` は `app:latest`、`app..web` は `app-web:latest`) | | `env` | `DEVBASE_ACCOUNT_GROUP=<グループ>` | 作業ブランチは `devbase/new--<名前>`、PR の題は `devbase: <名前> を足す`。 diff --git a/lib/devbase/plugin/scaffold.py b/lib/devbase/plugin/scaffold.py index 2264e21d..199accd1 100644 --- a/lib/devbase/plugin/scaffold.py +++ b/lib/devbase/plugin/scaffold.py @@ -6,6 +6,7 @@ from __future__ import annotations +import re from pathlib import PurePosixPath from typing import Dict, List, Optional @@ -21,6 +22,10 @@ _PLUGINS_KEY = 'plugins:' _EMPTY_LIST_VALUE = '[]' +_IMAGE_SEPARATORS = re.compile(r'[._-]+') +_VALID_IMAGE_SEPARATOR = re.compile(r'[._]|__|-+') +_IMAGE_SEPARATOR_FALLBACK = '-' + def _scalar(value: str) -> str: """YAML の 1 行のスカラー。``null``・``1.0`` のような名前も文字列のまま読める形にする""" @@ -52,6 +57,19 @@ def normal_plugin_path(path: str) -> str: return '' if normal == '.' else normal +def image_name(name: str) -> str: + """プロジェクト名から Docker の参照として有効なイメージ名を作る。 + + 名前の形は Docker より広く、``app-`` や ``app..web`` も通る。小文字にし、末尾の区切り文字を + 落とし、2 つの英数字の間に置けない区切り文字の並びを ``-`` に置き換える。 + """ + def separator(match: re.Match) -> str: + found = match.group() + return found if _VALID_IMAGE_SEPARATOR.fullmatch(found) else _IMAGE_SEPARATOR_FALLBACK + + return _IMAGE_SEPARATORS.sub(separator, name.lower().rstrip('._-')) + + def project_dir(plugin_path: str, name: str) -> str: """プロジェクトのディレクトリ (リポジトリの直下からのパス)""" return PurePosixPath(plugin_path, 'projects', name).as_posix() @@ -74,7 +92,7 @@ def project_files(plugin_path: str, name: str, ref: GitHubRef, group: str) -> Di services: dev: - image: {_scalar(name.lower() + ':latest')} + image: {_scalar(image_name(name) + ':latest')} build: context: ${{DEVBASE_ROOT}}/containers/general/ dockerfile: Dockerfile diff --git a/tests/plugin/test_create_project.py b/tests/plugin/test_create_project.py index b2cac90b..f68a65a7 100644 --- a/tests/plugin/test_create_project.py +++ b/tests/plugin/test_create_project.py @@ -50,6 +50,14 @@ def app(github): return APP +def test_name_outside_docker_rules_gets_a_valid_image(github, root, app, run_cli): + clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", APP, "--name", "app-", "--yes") == 0 + + compose = yaml.safe_load((clone / "team-a/projects/app-/compose.yml").read_text()) + assert compose["services"]["dev"]["image"] == "app:latest" + + def test_project_is_added_and_reflected(github, root, app, run_cli): clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) assert run_cli("project", "new", APP, "--yes") == 0 diff --git a/tests/plugin/test_scaffold.py b/tests/plugin/test_scaffold.py index 472c3bfa..2a662fa3 100644 --- a/tests/plugin/test_scaffold.py +++ b/tests/plugin/test_scaffold.py @@ -2,6 +2,7 @@ from __future__ import annotations +import re import textwrap import pytest @@ -73,6 +74,32 @@ def test_project_files(): assert files["team-a/projects/My-App/env"] == "DEVBASE_ACCOUNT_GROUP=acme\n" +@pytest.mark.parametrize("name, image", [ + ("web", "web"), + ("My-App", "my-app"), + ("a.b", "a.b"), + ("a_b", "a_b"), + ("a__b", "a__b"), + ("a---b", "a---b"), + ("app-", "app"), + ("app.", "app"), + ("app_", "app"), + ("App_-.", "app"), + ("app..web", "app-web"), + ("app___web", "app-web"), + ("app.-web", "app-web"), + ("app_-web", "app-web"), +]) +def test_image_name_is_a_valid_docker_reference(name, image): + assert scaffold.image_name(name) == image + # distribution/reference の regexp.go の pathComponent と同じ規則 + assert re.fullmatch(r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*", image) + + files = scaffold.project_files("team-a", name, REF, "acme") + compose = yaml.safe_load(files[f"team-a/projects/{name}/compose.yml"]) + assert compose["services"]["dev"]["image"] == f"{image}:latest" + + @pytest.mark.parametrize("name", ["null", "true", "1.0", "yes", "012"]) def test_templates_keep_names_as_strings(name): assert yaml.safe_load(scaffold.registry_yml(name))["name"] == name From 848847d8831073d8596c2f16ea4a19718a6cba75 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 04:44:39 +0000 Subject: [PATCH 16/18] =?UTF-8?q?Fix:=20#514=20Compose=20=E3=81=A8?= =?UTF-8?q?=E3=83=96=E3=83=A9=E3=83=B3=E3=83=81=E3=81=AB=E3=81=A7=E3=81=8D?= =?UTF-8?q?=E3=81=AA=E3=81=84=E5=90=8D=E5=89=8D=E3=81=AE=E3=83=AC=E3=83=93?= =?UTF-8?q?=E3=83=A5=E3=83=BC=E3=81=AE=E6=8C=87=E6=91=98=203=20=E4=BB=B6?= =?UTF-8?q?=E3=82=92=E7=9B=B4=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - project new の名前を Compose のプロジェクト名の規則に合わせる。既定の リポジトリ名は形を整え、--name の合わない名前は書き込みの前に止める - 名前の形を通っても git のブランチ名にできない名前は、有効で一意な ブランチ名へ置き換える Co-Authored-By: Claude Opus 5.5 --- docs/user/cli-reference/02-project.md | 2 +- docs/user/cli-reference/04-plugin.md | 2 +- issues/issue-514-design.md | 8 +++++--- lib/devbase/plugin/creator.py | 16 ++++++++++++++- lib/devbase/plugin/publish.py | 13 +++++++++++++ lib/devbase/plugin/scaffold.py | 23 ++++++++++++++++++++-- tests/plugin/test_create_plugin.py | 9 +++++++++ tests/plugin/test_create_project.py | 28 +++++++++++++++++++++++++++ tests/plugin/test_publish.py | 19 ++++++++++++++++++ 9 files changed, 112 insertions(+), 8 deletions(-) diff --git a/docs/user/cli-reference/02-project.md b/docs/user/cli-reference/02-project.md index f554738d..3f523a98 100644 --- a/docs/user/cli-reference/02-project.md +++ b/docs/user/cli-reference/02-project.md @@ -460,7 +460,7 @@ devbase project new [--plugin <名前>] [--group <名前>] [--name <名 | `repo` | はい | 対象の GitHub のリポジトリ(`owner/repo`・URL。[作成フロー](04-plugin.md#作成フローplugin-new--plugin-repo-new--project-new-に共通)) | | `--plugin` | いいえ | 入れ先のプラグイン | | `--group` | いいえ | アカウントグループ | -| `--name` | いいえ | プロジェクトの名前(既定: リポジトリ名) | +| `--name` | いいえ | プロジェクトの名前。小文字の英数字で始まり、小文字の英数字・`-`・`_` だけからなる形(Compose のプロジェクト名の規則)で、合わなければ何も変えずに終了コード 1 で止まります。既定はリポジトリ名を小文字にし、使えない文字の並びを `-` に置き換えたものです(`MyApp` は `myapp`、`foo.github.io` は `foo-github-io`) | | `--yes` | いいえ | 計画の確認を省く。端末が無いときは必須 | 入れ先のプラグインの `projects/<名前>/` に `project.yml`・`compose.yml`・`env` を足す PR を作ってマージし、手元へ取り込んで `projects/` へ反映します。`` はプロジェクト名として解決されません。 diff --git a/docs/user/cli-reference/04-plugin.md b/docs/user/cli-reference/04-plugin.md index a3b59936..854d0de0 100644 --- a/docs/user/cli-reference/04-plugin.md +++ b/docs/user/cli-reference/04-plugin.md @@ -98,7 +98,7 @@ devbase plugin migrate - **マージは 1 回だけ試します。** CI を待たず、`--auto` と `--admin` を使いません。必須のレビューや検査でマージできないときは、PR の URL とマージの後に打つコマンドを出して終了コード 1 で止まり、`plugins.yml` は変わりません - **コンテナは起動しません。** 起動は `devbase up` を別に打ちます -作業ブランチは `devbase/new-<種類>-<名前>` で、マージのときに消えます。同じブランチが既にあると止まり、開いている PR があればその URL を出します。 +作業ブランチは `devbase/new-<種類>-<名前>` で、マージのときに消えます。git のブランチ名にできない名前(`..` を含むか `.`・`.lock` で終わる)は、`.` を `-` に置き換えてハッシュを足した形になります。同じブランチが既にあると止まり、開いている PR があればその URL を出します。 ## `devbase plugin new` diff --git a/issues/issue-514-design.md b/issues/issue-514-design.md index de0bb2ce..f0891c89 100644 --- a/issues/issue-514-design.md +++ b/issues/issue-514-design.md @@ -57,7 +57,7 @@ | I6 | 全体 | 作成フローはコンテナを起動しない(`AGENTS.md` の P3: 利用者の環境の `devbase up` は人の承認が要る) | テストで止める | | I7 | プラグインリポジトリ | 既定ブランチへの直接の push は、空のリポジトリの最初のコミットだけである | テストで止める | | I8 | 手元の clone | 手元の clone の取り込みは早送りだけである | 早送りできなければ止める | -| I9 | 全体 | グループ(`--group`・最多の値・TTY で聞いた値)は `validate_account_group` を、プラグインとプロジェクトの名前は `names.is_single_segment_name` を通してから計画へ入れる | 通らなければ何も変えず、理由を出して終了コード 1 で止める | +| I9 | 全体 | グループ(`--group`・最多の値・TTY で聞いた値)は `validate_account_group` を、プラグインとプロジェクトの名前は `names.is_single_segment_name` を、プロジェクトの名前はさらに Compose のプロジェクト名の規則を通してから計画へ入れる(既定のリポジトリ名は規則の形へ整える) | 通らなければ何も変えず、理由を出して終了コード 1 で止める | ### ドメインイベント @@ -274,10 +274,12 @@ graph TD | ファイル | 中身 | | --- | --- | | `project.yml` | `version: 1`・`scale: 1`・`open_editor: true`・`repos`(`owner`・`repo`) | -| `compose.yml` | `containers/general` の `dev` 1 台。イメージ名は `<名前の小文字>:latest`。名前の形は Docker の参照より広いので、末尾の区切り文字を落とし、2 つの英数字の間に置けない区切り文字の並びを `-` にする(`app-` は `app:latest`、`app..web` は `app-web:latest`) | +| `compose.yml` | `containers/general` の `dev` 1 台。イメージ名は `<名前>:latest`。プロジェクトの名前は Docker の参照より広いので、末尾の区切り文字を落とし、2 つの英数字の間に置けない区切り文字の並びを `-` にする(`app-` は `app:latest`、`app_-web` は `app-web:latest`) | | `env` | `DEVBASE_ACCOUNT_GROUP=<グループ>` | -作業ブランチは `devbase/new--<名前>`、PR の題は `devbase: <名前> を足す`。 +プロジェクトの名前は、名前の形に加えて Compose のプロジェクト名の規則(`[a-z0-9][a-z0-9_-]*`)に合わせる。`devbase up` が名前をそのまま `COMPOSE_PROJECT_NAME` へ渡すので、合わない名前は作成が 0 で終わっても起動で止まるためである。既定のリポジトリ名は小文字にし、使えない文字の並びを `-` に置き換える(`MyApp` は `myapp`、`foo.github.io` は `foo-github-io`)。`--name` で渡された合わない名前は、計画の確定の前に終了コード 1 で止める。 + +作業ブランチは `devbase/new--<名前>`、PR の題は `devbase: <名前> を足す`。名前の形は git のブランチ名より広いので、`..` を含むか `.`・`.lock` で終わる名前は、ブランチの `<名前>` の `.` を `-` に置き換えて元の名前の SHA-256 の先頭 8 文字を足す(`app..web` は `app--web-<8 文字>`)。違う名前が同じブランチにならず、同じ名前は打ち直しても同じブランチになる。 ### 画面(`devbase list` のプラグインのメニュー) diff --git a/lib/devbase/plugin/creator.py b/lib/devbase/plugin/creator.py index 45759791..7a7d03fc 100644 --- a/lib/devbase/plugin/creator.py +++ b/lib/devbase/plugin/creator.py @@ -170,6 +170,20 @@ def _checked_name(name: str, what: str) -> str: return name +def _project_name(name: Optional[str], repo: str) -> str: + """プロジェクトの名前を決める。``devbase up`` が Compose へ渡せる名前だけを返す + + 既定のリポジトリ名は利用者が選んだものではないので形を整え、``--name`` は変えずに止める。 + """ + project = _checked_name(name or repo, "プロジェクト") + if not name: + return scaffold.compose_project_name(project) + if not scaffold.is_compose_project_name(project): + raise RepositoryError( + f"プロジェクトの名前にできません: '{project}' ({scaffold.COMPOSE_NAME_HINT})") + return project + + def _require_clone(registry: PluginRegistry, repo: RegisteredRepository) -> None: """登録の clone があることを確かめる。無ければ何も書かずに止める (読むだけ) @@ -406,7 +420,7 @@ def plan_project( """``project new`` の計画 (読むだけ)""" ref = GitHubRef.parse(value) gh.ensure_ready() - project = _checked_name(name or ref.repo, "プロジェクト") + project = _project_name(name, ref.repo) if gh.view_repo(ref) is None: raise RepositoryError(f"{ref.full_name} が見つからないか読めません") local = registry.get_projects_dir() / project diff --git a/lib/devbase/plugin/publish.py b/lib/devbase/plugin/publish.py index 4d373dd2..293692a0 100644 --- a/lib/devbase/plugin/publish.py +++ b/lib/devbase/plugin/publish.py @@ -7,7 +7,9 @@ from __future__ import annotations +import hashlib import os +import re import tempfile from pathlib import Path from typing import Dict, Optional @@ -23,6 +25,8 @@ logger = get_logger("devbase.plugin.publish") _PR_BODY = "devbase の作成フローが足しました。" +_BRANCH_UNSAFE = re.compile(r'\.\.|\.$|\.lock$') +_BRANCH_DIGEST_LENGTH = 8 class MergeFailed(RepositoryError): @@ -34,6 +38,15 @@ def __init__(self, message: str, pr_url: str): def branch_name(kind: str, name: str) -> str: + """作業ブランチの名前を返す。 + + 名前の形は git のブランチ名より広く、``a..b``・``a.``・``a.lock`` も通る。これらは ``.`` を + ``-`` に置き換え、元の名前のハッシュを足す。違う名前が同じブランチにならず、同じ名前は + 打ち直しても同じブランチになる。 + """ + if _BRANCH_UNSAFE.search(name): + digest = hashlib.sha256(name.encode()).hexdigest()[:_BRANCH_DIGEST_LENGTH] + name = f"{name.replace('.', '-')}-{digest}" return f"devbase/new-{kind}-{name}" diff --git a/lib/devbase/plugin/scaffold.py b/lib/devbase/plugin/scaffold.py index 199accd1..07a5e9a4 100644 --- a/lib/devbase/plugin/scaffold.py +++ b/lib/devbase/plugin/scaffold.py @@ -25,6 +25,11 @@ _IMAGE_SEPARATORS = re.compile(r'[._-]+') _VALID_IMAGE_SEPARATOR = re.compile(r'[._]|__|-+') _IMAGE_SEPARATOR_FALLBACK = '-' +_COMPOSE_PROJECT_NAME = re.compile(r'[a-z0-9][a-z0-9_-]*') +_COMPOSE_UNSAFE_CHARS = re.compile(r'[^a-z0-9_-]+') +_COMPOSE_FALLBACK = '-' + +COMPOSE_NAME_HINT = "小文字の英数字で始まり、小文字の英数字・`-`・`_` だけからなる形" def _scalar(value: str) -> str: @@ -57,11 +62,25 @@ def normal_plugin_path(path: str) -> str: return '' if normal == '.' else normal +def is_compose_project_name(name: str) -> bool: + """Compose のプロジェクト名にできるか。``devbase up`` は名前をそのまま Compose へ渡す""" + return _COMPOSE_PROJECT_NAME.fullmatch(name) is not None + + +def compose_project_name(name: str) -> str: + """名前の形に合う名前を Compose のプロジェクト名の形にする。 + + 小文字にし、使えない文字の並びを ``-`` に置き換える。名前の形は英数字で始まるので、結果も + 英数字で始まる。 + """ + return _COMPOSE_UNSAFE_CHARS.sub(_COMPOSE_FALLBACK, name.lower()) + + def image_name(name: str) -> str: """プロジェクト名から Docker の参照として有効なイメージ名を作る。 - 名前の形は Docker より広く、``app-`` や ``app..web`` も通る。小文字にし、末尾の区切り文字を - 落とし、2 つの英数字の間に置けない区切り文字の並びを ``-`` に置き換える。 + Compose のプロジェクト名でも ``app-`` や ``app_-web`` は Docker の参照にならない。小文字にし、 + 末尾の区切り文字を落とし、2 つの英数字の間に置けない区切り文字の並びを ``-`` に置き換える。 """ def separator(match: re.Match) -> str: found = match.group() diff --git a/tests/plugin/test_create_plugin.py b/tests/plugin/test_create_plugin.py index c7cc83ce..efc61ec8 100644 --- a/tests/plugin/test_create_plugin.py +++ b/tests/plugin/test_create_plugin.py @@ -43,6 +43,15 @@ def _assert_installed(root, name="team-a", source=URL): return plugin +@pytest.mark.parametrize("name", ["app..web", "app.", "app.lock"]) +def test_name_outside_branch_rules_is_installed(github, root, registered, run_cli, name): + assert run_cli("plugin", "new", FULL, "--name", name, "--yes") == 0 + + assert github.prs()[0]["state"] == "MERGED" + assert name in _registry_names(github) + _assert_installed(root, name) + + def test_registered_repo_gets_a_plugin(github, root, registered, run_cli, capsys): assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 pr = github.prs()[0] diff --git a/tests/plugin/test_create_project.py b/tests/plugin/test_create_project.py index f68a65a7..ad690a0d 100644 --- a/tests/plugin/test_create_project.py +++ b/tests/plugin/test_create_project.py @@ -58,6 +58,34 @@ def test_name_outside_docker_rules_gets_a_valid_image(github, root, app, run_cli assert compose["services"]["dev"]["image"] == "app:latest" +@pytest.mark.parametrize("repo, project", [ + ("MyApp", "myapp"), + ("foo.github.io", "foo-github-io"), + ("a..b", "a-b"), +]) +def test_default_name_follows_compose_rules(github, root, run_cli, repo, project): + github.add_repo(f"owner/{repo}", {"README.md": "x\n"}, permission="READ") + clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + assert run_cli("project", "new", f"owner/{repo}", "--yes") == 0 + + assert (clone / f"team-a/projects/{project}/project.yml").is_file() + assert (root / "projects" / project).exists() + assert not (root / "projects" / repo).exists() + + +@pytest.mark.parametrize("name", ["MyApp", "my.app", "app..web", "app.", "team.lock"]) +def test_name_outside_compose_rules_stops_before_writing( + github, root, app, run_cli, caplog, name): + clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) + before = _plugins_yml(root) + assert run_cli("project", "new", APP, "--name", name, "--yes") == 1 + + assert "小文字の英数字で始まり" in caplog.text + assert github.write_calls() == [] + assert not (clone / f"team-a/projects/{name}").exists() + assert _plugins_yml(root) == before + + def test_project_is_added_and_reflected(github, root, app, run_cli): clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) assert run_cli("project", "new", APP, "--yes") == 0 diff --git a/tests/plugin/test_publish.py b/tests/plugin/test_publish.py index b5a99e3e..ceda597d 100644 --- a/tests/plugin/test_publish.py +++ b/tests/plugin/test_publish.py @@ -2,6 +2,7 @@ from __future__ import annotations +import subprocess import tempfile from pathlib import Path @@ -22,6 +23,24 @@ def gh(github): return GhClient() +@pytest.mark.parametrize("name", ["app", "a.b", "app-", "app..web", "app.", "app.lock", "a.lock."]) +def test_branch_name_is_a_valid_git_branch(name): + branch = publish.branch_name("plugin", name) + subprocess.run(["git", "check-ref-format", "--branch", branch], check=True, + capture_output=True) + + +def test_branch_name_keeps_valid_names(): + assert publish.branch_name("plugin", "a.b") == "devbase/new-plugin-a.b" + + +def test_branch_name_is_unique_and_stable_for_replaced_names(): + names = ["a..b", "a.-b", "a-.b", "a--b", "a.b.", "a-b-"] + branches = [publish.branch_name("plugin", name) for name in names] + assert len(set(branches)) == len(names) + assert publish.branch_name("plugin", "a..b") == branches[0] + + def _temp_leftovers(tmp_path, monkeypatch): monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) return lambda: [p.name for p in Path(tmp_path).iterdir() if p.name.startswith("devbase-")] From 40d6c19549fc0a9a1206884f4d1b6cf28c0274e8 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 05:16:10 +0000 Subject: [PATCH 17/18] =?UTF-8?q?Docs:=20#514=20=E3=81=AE=E4=BD=9C?= =?UTF-8?q?=E6=88=90=E3=83=95=E3=83=AD=E3=83=BC=E3=82=92=E7=A2=BA=E5=AE=9A?= =?UTF-8?q?=E4=BB=95=E6=A7=98=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 設計・実装計画・要求の写しを docs/specifications/plugin-creation-flow.md へ まとめ、現在のコードと照合した。用語集の出所を確定仕様へ移し、CLI リファレンスから 確定仕様へのリンクを足す。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MLNyzXBPxRoJnnnHwA7Guz --- docs/glossary.md | 6 +- docs/glossary/glossary.json | 6 +- docs/specifications/plugin-creation-flow.md | 460 ++++++++++++++++++ docs/user/cli-reference/04-plugin.md | 2 +- issues/issue-514-design.md | 495 -------------------- issues/issue-514-plan.md | 156 ------ issues/issue-514-requirements.md | 162 ------- 7 files changed, 467 insertions(+), 820 deletions(-) create mode 100644 docs/specifications/plugin-creation-flow.md delete mode 100644 issues/issue-514-design.md delete mode 100644 issues/issue-514-plan.md delete mode 100644 issues/issue-514-requirements.md diff --git a/docs/glossary.md b/docs/glossary.md index 783a04ea..8cb95b60 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -269,6 +269,6 @@ devbase up / scale がコンテナを起動して待ち、その後にホスト | 語 | 識別子 | 意味 | 廃止した語 | 廃止した識別子 | 正本 | | --- | --- | --- | --- | --- | --- | -| プラグインリポジトリ | — | 直下に registry.yml を持つ Git リポジトリ。収めたプラグインは 0 件でもよい。devbase plugin repo add で登録する | — | — | — | -| 作成フロー | — | リポジトリ・プラグイン・プロジェクトを足す一連の操作。権限の確認からマージ、手元への取り込み、登録までを含む | — | — | — | -| 作成の計画 | — | 作成フローが書き込みの前に確定する、作るもの・ファイル・マージ先の組 | — | — | — | +| プラグインリポジトリ | — | 直下に registry.yml を持つ Git リポジトリ。収めたプラグインは 0 件でもよい。devbase plugin repo add で登録する | — | — | `docs/specifications/plugin-creation-flow.md` | +| 作成フロー | — | リポジトリ・プラグイン・プロジェクトを足す一連の操作。権限の確認からマージ、手元への取り込み、登録までを含む | — | — | `docs/specifications/plugin-creation-flow.md` | +| 作成の計画 | — | 作成フローが書き込みの前に確定する、作るもの・ファイル・マージ先の組 | — | — | `docs/specifications/plugin-creation-flow.md` | diff --git a/docs/glossary/glossary.json b/docs/glossary/glossary.json index 190e38a0..522cef74 100644 --- a/docs/glossary/glossary.json +++ b/docs/glossary/glossary.json @@ -1060,19 +1060,19 @@ "term": "プラグインリポジトリ", "context": "plugin-distribution", "meaning": "直下に registry.yml を持つ Git リポジトリ。収めたプラグインは 0 件でもよい。devbase plugin repo add で登録する", - "pending_source": "issues/issue-514-design.md" + "source": "docs/specifications/plugin-creation-flow.md" }, { "term": "作成フロー", "context": "plugin-distribution", "meaning": "リポジトリ・プラグイン・プロジェクトを足す一連の操作。権限の確認からマージ、手元への取り込み、登録までを含む", - "pending_source": "issues/issue-514-design.md" + "source": "docs/specifications/plugin-creation-flow.md" }, { "term": "作成の計画", "context": "plugin-distribution", "meaning": "作成フローが書き込みの前に確定する、作るもの・ファイル・マージ先の組", - "pending_source": "issues/issue-514-design.md" + "source": "docs/specifications/plugin-creation-flow.md" } ] } diff --git a/docs/specifications/plugin-creation-flow.md b/docs/specifications/plugin-creation-flow.md new file mode 100644 index 00000000..d4e5e3f0 --- /dev/null +++ b/docs/specifications/plugin-creation-flow.md @@ -0,0 +1,460 @@ +# リポジトリ・プラグイン・プロジェクトの作成フロー + +## 概要 + +`devbase plugin repo new`・`devbase plugin new`・`devbase project new` は、GitHub の URL か `owner/repo` を +1 つ受け、権限の確認からファイルの配置・PR・マージ・手元への取り込み・`plugins.yml` への登録までを 1 回で行う。 +`devbase list` の TUI のプラグインのメニューからも同じ操作を実行できる。 + +どのコマンドも、書き込みの前に作成の計画を確定して利用者に示す。計画までは読むだけで、GitHub にも手元にも +書かない。コンテナは起動しない(`devbase up` は打たない)。`gh` が要るのはこの 3 つのコマンドだけである。 + +利用者向けの引数と使い方は [plugin グループ](../user/cli-reference/04-plugin.md) と +[project グループ](../user/cli-reference/02-project.md#devbase-project-new) にある。 + +## 用語 + +プラグインリポジトリ・作成フロー・作成の計画・名前の形・アカウントグループは [用語集](../glossary.md) の定義に従う。 +プラグインリポジトリは、収めたプラグインが 0 件(`plugins: []`)でもよい。 + +## コンテキスト + +| コンテキスト | 何の語が 1 つの意味に決まるか | +| --- | --- | +| プラグインの配布 | プラグインリポジトリ・プラグイン・プロジェクト・登録・導入・作成フロー | +| 機密の置き場(`secret`) | アカウントグループとその宣言 | +| コマンドの入口(`cli`) | 名前の形 | + +作成フローはプラグインの配布に属する。ほかの 2 つに対しては順応者で、グループの規則 +(`validate_account_group`)と名前の形(`names.is_single_segment_name`)をそのまま受け入れ、独自の規則を持たない。 + +## 背景 + +GitHub 上のプラグインへリポジトリを足すには、`registry.yml`・`plugin.yml`・`project.yml` を人が置き、PR を出してマージし、 +`plugin update` を打つ必要がある。作成フローは、この手作業と入れ先の判断をまとめて行う。 + +既存の経路とのつなぎ目には、次の事実がある。 + +| 事実 | 仕様への影響 | +| --- | --- | +| `add_repository` は `registry.yml` が無いリポジトリを登録せず、clone を消す | `registry.yml` を既定ブランチへ入れてから登録する | +| `refresh_repository` の `git pull` は `--ff-only` を付けない | 登録済みの clone は先に `_pull_ff_only` で取り込む | +| `get_repository_by_url` は完全一致で探す | 登録の照合には使わず、URL の形を吸収する `_find_registered` を使う | +| GitHub は空のリポジトリに PR を作れない | 空のリポジトリの最初のコミットだけを既定ブランチへ直接入れる | + +## 対象範囲 + +| 区分 | 内容 | +| --- | --- | +| 含む | 3 つのコマンド、PR の作成・マージ・手元への取り込み・`plugins.yml` への登録、TUI の入口とプラグインのメニュー、シェル補完 | +| 含まない | 追加したプロジェクトの起動、`env` の値の登録、`pre-up` などのフック、`Dockerfile` の雛形の出し分け、プラグインの `description` の書き足し、GitHub 以外のホスト、Organization の作成、`gh` の導入やログインの代行 | + +## 構成要素 + +| 要素 | 置き場所 | 責務 | +| --- | --- | --- | +| 引数の解決と `gh` の呼び出し | `lib/devbase/plugin/github.py` | `GitHubRef`(引数の解決)、`GhClient`(権限・作成・PR・マージ)、`RepoView`。トークンを扱わない | +| 雛形と `registry.yml` の追記 | `lib/devbase/plugin/scaffold.py` | 雛形の文字列の生成、`registry.yml` への 1 項目の追記と読み直し、Compose とイメージの名前の形。外部へ出ない純粋な処理 | +| 既定ブランチへの反映 | `lib/devbase/plugin/publish.py` | 一時の浅い clone で変更を作る。`push_initial`(最初のコミット)、`publish_change`(push・PR・マージ)、`branch_name`、`MergeFailed` | +| 計画と実行 | `lib/devbase/plugin/creator.py` | `plan_repo`・`plan_plugin`・`plan_project`(読むだけ)、`execute`(書く)、`CreationPlan`、入れ先とグループの決定 | +| 登録の照合と取り込み | `lib/devbase/plugin/repo_manager.py` | `_find_registered`、`_require_default_branch`、`_pull_ff_only`、`_snapshot_repo_projects`。`refresh_repository` は控えを `pre_pull_projects` で受ける | +| CLI の入口 | `lib/devbase/commands/plugin.py`、`lib/devbase/commands/project.py` | `cmd_plugin_new`・`cmd_repo_new`・`cmd_project_new`、計画の確認 `run_creation`、端末で聞く `_TtyPrompter` | +| パーサと機密の注入 | `lib/devbase/cli.py` | パーサ、`SUBCMD_MAP`、`repo_subcmds`、`_NO_SECRET_INJECTION`、`_injection_subcommand` | +| TUI | `lib/devbase/tui/actions_plugin.py` | 2 階層のメニューと新規追加の 3 つの入口 | +| シェル補完 | `etc/_devbase`、`etc/devbase-completion.bash` | 3 つのコマンドとオプションの候補 | + +```mermaid +graph TD + CLI[commands/plugin・project] --> C[creator] + TUI[tui/actions_plugin] -->|確かめた値を --yes 相当で渡す| CLI + TUI -->|候補・グループの案・計画| C + C --> S[scaffold] + C --> P[publish] + C --> G[github] + P --> G + P --> S + C --> R[repo_manager・installer] + P -->|clone と git の実行| R + R --> Reg[plugins.yml] +``` + +`bin/devbase` は変わらない。`_PROJECT_NAME_SUBCOMMANDS` に `new` が無いので、`project new owner/repo` の引数は +プロジェクト名として解決されない。`new` は `project`・`plugin` の既存の副命令と接頭辞が重ならないため、 +`SUBCMD_PREFIX_PREFERENCES` は持たない。 + +## 仕様 + +### 集約 + +| 集約 | 持ち主(書き換えてよいもの) | 根 | エンティティ | 値オブジェクト | +| --- | --- | --- | --- | --- | +| プラグインリポジトリ(GitHub の既定ブランチ) | 中身は `publish` が PR のマージと、空のリポジトリの最初のコミットで書く。リポジトリの作成は `creator` が `GhClient.create_repo` を呼んで行う | リポジトリ | プラグイン・プロジェクト | `GitHubRef`・`registry.yml` の項目 | +| 手元の登録(`plugins.yml`) | `PluginRegistry`(`add_repository`・`install_plugin`・`refresh_repository` 経由だけ) | `plugins.yml` | 登録済みリポジトリ・導入済みプラグイン | — | +| 手元の clone(`repos/` の clone と `projects/` への反映) | `_pull_ff_only`(取り込み)と、`add_repository`(clone)・`install_plugin`・`refresh_repository`(`projects/` への反映) | `repos/` の clone | 作業ツリー | — | + +`creator` と `publish` は手元の `repos/` の clone へファイルを置かない。手元が変わるのは、既定ブランチへの反映の後に +上の持ち主を呼ぶときだけである。 + +### 常に成り立つ条件 + +| # | 集約 | 条件 | 破れたときの扱い | +| --- | --- | --- | --- | +| I1 | 全体 | 計画の確定(解決と確認)が終わるまで、GitHub にも手元にも書かない | テストで止める | +| I2 | 手元の登録 | 作成フローが既定ブランチへ入れる変更がすべて反映される(最初のコミットの push かマージが成功する)まで `plugins.yml` を変えない。入れる変更が無い経路は、確認の後にそのまま登録する | テストで止める | +| I3 | プラグインリポジトリ | `registry.yml` の編集の前後で既存の項目が同じで、増えるのは 1 項目だけである | 読み直しで不一致なら push せず止める | +| I4 | 手元の clone | 未コミットの変更を失わない | 取り込みが変更とぶつかれば止める | +| I5 | プラグインリポジトリ | リポジトリの公開は `--public` のときだけである | テストで止める | +| I6 | 全体 | 作成フローはコンテナを起動しない | テストで止める | +| I7 | プラグインリポジトリ | 既定ブランチへの直接の push は、空のリポジトリの最初のコミットだけである | テストで止める | +| I8 | 手元の clone | 手元の clone の取り込みは早送りだけである | 早送りできなければ止める | +| I9 | 全体 | グループ(`--group`・最多の値・端末で聞いた値)は `validate_account_group` を、プラグインとプロジェクトの名前は `names.is_single_segment_name` を、プロジェクトの名前はさらに Compose のプロジェクト名の規則を通してから計画へ入れる | 通らなければ何も変えず、理由を出して終了コード 1 で止まる | + +### コマンド + +| コマンド | 引数 | 終了コード | +| --- | --- | --- | +| `devbase plugin repo new ` | `--public`(既定 private)、`--yes` | 0 成功・push できる登録済み / 1 それ以外 | +| `devbase plugin new ` | `--name`(既定はリポジトリ名)、`--public`、`--yes` | 0 成功 / 1 それ以外 | +| `devbase project new ` | `--plugin`、`--group`、`--name`(既定はリポジトリ名を整えたもの)、`--yes` | 0 成功 / 1 それ以外 | + +`` は `owner/repo`・`https://github.com/owner/repo[.git]`・`git@github.com:owner/repo[.git]` を受ける。`git@` の形の +入力は clone の URL も `git@` のままにし、ほかは `https://github.com/owner/repo.git` にする。GitHub 以外の URL と形の誤りは +終了コード 1 になる。 + +`--public` は新しく作るときだけ効き、既存のリポジトリの公開範囲は変えない。 + +### 計画の確認 + +`run_creation` が `CreationPlan.describe()` の文面を出して確認を取る。 + +| 状況 | 動作 | +| --- | --- | +| `--yes` がある | 確認を出さずに実行する | +| 端末がある | `[y/N]` で聞く。`y`・`yes` のほかは何も変えず終了コード 1 | +| 端末が無く `--yes` も無い | 何も変えず終了コード 1 | +| 計画に `noop_reason` がある | 計画も確認も出さず、理由を出して終了コード 0 | + +### リポジトリの分岐 + +`plugin repo new` と、未登録のリポジトリへの `plugin new` が通る。 + +| リポジトリ | push | `registry.yml` | 動作 | +| --- | --- | --- | --- | +| 無い・未登録 | owner に作れる | — | 作る → 最初のコミットを直接 push → 登録 | +| 無い・未登録 | owner に作れない | — | 終了(1) | +| 無い・登録済み | — | — | 終了(1)。権限を失った登録の URL へ新しいリポジトリを作らない | +| 空・未登録 | できる | — | 最初のコミットを直接 push → 登録 | +| ある・未登録 | できる | 無い | PR → マージ → 登録 | +| ある・未登録 | できる | ある | 登録だけ | +| 空・ある・登録済み | できる | — | `plugin repo new` は何もせず 0 | +| 空・ある | できない | — | 終了(1)。登録済みでも同じ | + +- push できるのは `viewerPermission` が `ADMIN`・`MAINTAIN`・`WRITE` のときである +- owner に作れるのは次のどちらかのときである + - owner が `gh api user` の `login` と同じである(大文字小文字は区別しない) + - `gh api user/memberships/orgs/` の `state` が `active` で、`role` が `admin` か、組織の `members_can_create_repositories` が偽でない +- `members_can_create_repositories` は組織の owner にしか返らない。値が無いときは判定できないので計画へ進め、作れなければ `gh repo create` の出力を示して止まる +- 読めない private のリポジトリは「無い」と同じに見える。未登録なら `gh repo create` の失敗の出力を示して止まる +- 未登録で `repos/` の clone の置き場が既にあるときは、確認の前に終了コード 1 で止まる。`add_repository` の拒否でマージの後に止まるのを避けるためである + +### 登録の照合 + +登録済みか未登録かは、計画の確定の前に `_find_registered` で決める。入力の URL と `plugins.yml` の全登録の `repo.url` を +`_url_to_repos_dirname` の一致で比べる。比べ方は `_reject_duplicate_registration` と同じで、`add_repository` が拒否するものを +計画の段階で登録済みの経路へ入れる。 + +見つけた登録は計画に持ち、登録済みの経路の呼び出しには入力の URL ではなく登録の値を渡す。`install_plugin` の内部が +`get_repository_by_url` の完全一致で登録を探すためである。 + +| 呼び出し | 渡す値 | +| --- | --- | +| `_pull_ff_only` | 登録の `repo.local_path` の clone | +| `refresh_repository` | 登録の `repo.name` | +| `install_plugin` | `:<プラグイン名>`(登録の `repo.url`) | +| 一時の clone と push(`plugin new`・`project new`) | 登録の `repo.url`(SSH の認証だけの利用者が https で止まらない) | + +### 計画の確定の前の確認 + +`plugin new` と `project new` は、計画の確定の前に次を確かめる。対象の登録は、`plugin new` では `_find_registered` が見つけた +登録、`project new` では入れ先のプラグインの登録である。どれも GitHub にも手元にも書かず、終了コード 1 で止まる。 + +| 確認 | 止まる理由 | 案内 | +| --- | --- | --- | +| `repo.local_path` が空でなく、`devbase_root / repo.local_path` がディレクトリである | 空のまま進むと `devbase_root` そのものを指し、devbase 本体を取り込む | `plugin repo remove ` と `plugin repo add `。導入し直す `plugin install` も案内する | +| clone が GitHub の既定ブランチにいて、`origin` の同じブランチを追っている | clone の `origin/HEAD` は既定ブランチの変更に追従せず、取り込みが成功しても足したものが手元に現れない | 切り替えのコマンド | +| `plugin new`: 登録済みのリポジトリの既定ブランチに `registry.yml` がある | 登録済みの経路は 1 項目の追記だけで、リポジトリの分岐を通らない | — | +| `project new`: 登録の `path` が既定ブランチの `registry.yml` の項目と同じである | 古い `path` へマージすると、足したプロジェクトが `projects/` に現れないまま 0 で終わる | `plugin repo refresh ` | + +`plugin repo new` はこれらを確かめない。登録済みの経路は clone に触らないので、`local_path` が空でも push できれば何もせず 0 で終わる。 + +### 経路ごとの反映と登録 + +| コマンド | リポジトリ | 既定ブランチへの反映 | 登録と反映(反映の後に行う) | 通るイベント(E4 の後) | +| --- | --- | --- | --- | --- | +| `plugin repo new` | 無い | 最初のコミットの直接の push | `add_repository` | E5 → E6 → E9 | +| `plugin repo new` | 空 | 最初のコミットの直接の push | `add_repository` | E6 → E9 | +| `plugin repo new` | `registry.yml` が無い | PR のマージ | `add_repository` | E6 → E7 → E9 | +| `plugin repo new` | `registry.yml` がある・未登録 | 無し | `add_repository` | E9 | +| `plugin new` | 登録済み | プラグインの PR のマージ | `_pull_ff_only` → `refresh_repository` → `install_plugin` | E6 → E7 → E8 → E9 | +| `plugin new` | 無い | 最初のコミット → プラグインの PR のマージ | `add_repository` → `install_plugin` | E5 → E6 → E6 → E7 → E9 | +| `plugin new` | 空 | 最初のコミット → プラグインの PR のマージ | `add_repository` → `install_plugin` | E6 → E6 → E7 → E9 | +| `plugin new` | `registry.yml` が無い | `registry.yml` の PR のマージ → プラグインの PR のマージ | `add_repository` → `install_plugin` | E6 → E7 → E6 → E7 → E9 | +| `plugin new` | `registry.yml` がある・未登録 | プラグインの PR のマージ | `add_repository` → `install_plugin` | E6 → E7 → E9 | +| `project new` | 入れ先のプラグインのリポジトリ(登録済み) | プロジェクトの PR のマージ | `_pull_ff_only` → `refresh_repository` | E6 → E7 → E8 → E9 | + +未登録のリポジトリには手元の clone が無いので E8 を通らず、`add_repository` が clone する。 + +未登録のリポジトリへの `plugin new` は、リポジトリの分の反映とプラグインの追加を別の変更として順に行い、プラグインの PR の +マージが成功してから登録する。先に登録すると、マージの失敗で `plugins.yml` が変わったまま残るためである。 + +登録済みの経路は `_pull_ff_only` の前に、導入済みのプラグインのプロジェクト一覧を `_snapshot_repo_projects` で控え、 +`refresh_repository` へ `pre_pull_projects` で渡す。取り込みにプラグインの改名や移動が入っていても移行先を見つけられる。 + +```mermaid +sequenceDiagram + participant U as 利用者 + participant C as creator + participant G as gh + participant T as 一時の clone + participant L as 手元 + U->>C: コマンド + C->>G: 認証と権限(読むだけ) + C->>L: 登録の照合と clone の確認(読むだけ) + C->>U: 作成の計画と確認 + U-->>C: 承認 + opt リポジトリが無い + C->>G: repo create + end + alt 空のリポジトリ + C->>T: 浅い clone → registry.yml → commit → 既定ブランチへ push + else registry.yml が無い + C->>T: 浅い clone → ブランチ → registry.yml → commit → push + C->>G: PR 作成 → マージ + else registry.yml がある + Note over C,T: リポジトリの分岐では GitHub へ書かない + end + opt plugin new・project new + C->>T: 浅い clone → ブランチ → プラグインかプロジェクトのファイル → commit → push + C->>G: PR 作成 → マージ + end + opt 登録済みのリポジトリ + C->>L: 早送りの取り込み + end + C->>L: 登録・反映 +``` + +### ドメインイベント + +| # | イベント | 発生元 | 受け手 | +| --- | --- | --- | --- | +| E1 | 引数を GitHub の owner/repo へ解決した | `GitHubRef.parse` | 各フロー | +| E2 | `gh` の認証と権限を確かめた | `GhClient` | 各フロー | +| E3 | 入れ先のプラグインとグループを決めた | `plan_project` | 計画 | +| E4 | 実行の計画を示して確認を得た | CLI・TUI | `execute` | +| E5 | リポジトリを作った | `GhClient.create_repo` | `publish` | +| E6 | 手元の clone と別の作業場所でブランチを作り、ファイルを置いて push した | `publish` | `GhClient` | +| E7 | PR を作ってマージした | `GhClient` | 取り込み | +| E8 | 手元の clone へ取り込んだ | `_pull_ff_only` | 登録 | +| E9 | `plugins.yml` へ登録し、`projects/` へ反映した | `add_repository`・`install_plugin`・`refresh_repository` | 利用者 | + +最初のコミットの push も E6 に含む。 + +### プラグインの計画 + +名前は `--name`、無ければリポジトリ名である。名前の形に合わなければ終了コード 1 になる。次のときは何も変えずに終了コード 1 になる。 + +- 同じ名前のプラグインが導入済みである +- 同じ名前の項目が既定ブランチの `registry.yml` にある +- 同じ名前のパスがリポジトリにある + +### プロジェクトの計画 + +**名前。** プロジェクトの名前は、名前の形に加えて Compose のプロジェクト名の規則(`[a-z0-9][a-z0-9_-]*`)に合わせる。 +`devbase up` が名前をそのまま `COMPOSE_PROJECT_NAME` へ渡すので、合わない名前は作成が 0 で終わっても起動で止まるためである。 + +| 名前の出所 | 扱い | +| --- | --- | +| リポジトリ名(既定) | 名前の形を確かめた後、小文字にし、使えない文字の並びを `-` に置き換える(`MyApp` は `myapp`、`foo.github.io` は `foo-github-io`) | +| `--name` | 変えない。規則に合わなければ計画の確定の前に終了コード 1 で止まる | + +**対象。** 対象のリポジトリを読めないとき、同じ名前が手元の `projects/`(壊れた symlink を含む)か入れ先の既定ブランチに +あるときは、何も変えずに終了コード 1 になる。 + +**入れ先のプラグイン。** 次の順に決める。 + +1. `--plugin` があればそれを使う。導入済みの GitHub のプラグインの中に無いか、push できなければ終了コード 1 になる +2. 導入済みで、リンクの導入でなく、登録済みの GitHub のリポジトリに項目があり、そのリポジトリが空でなく push できるものを候補にする。`gh` はリポジトリごとに 1 回呼ぶ +3. 対象と同じ owner の候補があれば、それに絞る(大文字小文字は区別しない) +4. 1 件ならそれを計画に示す。複数なら端末で選ばせ、端末が無ければ候補を出して終了コード 1 になる。0 件なら終了コード 1 になる + +入れ先のパスは、導入済みの `plugin.path` の `repo.local_path` からの相対で決める。`registry.yml` の項目に `path` が無い +プラグインは、導入と同じくリポジトリの直下として扱い、書き込み先は `projects/<名前>` になる。 + +**グループ。** `--group`、入れ先の既存プロジェクトの最多の値の順に決める。最多が同数か値が無いときは端末で聞き、端末が無ければ +終了コード 1 になる。入れ先の既存プロジェクトの宣言を読めないものは、数えない。どの出所の値も `validate_account_group` を通す。 + +### TUI + +プラグインのメニューは第 1 階層が用途で、各項目はサブメニューへ入る。先頭の「見る」は閲覧だけで、Enter を続けて押しても安全な +一覧へ届く。 + +| 第 1 階層 | 第 2 階層 | +| --- | --- | +| 見る | 導入済み一覧・利用可能一覧・詳細・リポジトリ一覧 | +| 新規追加 | プロジェクト・プラグイン・リポジトリ | +| 導入・更新 | インストール・更新・リポジトリ登録・リポジトリ更新 | +| 削除 | アンインストール・リポジトリ削除 | +| 保守 | リンクの再同期・レガシー構成の移行 | + +新規追加の入力の順は次のとおりである。入力ごとに Esc・← で 1 つ前のメニューへ戻り、Ctrl-C で全体を中止する。 + +| 項目 | 順 | +| --- | --- | +| プロジェクト | リポジトリ → 名前(空で既定)→ 入れ先の選択(候補が 1 件なら選択を出さない)→ グループ(案を既定値に)→ 計画の確認 | +| プラグイン | リポジトリ → 名前(空で既定)→ 計画の確認 | +| リポジトリ | リポジトリ → 公開するかの確認(既定 いいえ)→ 計画の確認 | + +TUI は `creator` の読むだけの関数で候補・案・計画を得て、確かめた値を `yes=True` で `cmd_plugin`・`cmd_project_new` へ渡す。 +入力の差を CLI と TUI で分けないため、ロジックは二重に持たない。TUI のプラグインの入口は `--public` を持たない。 +`plugin repo new` の計画が `noop_reason` を持つときは、確認を出さずに渡す。 + +## データ・設定 + +`plugins.yml` の形は変わらない。 + +### 雛形 + +雛形は `scaffold.py` の文字列で生成する。小さな 3 種類で差し替えの要求が無く、テンプレートの置き場と依存を増やさないためである。 + +| 種類 | ファイル | 中身 | +| --- | --- | --- | +| リポジトリ | `registry.yml` | `name: <リポジトリ名>`・`description: ""`・`plugins: []` | +| プラグイン | `<名前>/plugin.yml` | `name`・`version: "1.0.0"`・`description: ""`・`requires.devbase: ">=3.0.0"`・`projects.mode: auto`・`priority: 50` | +| プラグイン | `<名前>/projects/.gitkeep` | 空 | +| プロジェクト | `<プラグインの path>/projects/<名前>/project.yml` | `version: 1`・`scale: 1`・`open_editor: true`・`repos`(`owner`・`repo`) | +| プロジェクト | `<プラグインの path>/projects/<名前>/compose.yml` | `containers/general` を建てる `dev` 1 台。ネットワークは外部の `devbase_net` | +| プロジェクト | `<プラグインの path>/projects/<名前>/env` | `DEVBASE_ACCOUNT_GROUP=<グループ>` | + +`compose.yml` のイメージ名は `<名前>:latest` である。プロジェクトの名前は Docker の参照より広いので、小文字にし、末尾の区切り文字を +落とし、2 つの英数字の間に置けない区切り文字の並びを `-` にする(`app-` は `app:latest`、`app_-web` は `app-web:latest`)。 + +### `registry.yml` の追記 + +コメントと引用符の形を保つため、YAML を書き戻さず文字列で 3 行(`name`・`path`・`description`)を足す。新しい依存も足さない。 + +| `plugins` の形 | 動作 | +| --- | --- | +| キーが無い | 末尾へブロックを足す | +| `plugins: []` | ブロックへ置き換える | +| ブロックで項目が無い | キーの直後へ足す | +| ブロックで項目がある | 最後の項目の後へ、同じ字下げで足す | +| それ以外の値 | 足せないので止まる | + +追記の後に読み直し、既存の項目が同じで 1 項目だけ増えたことを確かめ、違えば止まる(I3)。 + +### 作業ブランチと PR + +作業ブランチは `devbase/new-<種類>-<名前>`、PR の題は `devbase: <種類> <名前> を足す` である。種類は `repo`・`plugin`・`project` で、 +PR の本文は固定の 1 行である。 + +名前の形は git のブランチ名より広いので、`..` を含むか `.`・`.lock` で終わる名前は、ブランチの `<名前>` の `.` を `-` に置き換えて +元の名前の SHA-256 の先頭 8 文字を足す(`app..web` は `app--web-<8 文字>`)。違う名前が同じブランチにならず、同じ名前は打ち直しても +同じブランチになる。 + +### 一時の clone + +手元の未コミットの変更を守り、登録の有無を同じ手順で扱うため、作業は `tempfile.TemporaryDirectory` の `git clone --depth 1` で行う。 +成功でも失敗でも作業場所は残らない。 + +書き込むパスは、symlink と `..` を解決して clone の中に収まることを確かめる。clone の中身は他人が書いたもので、書き込みが利用者の +手元のファイルへ届かないようにするためである。外を指すものがあれば 1 ファイルも書かずに止まる。既にあるパスは上書きしない。 + +## 外部連携 + +GitHub の操作は `gh` の呼び出しで行う。認証を利用者の設定に任せられ、アプリがトークンを受け取らずに済むためである。 + +| 操作 | 呼び出し | +| --- | --- | +| 導入と認証の確認 | `shutil.which('gh')`、`gh api user` | +| リポジトリの状態 | `gh repo view --json isEmpty,defaultBranchRef,viewerPermission`。`Could not resolve to a Repository` は「無い」と読む | +| owner に作れるか | `gh api user/memberships/orgs/`、`gh api orgs/`。HTTP 403・404 は値が無いと読む | +| 既定ブランチのファイル | `gh api repos//contents/`。HTTP 404 は「無い」と読む | +| リポジトリの作成 | `gh repo create --private`(`--public` のときだけ `--public`) | +| PR | `gh pr create`、`gh pr list`(開いている PR の確認) | +| マージ | `gh pr view --json mergeable`、`gh repo view`(方式の確認)、`gh pr merge <方式> --delete-branch` | + +`gh` の子プロセスは `GH_HOST=github.com` で動かす。`GitHubRef` が受けるのも `git` が操作するのも github.com だけで、`GH_HOST` が別の +ホストを指すと確認やリポジトリの作成が `git` と別のホストへ向かうためである。`gh` の版は確かめない。古くて失敗したときは、その +出力で止まる。 + +**マージは 1 回だけ試す。** `mergeable` が `UNKNOWN` の間は 2 秒おきに最大 15 回読み、判定が出てから `gh pr merge` を 1 回実行する。 +CI は待たず、`--auto` と `--admin` は使わない。必須の検査やレビューを越えないためで、CI を持たないプラグインリポジトリも多い。 +マージの方式は、リポジトリが許す順に merge・squash・rebase から選ぶ。 + +## エラー処理 + +エラーは `RepositoryError`(`git_clone` の失敗は `PluginError`)の本文に理由と次のコマンドを載せ、CLI がエラーとして出して +終了コード 1 を返す。進んだ段階は `logger.info` で 1 行ずつ出す。 + +| 止まった所 | 残るもの | 出す案内 | +| --- | --- | --- | +| 解決・確認 | 何も残らない | 理由 | +| `gh` が無い・未認証 | 何も残らない | `gh` の入手先と `gh auth login` | +| 作ったリポジトリへの反映 | 作ったリポジトリ | 作成済みであることと、同じコマンドの打ち直し | +| 同じブランチが既にある | 既存のブランチと PR | 開いている PR があればその URL。無ければブランチを消して打ち直す案内 | +| PR の作成 | GitHub のブランチ | ブランチを消して打ち直す案内 | +| マージ | PR とブランチ | PR の URL と、マージの後に打つコマンド(未登録は `plugin repo add`、登録済みは `plugin repo refresh`。`plugin new` は `plugin install` も) | +| `plugin new` の `registry.yml` の PR | PR とブランチ。プラグインの PR はまだ無い。`plugins.yml` は元のまま | PR の URL と、マージの後に同じ `plugin new` を打ち直す案内 | +| 未登録のリポジトリへの `plugin new` のプラグインの PR | 先に反映した最初のコミットか `registry.yml` は既定ブランチに残る。`plugins.yml` は元のまま | PR の URL と、マージの後に打つコマンド(`plugin repo add`・`plugin install`) | +| 取り込み | マージ済み。手元は元のまま | 原因と `git -C status`、続けて打つコマンド | +| 登録 | マージと取り込み済み | 既存のコマンドのエラーと、続けて打つコマンド | + +取り込みは、既定ブランチ以外・detached HEAD・分岐した clone・作業ツリーの変更とぶつかる場合に何も変えず止まる。 + +## セキュリティ + +- 認証は `gh`・`git` の既存の設定に任せ、トークンを引数へ渡さない +- 機密の `GH_TOKEN` が環境変数に載ると `gh` がそのトークンで動くので、3 つのコマンドは機密を注入しない(`_NO_SECRET_INJECTION`。`pl` の別名でも同じ)。TUI は起動時の注入が載ったまま動くので、`gh` を呼ぶ前に `clear_injected` で取り除く +- `gh` の標準エラーはそのままエラーへ載せる +- リポジトリの公開は `--public` のときだけである(I5)。公開範囲を黙って広げない +- 一時の clone へ書くパスは clone の外へ出さない + +## 運用 + +- 外部コマンドは `gh`・`git` で、Linux・macOS で動く。`gh` は devbase の必須の依存ではなく、この 3 つのコマンドだけが要る +- 組織の規則で private の作成が禁じられているときは事前に判定せず、`gh repo create` の失敗で止まる +- 登録の照合は URL の大文字小文字の違いを同じものと見ない(devbasex/devbase#516) +- 実の GitHub での完走と TUI の見た目は、テストでは確かめない。作業用の Organization かアカウントで 3 つのコマンドを打つ配布後の確認の対象である + +## テスト観点 + +テストは実の GitHub に触らない。`tests/plugin/creation_harness.py` の偽の `gh` と、`url..insteadOf` で向けた手元の bare +リポジトリと本物の `git` で通し、作ったもの・PR・`plugins.yml` を結果で見る。 + +| 観点 | 満たすこと | テスト | +| --- | --- | --- | +| リポジトリの分岐 | 分岐の表の全行で、作るもの・PR・登録・終了コードが表のとおりである。既定は private で `--public` のときだけ公開になる。`plugins: []` も登録できる | `tests/plugin/test_create_repo.py` | +| 引数の解決 | 4 つの形が同じ owner/repo に解決され、GitHub 以外は拒まれる | `tests/plugin/test_github.py` | +| プラグイン | `plugin.yml`・`registry.yml` の項目が入り、`plugin list` に出る。重複名と名前の形の誤りは何も変えない | `tests/plugin/test_create_plugin.py` | +| 未登録へのプラグイン | 4 状態で、リポジトリの分 → プラグインの PR → 登録の順である | `tests/plugin/test_create_plugin.py` | +| 登録の照合 | URL の形が違っても登録済みの経路を通り、`plugins.yml` の `url` が変わらない。push できない登録は何も書かず 1 で終わる | `tests/plugin/test_create_plugin.py`、`tests/plugin/test_create_repo.py` | +| 登録の clone | `local_path` が空か clone が無い登録は、確認の前に止まり、書き込みの呼び出しが 0 回で、devbase 本体が変わらない。`plugin repo new` は 0 で終わる | `tests/plugin/test_create_plugin.py`、`tests/plugin/test_create_project.py` | +| プロジェクト | 3 ファイルと `projects/<名前>` の反映。読めないとき・重複のときは何も変わらない | `tests/plugin/test_create_project.py` | +| 入れ先とグループ | 決定の 4 段を満たす。同数で片方を選ばず、どの出所でもグループの規則を通す | `tests/plugin/test_create_project.py` | +| 名前 | Compose・Docker の参照・git のブランチ名の規則に合う | `tests/plugin/test_create_project.py`、`tests/plugin/test_create_plugin.py`、`tests/plugin/test_publish.py` | +| コンテナ | どの経路でも `docker` と `compose` を呼ばない | `tests/plugin/test_create_project.py` ほか | +| `gh` と確認 | `gh` が無い・未認証・確認の前は書き込みの呼び出しが 0 回である。端末が無く `--yes` が無ければ 1 である | `tests/plugin/test_create_repo.py` ほか | +| 手元の clone | 未コミットの変更が残り、分岐した clone と既定ブランチを追わない clone は止まる。`creator`・`publish` は手元の作業ツリーへ書かない | `tests/plugin/test_repo_manager_creation.py`、`tests/plugin/test_create_plugin.py` | +| マージの失敗 | `plugins.yml` が同じで URL が出る。未登録のリポジトリへの `plugin new` でも同じである。成功のとき作業場所が残らない | `tests/plugin/test_create_plugin.py`、`tests/plugin/test_create_project.py` | +| `registry.yml` | コメント付きのファイルで既存の行が残り、壊れる追記は止まる | `tests/plugin/test_scaffold.py` | +| TUI | メニューの全項目が既存の操作へ届き、Esc と Ctrl-C の戻り値が既存どおりに伝わる | `tests/cli/tui/test_actions_plugin.py` | +| 退行 | 既存の `plugin` のサブコマンドが変わらない。`project new owner/repo` がプロジェクトの切替を通らない。補完の候補が CLI と一致する | `tests/cli/test_project_new_dispatch.py`、`tests/cli/test_completion.py` | + +## 関連リンク + +- [CLI リファレンス: 作成フロー](../user/cli-reference/04-plugin.md#作成フローplugin-new--plugin-repo-new--project-new-に共通) +- [CLI リファレンス: `devbase project new`](../user/cli-reference/02-project.md#devbase-project-new) +- [プラグイン開発クイックスタート: コマンドで足す](../plugin-dev/quickstart.md#コマンドで足す) +- [plugin.yml リファレンス](../plugin-dev/plugin-yml-reference.md) +- [位置引数の解決](cli-argument-resolution.md) +- 課題: devbasex/devbase#514。実装 PR: #517・#518 diff --git a/docs/user/cli-reference/04-plugin.md b/docs/user/cli-reference/04-plugin.md index 854d0de0..b571632a 100644 --- a/docs/user/cli-reference/04-plugin.md +++ b/docs/user/cli-reference/04-plugin.md @@ -89,7 +89,7 @@ devbase plugin migrate ## 作成フロー(`plugin new` / `plugin repo new` / `project new` に共通) -リポジトリ・プラグイン・プロジェクトを足すコマンドは、権限の確認からマージ、手元への取り込み、登録までを 1 回で行います。 +リポジトリ・プラグイン・プロジェクトを足すコマンドは、権限の確認からマージ、手元への取り込み、登録までを 1 回で行います。振る舞いの正本は[確定仕様](../../specifications/plugin-creation-flow.md)にあります。 - **対象は GitHub だけです。** 引数は `owner/repo`・`https://github.com/owner/repo[.git]`・`git@github.com:owner/repo[.git]` のどれかです。`git@` の形で渡すと clone の URL も `git@` になります - **`gh` が要ります。** 入っていない・ログインしていないときは、何も変えずに次の操作を出して終了コード 1 で止まります。認証は `gh` と `git` の設定に任せます diff --git a/issues/issue-514-design.md b/issues/issue-514-design.md deleted file mode 100644 index f0891c89..00000000 --- a/issues/issue-514-design.md +++ /dev/null @@ -1,495 +0,0 @@ -# リポジトリ・プラグイン・プロジェクトの新規追加: 1 回の操作でマージと手元の取り込みまで済ませる(#514) - -## 目的 - -- **今どうなっているか**: 新しいリポジトリを devbase で使い始めるには、`registry.yml`・`plugin.yml`・`project.yml` などを手で置き、PR を出してマージし、`plugin update` まで打つ必要がある -- **誰に効くか**: プラグインの保守者と、社内のプラグインリポジトリへプロジェクトを足す開発者 -- **変えると何が成り立つか**: 引数 1 つのコマンドか `devbase list` の TUI で、権限の確認から手元の `projects/` への反映までが終わる - -## 適用範囲 - -- **働く範囲**: devbase の CLI と TUI。書き込む先は利用者が指定した GitHub のリポジトリと手元の `repos/`・`projects/`・`plugins.yml` -- **プロジェクトごとに違うもの**: 入れ先のプラグイン・アカウントグループ・名前は引数で受け、無ければ決定の規則で決める -- **当たるモード**: `standard` - -## あるべき姿の根拠 - -| 根拠 | 種類 | 何を示すか | -| --- | --- | --- | -| 「PRを作成してmerge、手元に取り込むところまで実施して完了」 | 利用者の指示の原文 | 完了の位置 | -| `gh repo view --json isEmpty,defaultBranchRef,viewerPermission` は権限と空かどうかを 1 回で返し、無いリポジトリでは `Could not resolve to a Repository` で終了コード 1 になる(gh 2.103.2 で実行) | 実測 | 権限の判定に追加の API の組み合わせが要らないこと | -| `git pull` は `lib/devbase/plugin/repo_manager.py` の `_git_pull` で `--ff-only` を付けずに実行される | 実測(コードの読み取り) | 取り込みの前に早送りの確認が別に要ること | -| `add_repository` は `registry.yml` が無いと登録せず clone を消す(`repo_manager.py`) | 実測(コードの読み取り) | 登録より先に `registry.yml` を入れる順序が要ること | - -要求と受け入れ条件は #514 の本文にある(コピーは `issues/issue-514-requirements.md`)。この文書は「どう作るか」だけを扱う。 - -## ドメインモデル - -### コンテキスト - -| コンテキスト | 何の語が 1 つの意味に決まるか | -| --- | --- | -| プラグインの配布 | プラグインリポジトリ・プラグイン・プロジェクト・登録・導入・作成フロー | -| 機密の置き場(`secret`) | アカウントグループとその宣言 | -| コマンドの入口(`cli`) | 名前の形 | - -変更はプラグインの配布の中で閉じ、ほかの 2 つのモデルを変えない。コンテキストマップの関係は**順応者**である。プラグインの配布が下流になり、グループの規則(`validate_account_group`)と名前の形(`names.is_single_segment_name`)をそのまま受け入れて、独自の規則を持たない。 - -### 集約 - -| 集約 | 持ち主(書き換えてよいもの) | 根 | エンティティ | 値オブジェクト | -| --- | --- | --- | --- | --- | -| プラグインリポジトリ(GitHub の既定ブランチ) | 中身は `publish` が PR のマージと、空のリポジトリの最初のコミットで書く。リポジトリの作成は `creator` が `GhClient.create_repo` を呼んで行う | リポジトリ | プラグイン・プロジェクト | `GitHubRef`・`registry.yml` の項目 | -| 手元の登録(`plugins.yml`) | 既存の `PluginRegistry`(`add_repository`・`install_plugin`・`refresh_repository` 経由だけ) | `plugins.yml` | 登録済みリポジトリ・導入済みプラグイン | — | -| 手元の clone(`repos/` の clone と `projects/` への反映) | `_pull_ff_only`(取り込み)と、既存の `add_repository`(clone)・`install_plugin`・`refresh_repository`(`projects/` への反映) | `repos/` の clone | 作業ツリー | — | - -`creator` と `publish` は手元の `repos/` の clone へファイルを置かない。手元が変わるのは、既定ブランチへの反映の後に上の持ち主を呼ぶときだけである。 - -### 不変条件 - -| # | 集約 | 条件 | 破れたときの扱い | -| --- | --- | --- | --- | -| I1 | 全体 | 計画の確定(解決と確認)が終わるまで、GitHub にも手元にも書かない | 実装の誤り。テストで止める | -| I2 | 手元の登録 | 作成フローが既定ブランチへ入れる変更がすべて反映される(最初のコミットの push かマージが成功する)まで `plugins.yml` を変えない。入れる変更が無い経路は、確認の後にそのまま登録する | 同上 | -| I3 | プラグインリポジトリ | `registry.yml` の編集の前後で既存の項目が同じで、増えるのは 1 項目だけである | 検証で不一致なら push せず止める | -| I4 | 手元の clone | 未コミットの変更を失わない | 取り込みが変更とぶつかれば止める | -| I5 | プラグインリポジトリ | リポジトリの公開は `--public` のときだけである | テストで止める | -| I6 | 全体 | 作成フローはコンテナを起動しない(`AGENTS.md` の P3: 利用者の環境の `devbase up` は人の承認が要る) | テストで止める | -| I7 | プラグインリポジトリ | 既定ブランチへの直接の push は、空のリポジトリの最初のコミットだけである | テストで止める | -| I8 | 手元の clone | 手元の clone の取り込みは早送りだけである | 早送りできなければ止める | -| I9 | 全体 | グループ(`--group`・最多の値・TTY で聞いた値)は `validate_account_group` を、プラグインとプロジェクトの名前は `names.is_single_segment_name` を、プロジェクトの名前はさらに Compose のプロジェクト名の規則を通してから計画へ入れる(既定のリポジトリ名は規則の形へ整える) | 通らなければ何も変えず、理由を出して終了コード 1 で止める | - -### ドメインイベント - -| # | イベント | 発生元 | 受け手 | -| --- | --- | --- | --- | -| E1 | 引数を GitHub の owner/repo へ解決した | `GitHubRef.parse` | 各フロー | -| E2 | `gh` の認証と権限を確かめた | `GhClient` | 各フロー | -| E3 | 入れ先のプラグインとグループを決めた | `plan_project` | 計画 | -| E4 | 実行の計画を示して確認を得た | CLI・TUI | `execute` | -| E5 | リポジトリを作った | `GhClient.create_repo` | `publish` | -| E6 | 手元の clone と別の作業場所でブランチを作り、ファイルを置いて push した | `publish` | `GhClient` | -| E7 | PR を作ってマージした | `GhClient` | 取り込み | -| E8 | 手元の clone へ取り込んだ | `_pull_ff_only` | 登録 | -| E9 | `plugins.yml` へ登録し、`projects/` へ反映した | 既存の `add_repository`・`install_plugin`・`refresh_repository` | 利用者 | - -E5〜E9 の通り方は、コマンドとリポジトリの状態の組で変わる(「経路ごとの反映と登録」)。未登録のリポジトリには手元の clone が無いので E8 を通らず、E9 の `add_repository` が clone する。 - -| コマンド | リポジトリ | 通るイベント(E4 の後) | -| --- | --- | --- | -| `plugin repo new` | 無い | E5 → E6(最初のコミット)→ E9 | -| `plugin repo new` | 空 | E6(最初のコミット)→ E9 | -| `plugin repo new` | `registry.yml` が無い | E6 → E7 → E9 | -| `plugin repo new` | `registry.yml` がある・未登録 | E9 | -| `plugin new` | 登録済み | E6 → E7 → E8 → E9 | -| `plugin new` | 無い | E5 → E6(最初のコミット)→ E6 → E7 → E9 | -| `plugin new` | 空 | E6(最初のコミット)→ E6 → E7 → E9 | -| `plugin new` | `registry.yml` が無い | E6 → E7 → E6 → E7 → E9 | -| `plugin new` | `registry.yml` がある・未登録 | E6 → E7 → E9 | -| `project new` | 入れ先のプラグインのリポジトリ(登録済み) | E6 → E7 → E8 → E9 | - -push できる登録済みのリポジトリへの `plugin repo new` は E4 の前に 0 で終わり、どのイベントも通らない。push できないときは登録済みでも E4 の前に終了コード 1 で止まる。 - -`plugin new`・`project new` は、登録の `local_path` が空か clone のディレクトリが無いとき、E4 の前に終了コード 1 で止まり、どのイベントも通らない(「経路ごとの反映と登録」)。 - -### 用語 - -| 用語 | 意味 | 用語集への反映 | -| --- | --- | --- | -| プラグインリポジトリ | 直下に `registry.yml` を持つ Git リポジトリ。収めたプラグインは 0 件でもよい | 追加 | -| 作成フロー | リポジトリ・プラグイン・プロジェクトを足す一連の操作。権限の確認からマージ、手元への取り込み、登録までを含む | 追加 | -| 作成の計画 | 作成フローが書き込みの前に確定する、作るもの・ファイル・マージ先の組 | 追加 | - -## 外部の調査 - -| 種類 | 調べるか | 理由 | -| --- | --- | --- | -| 標準・仕様 | 調べない | 触るのは GitHub の操作とこのリポジトリ固有の `registry.yml`・`plugin.yml` で、業界の標準の形が無い。GitHub の操作の形は下の 2 種類で見る | -| 主要な製品 | 調べる | 雛形を作るコマンドの入口と作るものの範囲を比べる | -| ライブラリとサービス | 調べる | 雛形の生成・YAML の書き戻し・GitHub の操作を、依存を足して得るか自前で書くかを決める | - -### 主要な製品 - -| # | 製品 | どう解いているか | 設計への反映 | 出典 | -| --- | --- | --- | --- | --- | -| PRD1 | `gh extension create` | 名前を引数に雛形を作る | 動詞で雛形を作る形を踏む | https://cli.github.com/manual/gh_extension_create (2026-11-06) | -| PRD2 | `helm create` | 既定の雛形を組み込みで持ち、`--starter` で差し替える | 組み込みの雛形を持つ形を採る。差し替えは #514 の要求に無いので持たない | https://helm.sh/docs/helm/helm_create/ (2026-11-06) | -| PRD3 | `cargo new` | パッケージの雛形を作り、手元の Git リポジトリも初期化する | 手元の初期化までの形と比べると、PR・マージまで行うのは #514 の固有の要求である | https://doc.rust-lang.org/cargo/commands/cargo-new.html (2026-11-06) | - -### ライブラリとサービス - -| # | 候補 | 版 | ライセンス | 最後のリリースの日付 | 終了のアナウンス | 要件を満たすか | 出典 | -| --- | --- | --- | --- | --- | --- | --- | --- | -| LIB1 | ruamel.yaml | 0.19.1 | MIT | 2026-01-02 | 無し | コメントを保って書き戻せるが、新しい依存になる。`registry.yml` の操作は 1 項目の追記だけ | https://pypi.org/pypi/ruamel.yaml/json (2026-11-06) | -| LIB2 | PyYAML(依存済み) | `pyyaml>=6.0` | 確かめなかった | 確かめなかった | 確かめなかった | 読み直しの検証に使う。書き戻しはコメントを失う | `pyproject.toml`(2026-11-06) | -| LIB3 | Copier | 9.19.1 | MIT | 2026-10-13 | 無し | 満たすが、雛形は小さな 3 種類で、テンプレートのリポジトリと新しい依存が割に合わない | https://pypi.org/pypi/copier/json (2026-11-06) | -| LIB4 | Cookiecutter | 2.7.1 | 確かめられなかった | 2026-03-04 | 無し | LIB3 と同じ | https://pypi.org/pypi/cookiecutter/json (2026-11-06) | -| LIB5 | PyGithub | 2.10.0 | LGPL | 2026-08-20 | 無し | 満たすが、トークンをアプリが扱うことになり、`gh` の認証に任せる方針(セキュリティ)と合わない | https://pypi.org/pypi/PyGithub/json (2026-11-06) | -| LIB6 | GitHub CLI(`gh`) | 2.103.2 | 確かめなかった | 2026-10-23 | 確かめなかった | 満たす。認証を利用者の設定に任せられ、`repo create` の `--private`・`pr merge` の方式の指定が揃う | `gh --version`、https://cli.github.com/manual/gh_pr_merge (2026-11-06) | - -### 確かめられなかったこと - -| 対象 | 理由 | -| --- | --- | -| LIB4 のライセンス | PyPI の JSON の `license`・`classifiers` が空だった | -| LIB1・LIB3・LIB4・LIB5 の終了のアナウンス | 表の「無し」は PyPI の版の情報に見当たらなかったという意味で、各リポジトリのアーカイブの状態までは見ていない | -| LIB2・LIB6 のライセンスなど | どちらも既存の依存か既存の前提で、今回は採否が変わらないため取得していない | - -調べた量: 候補 9 件・取得の試み 11 回。 - -## 機能一覧 - -| # | 機能 | 誰が使うか | -| --- | --- | --- | -| 1 | `devbase plugin repo new [--public] [--yes]` | プラグインの保守者 | -| 2 | `devbase plugin new [--name] [--public] [--yes]` | プラグインの保守者 | -| 3 | `devbase project new [--plugin] [--group] [--name] [--yes]` | 開発者 | -| 4 | `devbase list` のプラグインのメニューの組み直しと、1〜3 の入口 | TUI の利用者 | - -## 構成要素 - -| 要素 | 責務 | -| --- | --- | -| `lib/devbase/plugin/github.py`(新規) | `GitHubRef`(引数の解決)と `GhClient`(`gh` の呼び出し。権限・作成・PR・マージ)。トークンを扱わない | -| `lib/devbase/plugin/scaffold.py`(新規) | テンプレートの文字列の生成と `registry.yml` への 1 項目の追記。外部へ出ない純粋な処理 | -| `lib/devbase/plugin/publish.py`(新規) | 一時の clone で変更を作り、空のリポジトリなら最初のコミットを push し、それ以外は push・PR・マージするまで(E6・E7) | -| `lib/devbase/plugin/creator.py`(新規) | 3 つのフローの `plan_*`(読むだけ)と `execute`(書く)。入れ先とグループの決定 | -| `lib/devbase/commands/plugin.py` | `plugin new`・`plugin repo new` の入口 | -| `lib/devbase/commands/project.py` | `project new` の入口 | -| `lib/devbase/cli.py` | パーサ、`SUBCMD_MAP`、`repo_subcmds`、`project` の分岐、`_NO_SECRET_INJECTION` への `('project', 'new')` の追加 | -| `etc/_devbase`・`etc/devbase-completion.bash` | シェル補完 | -| `lib/devbase/tui/actions_plugin.py` | メニューの組み直しと 3 つの入口 | -| `lib/devbase/plugin/repo_manager.py` | `_pull_ff_only` と `_find_registered`(URL の形によらず登録を探す)を足す。既存の関数は変えない | - -`bin/devbase` は変えない。`_PROJECT_NAME_SUBCOMMANDS` に `new` を足さないので、`project new owner/repo` は name 解決を通らない。 - -`SUBCMD_MAP` へ値を足すので、既存の規則を 1 つずつ見た。`tests/cli/test_prefix_resolution.py` の網羅の検査と補完の一致テストは新しい値にも当たるので、値を足す側で満たす。`new` は既存の `project`・`plugin` の副命令と接頭辞が重ならないため、`SUBCMD_PREFIX_PREFERENCES` は変えない。 - -```mermaid -graph TD - CLI[commands/plugin・project] --> C[creator] - TUI[tui/actions_plugin] --> CLI - TUI -->|候補とグループの案| C - C --> S[scaffold] - C --> P[publish] - C --> G[github] - P --> G - P --> S - C --> R[既存: repo_manager・installer] - R --> Reg[plugins.yml] -``` - -## 入出力の契約 - -### コマンド - -| コマンド | 引数 | 終了コード | -| --- | --- | --- | -| `devbase plugin repo new ` | `--public`(既定 private)、`--yes` | 0 成功・push できる登録済み / 1 それ以外 | -| `devbase plugin new ` | `--name`(既定はリポジトリ名)、`--public`、`--yes` | 0 成功 / 1 それ以外 | -| `devbase project new ` | `--plugin`、`--group`、`--name`(既定はリポジトリ名)、`--yes` | 0 成功 / 1 それ以外 | - -`` は `owner/repo`・`https://github.com/owner/repo[.git]`・`git@github.com:owner/repo[.git]` を受ける。`git@` の形の入力は clone の URL も `git@` のままにし、ほかは `https://github.com/owner/repo.git` にする。 - -### 引数の解決と分岐(リポジトリ) - -| リポジトリ | push | `registry.yml` | 動作 | -| --- | --- | --- | --- | -| 無い | owner に作れる | — | 作る → 最初のコミットを直接 push → 登録 | -| 無い | owner に作れない | — | 終了(1) | -| 空 | できる | — | 最初のコミットを直接 push → 登録 | -| ある | できる | 無い | PR → マージ → 登録 | -| ある | できる | ある | 登録だけ | -| ある | できる | ある(登録済み) | 何もせず 0 | -| ある・空 | できない | — | 終了(1)。登録済みでも同じ | - -- push できるのは `viewerPermission` が `ADMIN`・`MAINTAIN`・`WRITE` のとき -- owner に作れるのは次のどちらかのとき: - - owner が `gh api user` の `login` と同じである - - `gh api user/memberships/orgs/` の `state` が `active` で、`role` が `admin` か、組織の `members_can_create_repositories` が偽でない - - `members_can_create_repositories` は組織の owner にしか返らない。値が無いときは判定できないので計画へ進め、作れなければ `gh repo create` の出力を示して終了する(書き込みは起きない) -- 読めない private のリポジトリは「無い」と同じに見える。`gh repo create` が失敗するので、その出力を示して終了する - -### 経路ごとの反映と登録 - -`plugin new` は未登録のリポジトリでも受け入れ条件 17 を守るため、プラグインの PR のマージまで登録しない。 - -登録済みか未登録かは、計画の確定の前に `_find_registered` で決める。これは入力の URL と `plugins.yml` の全登録の `repo.url` を `_url_to_repos_dirname` の一致で比べ、見つけた登録を返す読むだけの関数である。`get_repository_by_url` の完全一致では、`git@` の形や `.git` の無い URL で登録したリポジトリが未登録に見え、プラグインの PR をマージした後に `add_repository` が登録済みとして拒否する。 - -見つけた登録は計画に持ち、登録済みの経路の呼び出しには入力の URL ではなく登録の値を渡す。`install_plugin` の内部も `get_repository_by_url` の完全一致で登録を探すためである。 - -| 呼び出し | 渡す値 | -| --- | --- | -| `_pull_ff_only` | 登録の `repo.local_path` の clone | -| `refresh_repository` | 登録の `repo.name` | -| `install_plugin` | `:<プラグイン名>`(登録の `repo.url`) | -| 一時の clone と push | 登録の `repo.url`(SSH の認証だけの利用者が https で止まらない) | - -`plugin new` と `project new` は、計画の確定の前に、登録の clone を確かめる。対象は `plugin new` では `_find_registered` が見つけた登録、`project new` では入れ先のプラグインの登録である。 - -| 登録の状態 | 動作 | -| --- | --- | -| `repo.local_path` が空(v3.0.0 より前の登録) | GitHub にも手元にも書かず、終了コード 1 で止まる | -| `devbase_root / repo.local_path` のディレクトリが無い | 同上 | -| どちらでもない | 下の表の経路へ進む | - -- **空のまま進めない理由**: `devbase_root / ""` は devbase 本体を指す。`_pull_ff_only` が本体の clone を取り込むか、続く `refresh_repository` の拒否で既定ブランチへのマージの後に止まる -- **案内**: `devbase plugin repo remove ` の後に `devbase plugin repo add ` を打つ。`repo remove` はそのリポジトリから導入したプラグインもアンインストールするので、`devbase plugin install` を打ち直すことも案内に書く -- **`plugin repo new` は確かめない**: 登録済みの経路は clone に触らないので、`local_path` が空でも push できれば何もせず 0 で終わる - -`project new` は、計画の確定の前に、入れ先のプラグインの登録の `path` を既定ブランチの `registry.yml` と比べる。項目が無いか違うときは、GitHub にも手元にも書かず終了コード 1 で止まり、`devbase plugin repo refresh ` を案内する。古い `path` へマージすると、続く取り込みが新しい `path` を登録し、足したプロジェクトが `projects/` に現れないまま 0 で終わるためである。 - -入れ先のパスは、導入済みの `plugin.path` の `repo.local_path` からの相対で決める。`registry.yml` の項目に `path` が無いプラグインは、導入と同じくリポジトリの直下として扱い、書き込み先は `projects/<名前>` になる。 - -`plugin new` と `project new` は、計画の確定の前に、登録の clone が GitHub の既定ブランチにいて、`origin` の同じブランチを追っていることを確かめる。違うときは、GitHub にも手元にも書かず終了コード 1 で止まり、切り替えのコマンドを案内する。clone の `origin/HEAD` は既定ブランチを変えても追従せず、古いブランチが残っていると取り込みが成功して、足したものが手元に現れないまま 0 で終わるためである。 - -一時の clone へ書くパスは、symlink と `..` を解決して clone の中に収まることを確かめ、外を指すものがあれば 1 ファイルも書かずに止まる。clone の中身は他人が書いたもので、書き込みが利用者の手元のファイルへ届かないようにする。 - -登録済みの経路の `_pull_ff_only` の前に、導入済みのプラグインのプロジェクト一覧を控え、`refresh_repository` へ渡す。取り込みにプラグインの改名や移動が入っていても、移行先を見つけられる。 - -| コマンド | リポジトリ | 既定ブランチへの反映 | 登録と反映(反映の後に行う) | -| --- | --- | --- | --- | -| `plugin repo new` | 無い・空 | 最初のコミットの直接の push | `add_repository` | -| `plugin repo new` | `registry.yml` が無い | PR のマージ | `add_repository` | -| `plugin repo new` | `registry.yml` がある・未登録 | 無し | `add_repository` | -| `plugin new` | 登録済み | プラグインの PR のマージ | `_pull_ff_only` → `refresh_repository` → `install_plugin` | -| `plugin new` | 未登録 | 上の 3 行のどれかの反映に続けて、プラグインの PR のマージ | `add_repository` → `install_plugin` | -| `project new` | 入れ先のプラグインのリポジトリ(登録済み) | プロジェクトの PR のマージ | `_pull_ff_only` → `refresh_repository` | - -### 入れ先のプラグインの決定(プロジェクト) - -1. `--plugin` があればそれを使う(導入済みで push できることは確かめる) -2. 導入済みで、登録済みリポジトリの `plugins` に項目があり、そのリポジトリへ push できるものを候補にする。リポジトリごとに `gh` を 1 回呼ぶ -3. 対象と同じ owner の候補があれば、それに絞る -4. 1 件ならそれを計画に示す。複数なら TTY で選ばせ、TTY が無ければ候補を出して 1 で終わる。0 件なら 1 で終わる - -### テンプレート - -リポジトリの `registry.yml` は `name: <リポジトリ名>`・`description: ""`・`plugins: []` である。`plugins` が空でも `add_repository` は登録する。 - -プラグインは `<名前>/plugin.yml`(`name`・`version: "1.0.0"`・`description`・`requires.devbase: ">=3.0.0"`・`projects.mode: auto`・`priority: 50`)と `<名前>/projects/.gitkeep`。 - -プロジェクトは `<プラグインの path>/projects/<名前>/` に次の 3 つを置く。 - -| ファイル | 中身 | -| --- | --- | -| `project.yml` | `version: 1`・`scale: 1`・`open_editor: true`・`repos`(`owner`・`repo`) | -| `compose.yml` | `containers/general` の `dev` 1 台。イメージ名は `<名前>:latest`。プロジェクトの名前は Docker の参照より広いので、末尾の区切り文字を落とし、2 つの英数字の間に置けない区切り文字の並びを `-` にする(`app-` は `app:latest`、`app_-web` は `app-web:latest`) | -| `env` | `DEVBASE_ACCOUNT_GROUP=<グループ>` | - -プロジェクトの名前は、名前の形に加えて Compose のプロジェクト名の規則(`[a-z0-9][a-z0-9_-]*`)に合わせる。`devbase up` が名前をそのまま `COMPOSE_PROJECT_NAME` へ渡すので、合わない名前は作成が 0 で終わっても起動で止まるためである。既定のリポジトリ名は小文字にし、使えない文字の並びを `-` に置き換える(`MyApp` は `myapp`、`foo.github.io` は `foo-github-io`)。`--name` で渡された合わない名前は、計画の確定の前に終了コード 1 で止める。 - -作業ブランチは `devbase/new--<名前>`、PR の題は `devbase: <名前> を足す`。名前の形は git のブランチ名より広いので、`..` を含むか `.`・`.lock` で終わる名前は、ブランチの `<名前>` の `.` を `-` に置き換えて元の名前の SHA-256 の先頭 8 文字を足す(`app..web` は `app--web-<8 文字>`)。違う名前が同じブランチにならず、同じ名前は打ち直しても同じブランチになる。 - -### 画面(`devbase list` のプラグインのメニュー) - -第 1 階層を用途で分け、各項目はサブメニューへ入る。先頭を「見る」にして、Enter を続けて押しても安全な一覧へ届くようにする。 - -| 第 1 階層 | 第 2 階層 | -| --- | --- | -| 見る | 導入済み一覧・利用可能一覧・詳細・リポジトリ一覧 | -| 新規追加 | プロジェクト・プラグイン・リポジトリ | -| 導入・更新 | インストール・更新・リポジトリ登録・リポジトリ更新 | -| 削除 | アンインストール・リポジトリ削除 | -| 保守 | リンクの再同期・レガシー構成の移行 | - -新規追加の入力の順は次のとおりである。入力ごとに Esc で 1 つ前のメニューへ戻り、Ctrl-C で全体を中止する(既存の規約)。 - -| 項目 | 順 | -| --- | --- | -| プロジェクト | リポジトリ → 名前(空で既定)→ 入れ先の選択(候補が 1 件なら選択を出さない)→ グループ(案を既定値に)→ 計画の確認 | -| プラグイン | リポジトリ → 名前(空で既定)→ 計画の確認 | -| リポジトリ | リポジトリ → 公開するかの確認(既定 いいえ)→ 計画の確認 | - -TUI は確認を終えた値を `--yes` 相当で `cmd_plugin`・`cmd_project_new` へ渡す。ロジックは二重に持たない。 - -## 処理の流れ - -```mermaid -sequenceDiagram - participant U as 利用者 - participant C as creator - participant G as gh - participant T as 一時の clone - participant L as 手元 - U->>C: コマンド - C->>G: 認証と権限(読むだけ) - C->>L: 登録の照合と clone の確認(読むだけ) - C->>U: 作成の計画と確認 - U-->>C: 承認 - opt リポジトリが無い - C->>G: repo create - end - alt 空のリポジトリ - C->>T: 浅い clone → registry.yml → commit → 既定ブランチへ push - else registry.yml が無い - C->>T: 浅い clone → ブランチ → registry.yml → commit → push - C->>G: PR 作成 → マージ - else registry.yml がある - Note over C,T: リポジトリの分岐では GitHub へ書かない - end - opt plugin new・project new - C->>T: 浅い clone → ブランチ → プラグインかプロジェクトのファイル → commit → push - C->>G: PR 作成 → マージ - end - opt 登録済みのリポジトリ - C->>L: 早送りの取り込み - end - C->>L: 登録・反映 -``` - -リポジトリの分岐の反映とプラグインの追加は別の浅い clone で順に行う(決定 8)。`plugin repo new` は権限の確認と登録の照合で登録済みだと分かると確認へ進まず、push できれば 0、できなければ 1 で終わる。 - -### 途中で止まったとき - -| 止まった所 | 残るもの | 出す案内 | -| --- | --- | --- | -| 解決・確認 | 何も残らない | 理由 | -| push | リポジトリを作った後なら、そのリポジトリ | 同じコマンドの再実行 | -| 同じブランチが既にある | 既存のブランチと PR | 開いている PR の URL | -| マージ | PR とブランチ | PR の URL。マージの後に打つコマンド(`plugin repo add`・`plugin repo refresh`・`plugin install`) | -| `plugin new` の `registry.yml` の PR | PR とブランチ。プラグインの PR はまだ無い。`plugins.yml` は元のまま | PR の URL。この PR をマージした後に同じ `plugin new` を打ち直す案内 | -| 未登録のリポジトリへの `plugin new` のプラグインの PR | 先に反映した最初のコミットか `registry.yml` は既定ブランチに残る。`plugins.yml` は元のまま | PR の URL。マージの後に打つコマンド(`plugin repo add`・`plugin install`) | -| 取り込み | マージ済み。手元は元のまま | 原因と `git -C status`、続けて打つコマンド | -| 登録 | マージと取り込み済み | 既存のコマンドのエラーと、続けて打つコマンド | - -## 非機能の実現方式 - -| 大項目 | 実現方式 | -| --- | --- | -| 運用・保守性 | 上の表の案内を `RepositoryError` の本文に載せる。進んだ段階を `logger.info` で 1 行ずつ出す | -| セキュリティ | 認証は `gh`・`git` の既存の設定に任せ、トークンを引数へ渡さない。`gh` の標準エラーはそのままエラーへ載せる(`gh` はトークンを出さない)| -| システム環境 | Linux・macOS。外部コマンドは `gh`・`git`。`gh` の版は確かめない(`gh` 2.103.2 で確かめた。古くて失敗したときは、その出力で止まる)| - -## 決定の記録 - -### 決定 1: 手元の未コミットの変更を守るため、作業は一時の浅い clone で行う - -`repos/` の clone の worktree や作業ツリーを使わず、`tempfile.TemporaryDirectory` に `git clone --depth 1` して作業する。未登録のリポジトリには手元の clone が無く、登録済みの clone には利用者の変更がある。一時の clone なら 2 つの場合を同じ手順で扱える。 - -採らなかった案: 手元の clone に `git worktree add` する。未登録の場合を別の経路で書く必要があり、`.git/worktrees` に管理情報が残る恐れがある。 - -根拠: Value 3(MVV 版 1) - -### 決定 2: 登録済みの経路を二重に書かないため、取り込みと登録は既存の関数に任せる - -既定ブランチへの反映の後は `add_repository`・`install_plugin`・`refresh_repository` を呼ぶ。`refresh_repository` の `git pull` は早送りを保証しないので、前に `_pull_ff_only` を置き、既定ブランチでない clone や分岐した clone は止める。 - -採らなかった案: `_git_pull` に `--ff-only` を足す。既存の `plugin repo refresh` の振る舞いが変わる。 - -根拠: 根拠なし(MVV 版 1) - -### 決定 3: 公開範囲を黙って広げないため、新しいリポジトリは private を既定にする - -`--public` のときだけ公開する。`--public` は作成するときだけ効き、既存のリポジトリの公開範囲は変えない。 - -根拠: Value 3(MVV 版 1) - -### 決定 4: 必須の検査やレビューを越えないため、マージは 1 回だけ試し、CI を待たない - -`gh pr view --json mergeable` が `UNKNOWN` の間は最長 30 秒待ち、判定が出てから `gh pr merge` を 1 回実行する。失敗したら PR の URL を出して止まる。`--auto` と管理者の権限による `--admin` は使わない。マージの方式は、リポジトリが許す順に merge・squash・rebase から選ぶ。 - -採らなかった案: CI を待つ。プラグインリポジトリの多くは CI を持たず、待つ処理と時間切れの扱いを足す費用に見合わない。 - -根拠: 根拠なし(MVV 版 1) - -### 決定 5: 入力の差を CLI と TUI で分けないため、TUI は値を集めて CLI のハンドラへ渡す - -TUI は `creator` の読むだけの関数(候補とグループの案)を呼び、集めた値を `yes=True` でハンドラへ渡す。既存の `actions_plugin` と同じ委譲の形である。 - -根拠: 根拠なし(MVV 版 1) - -### 決定 6: 既存のレジストリの書式を壊さないため、`registry.yml` は YAML を書き戻さず文字列で追記する - -`plugins:` のブロックの末尾に 3 行を足す。`plugins: []` はブロックへ置き換える。追記の後に読み直し、既存の項目が同じで 1 項目だけ増えたことを確かめ、違えば止める(I3)。 - -採らなかった案: `yaml.safe_dump` で書き戻す。コメントと引用符の形が失われ、差分が読めなくなる。 - -採らなかった案: ruamel.yaml で書き戻す。1 項目の追記のために新しい依存を足すことになる。 - -- 作り方: 自前で作る -- 比べた候補: LIB1 / LIB2 - -根拠: 根拠なし(MVV 版 1) - -### 決定 7: 人が書いた説明を崩さないため、プラグインの説明文へプロジェクト名を足さない - -`plugin.yml` と `registry.yml` の `description` は人が書いた文で、機械で足すと読めない文になる。#514 の「含まない」のとおりである。 - -根拠: 根拠なし(MVV 版 1) - -### 決定 8: マージできないときに手元の登録を残さないため、登録は作成フローの最後の反映の後に回す - -未登録のリポジトリへの `plugin new` は、リポジトリの分岐の反映に続けてプラグインの PR をマージし、そのマージが成功してから `add_repository` と `install_plugin` を呼ぶ。リポジトリの分岐の反映とプラグインの追加は順に別の変更として行い、1 つの PR にまとめない。 - -採らなかった案: リポジトリの分岐を終えた時点で登録する。プラグインの PR のマージが失敗すると `plugins.yml` が変わったまま残り、受け入れ条件 17 を破る。 - -根拠: 根拠なし(MVV 版 1) - -### 決定 9: URL の形の違いでマージの後に止まらないため、登録の照合は `_url_to_repos_dirname` の一致で行う - -`repo_manager.py` に `_find_registered` を足し、計画の確定の前に登録を探す。見つけた登録の `repo.url`・`repo.name`・`repo.local_path` を後の呼び出しへ渡す(「経路ごとの反映と登録」)。比べ方は既存の `_reject_duplicate_registration` と同じで、`add_repository` が拒否するものを計画の段階で登録済みの経路へ入れる。 - -採らなかった案: `get_repository_by_url` を URL の形の違いを吸収するよう変える。`install_plugin` などの既存の経路の振る舞いが変わる。 - -採らなかった案: `add_repository` の拒否を受けてから登録済みとして続ける。既定ブランチへのマージの後に経路が変わり、計画で示した手順と違う動きになる。 - -根拠: 根拠なし(MVV 版 1) - -### 決定 10: 依存を増やさないため、雛形は `scaffold.py` の文字列で生成する - -雛形はプラグイン・プロジェクト・`registry.yml` の小さな 3 種類で、差し替えの要求が無い。`helm create` の組み込みの雛形と同じく、コードの中に持つ。 - -採らなかった案: Copier か Cookiecutter を使う。テンプレートの置き場と新しい依存が増え、小さな雛形に見合わない。 - -- 作り方: 自前で作る -- 比べた候補: LIB3 / LIB4 / PRD2 - -根拠: 根拠なし(MVV 版 1) - -### 決定 11: トークンをアプリで扱わないため、GitHub の操作は `gh` に任せる - -権限の確認・リポジトリの作成・PR・マージを `gh` の呼び出しで行う。認証は利用者の `gh` の設定に任せる。操作先のホストだけは `GH_HOST=github.com` で固定する。`GitHubRef` が受けるのも `git` が操作するのも github.com だけで、`GH_HOST` が別のホストを指すと確認やリポジトリの作成が `git` と別のホストへ向かうためである。機密の `GH_TOKEN` が環境変数に載ると `gh` がそのトークンで動くので、3 つのコマンドは機密を注入せず、TUI は `gh` を呼ぶ前に注入を取り除く。 - -採らなかった案: PyGithub を使う。トークンをアプリが受け取ることになる。 - -- 作り方: ライブラリやサービスを使う -- 比べた候補: LIB5 / LIB6 - -根拠: 根拠なし(MVV 版 1) - -## テスト設計 - -| 受け入れ条件・不変条件 | どの振る舞いで縛るか | どう壊したら落ちるべきか | -| --- | --- | --- | -| 1・2・3・4、I5、I7 | 分岐の表と経路の表の全行を、偽の `gh` と手元の bare リポジトリで実行し、作ったもの・PR・`plugins.yml` を見る。`plugins` が空の `registry.yml` も登録できる | 既定を公開にする・PR を飛ばす・権限なしで作る・プラグイン 0 件の登録を拒む | -| 5 | `GitHubRef.parse` が 4 つの形で同じ owner/repo を返し、GitHub 以外を拒む | `.git` を外さない・別ホストを通す | -| 6・7・8、I9 | プラグインのフローで `plugin.yml`・`registry.yml`・導入の状態を見る。未登録・重複名・形の誤りを含む | 登録の省略・重複の上書き・名前の形を見ない | -| 6・7、決定 8 | 未登録のリポジトリへの `plugin new` を、無い・空・`registry.yml` が無い・ある の 4 状態で実行し、既定ブランチへの反映の順(リポジトリの分岐 → プラグインの PR → 登録)を見る | プラグインを最初のコミットや `registry.yml` の PR へまとめる・プラグインの PR の前に登録する | -| 6・7、決定 9 | `git@` の形と `.git` の無い URL で登録したリポジトリへ、形の違う入力で `plugin new` を打つ。登録済みの経路を通って 0 で終わり、`plugins.yml` の `url` が変わらず、プラグインが導入される。同じ入力の `plugin repo new` は何もせず 0 で終わる。push できない登録へは、同じ入力の `plugin repo new` が何も書かず 1 で終わる | 完全一致で照合する・入力の URL を `install_plugin` へ渡す・push の可否を見ずに登録済みなら 0 で終わる | -| 6・9、I1 | `local_path` が空の登録と clone のディレクトリが無い登録へ、`plugin new` と `project new` を打つ。どちらも確認の前に終了コード 1 で止まり、GitHub への書き込みの呼び出しが 0 回で、`plugins.yml` と devbase 本体の作業ツリーが変わらず、案内に `plugin repo remove` と `plugin repo add` が出る。同じ登録へ `plugin repo new` を打つと、push できれば何もせず 0 で終わる | 空の `local_path` を `devbase_root` へ足して取り込む・確かめをマージの後へ回す | -| 9・12 | プロジェクトの 3 ファイルと `projects/<名前>` の反映を見る。読めないとき・重複のときは何も変わらない | ファイルの欠け・上書き | -| 10 | 決定の規則の 4 段を候補の表で縛る | owner の絞り込みの省略・TTY なしで選ぶ | -| 11、I9 | 最多の値・同数・値なし・`--group`。予約語など `validate_account_group` が弾く値は、どの出所でも何も書かず終了コード 1 になる | 同数で片方を選ぶ・グループの規則を通さず `env` へ書く | -| 13、I6 | 作成フローの全経路で `docker` と `compose` を呼ばない | 手順に `up` を足す | -| 14 | `gh` なし・未認証で、書き込みの呼び出しが 0 回 | 確認を後回しにする | -| 15、I1 | 確認の前は書き込みの呼び出しが 0 回。TTY なしで `--yes` なしは 1 | 確認を飛ばす | -| 16、I4、I8 | 手元に未コミットの変更がある clone で完走し、変更が残る。分岐した clone は止まる。GitHub の既定ブランチと違うブランチの clone は、書き込みの前に止まる | `creator`・`publish` が手元の作業ツリーへ書く・マージコミットを作る・`origin/HEAD` で既定ブランチを決める | -| 17、I2 | マージの失敗で `plugins.yml` が同じで、URL が出る。未登録のリポジトリへの `plugin new` でも同じである。成功のとき作業場所が残らない | 先に登録する | -| 18・19・20 | メニューの全項目が既存の操作へ届き、Esc と Ctrl-C の戻り値が既存どおりに伝わる | 項目の欠け・Esc の取り違え | -| 21 | 既存のテストが変わらず通る | 既存の属性を変える | -| 22 | `project new owner/repo` がプロジェクトの切替を通らない | `_PROJECT_NAME_SUBCOMMANDS` へ足す | -| I3 | コメント付きの `registry.yml` で追記し、既存の行が残る。壊れる追記は止まる | `safe_dump` で書き戻す | - -## 設計の結果 - -| 課題 | 扱い | 取り込み先 | 触るファイル | -| --- | --- | --- | --- | -| #514 | 実装する | — | `lib/devbase/plugin/`、`lib/devbase/commands/plugin.py`、`lib/devbase/commands/project.py`、`lib/devbase/cli.py`、`lib/devbase/tui/actions_plugin.py`、`etc/`、`tests/`、`docs/user/cli-reference/`、`CHANGELOG.md` | - -## 未確認のまま残ること - -| 項目 | 内容 | -| --- | --- | -| 実の GitHub での完走 | テストでは書かない。リリース後テストで利用者の作業用のアカウントで確かめる | -| 組織の設定 | 組織の規則で private の作成が禁じられているとき、`gh repo create` の失敗で止まる形になる。事前には判定しない | diff --git a/issues/issue-514-plan.md b/issues/issue-514-plan.md deleted file mode 100644 index e5b594f3..00000000 --- a/issues/issue-514-plan.md +++ /dev/null @@ -1,156 +0,0 @@ -# #514: リポジトリ・プラグイン・プロジェクトの新規追加コマンドと TUI の操作 - -## 関連リンク - -- 課題: #514(写しは `issues/issue-514-requirements.md`) -- 設計: `issues/issue-514-design.md`(決定 1〜11、不変条件 I1〜I9、「経路ごとの反映と登録」、「テスト設計」) - -## モード - -`standard`(設計の「当たるモード」のとおり。公開の CLI と TUI が増え、GitHub へ書く) - -## 目的と非目的 - -達成したい状態: - -- 引数 1 つのコマンドか `devbase list` の TUI で、権限の確認からマージ、手元の取り込みと登録までが終わる - -やらないこと: - -- `devbase up` の実行、`env` の値の登録、フックや `Dockerfile` の雛形の出し分け -- プラグインの `description` の書き足し、GitHub 以外のホスト、Organization の作成、`gh` の導入の代行 -- #516(大文字小文字の違う URL の二重登録) - -## 前提 - -- 前提 1: テストは実の GitHub に触らない。偽の `gh` と手元の bare リポジトリ(`url..insteadOf`)で通す -- 前提 2: 手元の `plugins.yml`・`repos/`・`projects/` の実物に触らない。テストは一時のルートで組む - -## 受け入れ条件 - -`issues/issue-514-requirements.md` の 1〜22 をそのまま使う。検証手段は「テスト設計」の表の行で、下の各タスクへ割り当てる。 - -## 代替案と採否 - -設計の決定 1〜11 のとおり。実装の計画で新たに選んだものは次の 2 つである。 - -| 案 | 内容 | 採否 | 理由 | -| --- | --- | --- | --- | -| A | 作成フローのテストは実の `git` と偽の `gh` の実行ファイルで通す | 採用 | `gh` と `git` の引数と順序を実物の push・マージの結果で縛れる | -| B | `subprocess.run` をモックする | 不採用 | 手元の作業ツリーへ書かないこと(I4)や push の順序を結果で確かめられない | -| C | 既定ブランチの `registry.yml` と既存のパスは `gh api` の contents で読む | 採用 | 計画の確定の前に手元へ何も作らない(I1)。手元の clone が古くても重複を見つけられる | -| D | 計画の段階で一時の clone を作って読む | 不採用 | 確認の前に時間のかかる clone が要る | - -## 不変条件 - -設計の I1〜I9 をそのまま使う。 - -## 互換性 - -| 対象 | 変更 | 互換性の扱い | -| --- | --- | --- | -| 公開インタフェース(コマンド) | `plugin repo new`・`plugin new`・`project new` | 追加のみ | -| TUI | プラグインのメニューの階層 | 変わる(受け入れ条件 19) | -| データスキーマ | `plugins.yml` | 変えない | - -## 修正対象 - -- 新規: `lib/devbase/plugin/{github,scaffold,publish,creator}.py` -- 変更: `lib/devbase/plugin/repo_manager.py`、`lib/devbase/commands/{plugin,project}.py`、`lib/devbase/cli.py`、`lib/devbase/tui/actions_plugin.py`、`etc/_devbase`、`etc/devbase-completion.bash` -- 文書: `docs/user/cli-reference/`、`docs/plugin-dev/`、`docs/glossary/glossary.json`、`docs/glossary.md`、`CHANGELOG.md` -- テスト: `tests/plugin/`(作成フロー)、`tests/cli/`(解決・補完)、`tests/cli/tui/test_actions_plugin.py` - -## タスク分解 - -### Task 1: 引数の解決と `gh` の呼び出し - -- **対象ファイル:** `lib/devbase/plugin/github.py`、`tests/plugin/test_github.py` -- **変更内容:** `GitHubRef.parse`、`GhClient`(認証・権限・作成の可否・読み取り・作成・PR・マージ) -- **満たす受け入れ条件:** 5、14 -- **進め方:** 失敗するテスト → 通す最小実装 → 整理 - -### Task 2: 雛形と `registry.yml` の追記 - -- **対象ファイル:** `lib/devbase/plugin/scaffold.py`、`tests/plugin/test_scaffold.py` -- **変更内容:** 3 種類の雛形の文字列、書式を保つ 1 項目の追記と読み直しの検証 -- **満たす受け入れ条件:** 6、9、I3 -- **進め方:** 失敗するテスト → 通す最小実装 → 整理 - -### Task 3: 登録の照合と早送りの取り込み - -- **対象ファイル:** `lib/devbase/plugin/repo_manager.py`、`tests/plugin/test_repo_manager_creation.py` -- **変更内容:** `_find_registered`・`_pull_ff_only` の追加。既存の関数は変えない -- **満たす受け入れ条件:** 16、I4、I8、決定 9 -- **進め方:** 失敗するテスト → 通す最小実装 → 整理 - -### Task 4: 一時の clone から既定ブランチへの反映 - -- **対象ファイル:** `lib/devbase/plugin/publish.py`、`tests/plugin/creation_harness.py`、`tests/plugin/conftest.py`、`tests/plugin/test_publish.py` -- **変更内容:** 最初のコミットの直接の push、ブランチ・PR・マージ。偽の `gh` と bare リポジトリの土台 -- **満たす受け入れ条件:** 1、2、16、17、I7 -- **進め方:** 失敗するテスト → 通す最小実装 → 整理 - -### Task 5: `devbase plugin repo new` - -- **対象ファイル:** `lib/devbase/plugin/creator.py`、`lib/devbase/commands/plugin.py`、`lib/devbase/cli.py`、`tests/plugin/test_create_repo.py` -- **変更内容:** `plan_repo`・`execute`・計画の確認と `--yes`、パーサと `SUBCMD_MAP`・`repo_subcmds` -- **満たす受け入れ条件:** 1〜5、14、15、17、I1、I2、I5、I7 -- **進め方:** 失敗するテスト → 通す最小実装 → 整理 - -### Task 6: `devbase plugin new` - -- **対象ファイル:** `lib/devbase/plugin/creator.py`、`lib/devbase/commands/plugin.py`、`lib/devbase/cli.py`、`tests/plugin/test_create_plugin.py` -- **変更内容:** `plan_plugin`、未登録の 4 状態、登録済みの経路、登録の clone の確かめ -- **満たす受け入れ条件:** 6、7、8、16、17、I2、I8、I9、決定 8、決定 9 -- **進め方:** 失敗するテスト → 通す最小実装 → 整理 - -### Task 7: `devbase project new` - -- **対象ファイル:** `lib/devbase/plugin/creator.py`、`lib/devbase/commands/project.py`、`lib/devbase/cli.py`、`tests/plugin/test_create_project.py`、`tests/cli/test_project_new_dispatch.py` -- **変更内容:** 入れ先の決定、グループの決定、`plan_project`、`_NO_SECRET_INJECTION` -- **満たす受け入れ条件:** 9〜13、22、I6、I9 -- **進め方:** 失敗するテスト → 通す最小実装 → 整理 - -### Task 8: シェル補完 - -- **対象ファイル:** `etc/_devbase`、`etc/devbase-completion.bash`、`tests/cli/test_completion.py` -- **変更内容:** 3 つのコマンドとオプションの候補 -- **満たす受け入れ条件:** 目的の「シェル補完」 -- **進め方:** 失敗するテスト → 通す最小実装 → 整理 - -### Task 9: TUI のメニューの組み直しと 3 つの入口 - -- **対象ファイル:** `lib/devbase/tui/actions_plugin.py`、`tests/cli/tui/test_actions_plugin.py` -- **変更内容:** 第 1 階層を用途で分け、新規追加の入力の順を設計のとおりに置く -- **満たす受け入れ条件:** 18、19、20 -- **進め方:** 失敗するテスト → 通す最小実装 → 整理 - -### Task 10: 文書 - -- **対象ファイル:** `docs/user/cli-reference/`、`docs/plugin-dev/`、`docs/glossary/glossary.json`、`docs/glossary.md`、`CHANGELOG.md` -- **変更内容:** コマンドのリファレンス、プラグインリポジトリの定義、用語集の出所、変更履歴 -- **満たす受け入れ条件:** 影響の「公開インタフェース」 -- **進め方:** テスト駆動を適用しない(文書だけ。`glossary.py check` と固有の語の検査で確かめる) - -## 影響範囲 - -- `devbase plugin`・`devbase plugin repo`・`devbase project` の接頭辞の解決と補完 -- `devbase list` のプラグインのメニュー - -## リスクと対処 - -| リスク | 対処 | -| --- | --- | -| `SUBCMD_MAP` と補完の一致テストに新しい値が当たる | タスクごとにテストを通す | -| `actions_plugin.py` のメニューの変更で既存のテストの前提が変わる | タスクごとにテストを通す。`_run_operation`・`_run_repo_operation` の契約は残す | -| `repo_manager.py` の既存の経路を壊す | 足すだけにして既存の関数を変えない | - -## 切り戻し手順 - -- 追加のコマンドは該当のコミットを revert すれば消える。`plugins.yml` の形は変わらないので、データの戻しは要らない - -## 完了の定義 - -- [ ] 受け入れ条件 1〜22 と I1〜I9 が「テスト設計」の行のテストに対応している -- [ ] `env -u DEVBASE_ROOT uv run --locked pytest tests/ -q`、`uvx ruff check --select=E9,F63,F7,F82 lib`、`python3 .github/scripts/proper_term_check.py` が通る -- [ ] 実の GitHub での完走は、リリース後テストで利用者が確かめる(テストからは書かない) diff --git a/issues/issue-514-requirements.md b/issues/issue-514-requirements.md deleted file mode 100644 index 1d69f9fe..00000000 --- a/issues/issue-514-requirements.md +++ /dev/null @@ -1,162 +0,0 @@ -# #514: リポジトリ・プラグイン・プロジェクトを新規に足すコマンドと TUI の操作を作る - -正は課題の本文(#514)で、この文書はその写しである。`spec-copy.py write` で作り直す。手で直さない。 - -## 依頼(原文) - -> devbaseにリポジトリ/プラグイン/projectの新規追加コマンドを作りましょう -> * いずれもgithub urlまたはowner/repos 名を引数とする -> * リポジトリはそのURLが存在し、権限があればリポジトリを作成、いずれも無ければ終了 -> * プラグインの場合はリポジトリに新しいプラグインのディレクトリを作成し、設定のjsonなどを配置 -> * リポジトリ、プラグインの追加はdevbaseに登録。 -> * プロジェクトはどのプラグインに属するかを決定(または問い合わせ)して、プラグインに追加 -> * PRを作成してmerge、手元に取り込むところまで実施して完了 -> -> * devbase listのTUIからも一連の操作が可能となるようにする(プラグインのメニューは整理しなおすこと) - -(書き手: 利用者、日付: 2026-11-06) - -## 起票者の推定 - -利用者の原文に無く、起票者が推して足した条件。承認ゲート 1 で利用者が確かめるまで、利用者の決定として扱わない。 - -| # | 条件 | 推した出所 | この要求での扱い | -| --- | --- | --- | --- | -| S1 | 「URL が存在し、権限があれば」「いずれも無ければ終了」を、次の 3 分岐と読む。存在して push できる → 使う。存在せず owner に作成できる → 作る。どちらでもない → 終了 | 原文の 3 行目は「存在するのに作成する」とも読めるため、成り立つ読み方を選んだ | 受け入れ条件 1〜5 | -| S2 | コマンド名は `devbase plugin repo new`・`devbase plugin new`・`devbase project new` | 既存の `plugin repo add` は「既にあるものの登録」なので語を分けた | 受け入れ条件 1・6・9 | -| S3 | 作るリポジトリの既定は private で、`--public` のときだけ公開する | 公開範囲を黙って広げないため | 受け入れ条件 1 | -| S4 | プラグインの設定は `plugin.yml` と `registry.yml`(原文の「設定のjson」は JSON ではなく既存の YAML と読む) | `docs/plugin-dev/plugin-yml-reference.md`、`lib/devbase/plugin/installer.py` の `parse_registry_yml` | 受け入れ条件 6 | -| S5 | プロジェクトの名前は既定でリポジトリ名、`--name` で変えられる。雛形は `containers/general` の dev 1 台・`scale: 1` | 既存のプロジェクトの形 | 受け入れ条件 9 | -| S6 | アカウントグループの宣言は、`--group` が無ければ入れ先のプラグインの既存プロジェクトの最多の値を使う | `env` の `DEVBASE_ACCOUNT_GROUP` は宣言が必須(#315) | 受け入れ条件 11 | -| S7 | 変更系の実行の前に計画を示して確認する。TTY が無いときは `--yes` を要る | マージは共有のレジストリの `main` へ届く | 受け入れ条件 15 | -| S8 | 空のリポジトリには PR を出せないので、作成直後の最初のコミットだけ既定ブランチへ直接入れる | GitHub は空のリポジトリに PR を作れない | 受け入れ条件 1 | -| S9 | 3 つの操作の TUI の入口は、どれも「プラグイン」のカテゴリの中に置く | 原文の「プラグインのメニューは整理しなおす」 | 受け入れ条件 18 | - -## 目的 - -新しいリポジトリを devbase で開発を始められる状態にするまでの手作業(レジストリのファイルの追記・`project.yml` などの配置・PR・マージ・`plugin update`)を、1 回のコマンドか TUI の操作で済ませる。今は [プラグイン開発クイックスタート](docs/plugin-dev/quickstart.md) の手順を人が打つ必要があり、入れ先のプラグインの判断も人の頭の中にある。 - -## 前提 - -- 前提 1: 対象は GitHub(github.com)だけである。GitHub 以外の URL は受け付けない -- 前提 2: `gh` がホストに入っていて認証済みである。`gh` は devbase の必須の依存には足さず、この 3 つのコマンドだけが要る -- 前提 3: 利用者はこのコマンドを打つことで、レジストリの既定ブランチへのマージを意図している - -## 対象範囲 - -含む: - -- `devbase plugin repo new`・`devbase plugin new`・`devbase project new` の追加 -- PR の作成・マージ・手元への取り込み・`plugins.yml` への登録 -- `devbase list` の TUI からの同じ 3 つの操作と、プラグインのメニューの組み直し -- シェル補完・CLI リファレンス・`CHANGELOG.md` - -含まない: - -- 追加したプロジェクトの起動(`devbase up` は打たない。P3) -- `env` の値の登録、`pre-up` などのフック、`Dockerfile` の雛形の出し分け -- 既存のプラグインの `description` にプロジェクト名を書き足す更新 -- GitHub 以外のホスト、Organization の作成、`gh` の導入やログインの代行 - -## ドメインイベント - -| # | イベント | 引き金 | 失敗したとき | 順序の前提 | -| --- | --- | --- | --- | --- | -| E1 | 引数を GitHub の owner/repo へ解決した | コマンドの実行 | GitHub 以外・形の誤りは変更なしで終了 | — | -| E2 | `gh` の認証と権限を確かめた | E1 | 未導入・未認証・権限なしは変更なしで終了 | E1 | -| E3 | 入れ先のプラグインとグループを決めた | E2(project) | 決まらず聞けないときは変更なしで終了 | E2 | -| E4 | 実行の計画を示して確認を得た | E2・E3 | 断られたら変更なしで終了 | E3 | -| E5 | リポジトリを作った | E4(存在しないとき) | 作成に失敗したら終了 | E4 | -| E6 | 手元の clone と別の作業場所でブランチを作り、ファイルを置いて push した | E4 | push に失敗したら手元の登録は変えない | E4・E5 | -| E7 | PR を作ってマージした | E6 | マージできなければ PR の URL を示して終了 | E6 | -| E8 | 手元の clone へ取り込んだ | E7 | 取り込めなければ原因と次のコマンドを示して終了 | E7 | -| E9 | `plugins.yml` へ登録し、`projects/` へ反映した | E8 | 失敗したら次のコマンドを示して終了 | E8 | - -## 用語 - -| 用語 | 意味 | -| --- | --- | -| プラグインリポジトリ | 直下に `registry.yml` を持つ Git リポジトリ。収めたプラグインは 0 件でもよい。`devbase plugin repo add` で登録するもの(~~1 つ以上のプラグインを収めた~~ → 0 件でもよいへ変更。2026-11-06、ゲート 1 の承認) | -| 作成フロー | リポジトリ・プラグイン・プロジェクトを足す一連の操作。権限の確認からマージ、手元への取り込み、登録までを含む | - -## 受け入れ条件 - -### リポジトリ(`devbase plugin repo new `) - -- [ ] 1. 前提: 指定のリポジトリが無く、owner に作成できる。操作: 実行する。結果: private のリポジトリができ、`registry.yml` を持つ最初のコミットが既定ブランチに入り、`repos/` に clone され、`plugins.yml` に登録され、終了コードは 0。`--public` のときだけ公開になる -- [ ] 2. 前提: リポジトリがあり push でき、`registry.yml` が無い。結果: `registry.yml` を足す PR が作られてマージされ、手元へ取り込まれて登録され、終了コードは 0 -- [ ] 3. 前提: リポジトリがあり push でき、`registry.yml` がある。結果: PR を作らずに登録し、終了コードは 0。登録済みなら変更せず、その旨を出して終了コードは 0 -- [ ] 4. 前提: リポジトリがあるが push できない、または無くて owner に作成できない。結果: GitHub にも手元にも何も作らず、理由を出して終了コードは 1 -- [ ] 5. `https://github.com/owner/repo`・`https://github.com/owner/repo.git`・`git@github.com:owner/repo.git`・`owner/repo` が同じ結果になり、GitHub 以外の URL は終了コード 1 になる - -### プラグイン(`devbase plugin new [--name <名前>]`) - -- [ ] 6. 前提: 登録済みのプラグインリポジトリ。結果: `<名前>/plugin.yml`・`<名前>/projects/`・`registry.yml` の項目を足す PR が作られてマージされ、手元へ取り込まれてプラグインが導入された状態(`devbase plugin list` に出る)になり、終了コードは 0 -- [ ] 7. 前提: リポジトリが未登録。結果: 受け入れ条件 1〜4 の分岐を通してからプラグインを足す。分岐が終了なら何も作らない -- [ ] 8. 同じ名前のプラグインが既にあるとき、何も変えずに終了コード 1 になる。名前は「名前の形」に合わなければ終了コード 1 になる - -### プロジェクト(`devbase project new [--plugin <名前>] [--group <名前>] [--name <名前>]`) - -- [ ] 9. 前提: 対象のリポジトリを読め、入れ先のプラグインへ push できる。結果: 入れ先の `projects/<名前>/` に `project.yml`・`compose.yml`・`env` を足す PR が作られてマージされ、手元へ取り込まれ、`devbase list` にプロジェクトが出て、終了コードは 0 -- [ ] 10. 入れ先の決定: `--plugin` があればそれを使う。無ければ、導入済みで push できるプラグインを候補にし、候補のうち対象と同じ owner のものがあればそれに絞る。1 件なら確認の計画に示して使い、複数で TTY があれば選ばせ、複数で TTY が無ければ候補を出して終了コード 1 になる。候補が 0 件なら終了コード 1 になる -- [ ] 11. グループの決定: `--group` があればそれを使う。無ければ入れ先の既存プロジェクトの最多の値を使う。決まらないとき、TTY があれば聞き、無ければ終了コード 1 になる -- [ ] 12. 対象のリポジトリを読めないとき、同じ名前のプロジェクトが `projects/` か入れ先に既にあるとき、何も変えずに終了コード 1 になる -- [ ] 13. どの経路でも `devbase up` を実行しない - -### 3 つに共通 - -- [ ] 14. `gh` が無い・未認証のとき、何も変えずに次の操作を出して終了コード 1 になる -- [ ] 15. 変更の前に計画(作るもの・マージ先)を示す。TTY があれば確認を取り、断れば何も変えない。TTY が無いときは `--yes` が無ければ何も変えずに終了コード 1 になる -- [ ] 16. 手元の clone に未コミットの変更があっても、その変更は失われず、作業は clone の作業ツリーを汚さない。取り込みが早送りで済まないときは変更を残したまま原因を出して終了コード 1 になる -- [ ] 17. マージできないとき(必須のレビューや検査が足りないなど)、PR の URL と続けるコマンドを出して終了コード 1 になり、`plugins.yml` は変わらない。作業用のブランチと作業場所は成功のときに残らない - -### TUI - -- [ ] 18. `devbase list` のプラグインのメニューから 3 つの操作を実行でき、引数は CLI と同じ値に解決される。入れ先の選択は TTY の選択肢として出る -- [ ] 19. プラグインのメニューは第 1 階層が用途で分かれ、既存の全操作(一覧・導入・削除・更新・詳細・再同期・移行・リポジトリの一覧/登録/削除/更新)へ届く -- [ ] 20. Esc・←・Ctrl-C のふるまいが既存のメニューと同じである - -### 退行しないこと - -- [ ] 21. 既存の `plugin` のサブコマンドの引数と出力は変わらない -- [ ] 22. `devbase project new owner/repo` の引数がプロジェクト名として解決されない - -## 非機能の条件 - -| 大項目 | 条件 | -| --- | --- | -| 運用・保守性 | 途中で止まったとき、どこまで進んだかと次のコマンドが出力に出る | -| セキュリティ | トークンを引数やログへ出さない。認証は `gh` と `git` の既存の設定に任せる。公開は `--public` のときだけ | -| システム環境 | Linux・macOS で動く。`gh` の最低版は設計で決める | - -## 影響 - -| 対象 | 影響 | -| --- | --- | -| 公開インタフェース | 変わる。サブコマンドの追加のみで、既存のコマンドは互換 | -| データ | `plugins.yml` の形は変わらない | -| 既存の振る舞い | TUI のプラグインのメニューの並びと階層が変わる | - -## 検証手段 - -| 項目 | 手段 | -| --- | --- | -| テスト | `env -u DEVBASE_ROOT uv run --locked pytest tests/ -q`。`gh` と `git` の push・マージは偽の `gh` と手元の bare リポジトリで置き換える | -| 静的解析・型検査 | `uvx ruff check --select=E9,F63,F7,F82 lib`、`python3 .github/scripts/proper_term_check.py` | -| 手動確認 | 利用者が作業用の Organization かアカウントで 3 つのコマンドを打ち、GitHub の PR とマージ、`devbase list` の表示を見る。TUI の見た目もこのときに見る | - -## 前提とする取り決め - -| 項目 | 参照先 / 決めたこと | -| --- | --- | -| プロジェクト構造 | `AGENTS.md` の「このリポジトリ」。実装は `lib/devbase/` | -| コーディング規約 | `AGENTS.md` の「書き方」 | -| テスト戦略 | 分岐は単体、CLI と TUI は引数の解決までを結合で確かめる。実の GitHub へはテストから触らない | - -## 境界 - -| 区分 | 内容 | -| --- | --- | -| 常に行う | 全テストと lint の実行、`CHANGELOG.md` の更新 | -| 確認してから行う | 公開インタフェースの形(承認ゲート 1)、`main` への配布(承認ゲート 2) | -| 行わない | テストから実の GitHub へ書く、`devbase up` の実行、強制 push | From 4fd5f679797c9ecbce250a2b5cd389cf4f12dc35 Mon Sep 17 00:00:00 2001 From: "takemi.ohama" Date: Fri, 6 Nov 2026 05:39:21 +0000 Subject: [PATCH 18/18] =?UTF-8?q?Refactor:=20#514=20=E6=96=B0=E3=81=97?= =?UTF-8?q?=E3=81=84=E3=82=B3=E3=83=9E=E3=83=B3=E3=83=89=E3=81=AE=E5=89=AF?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E3=82=92=20new=20=E3=81=8B=E3=82=89=20create?= =?UTF-8?q?=20=E3=81=B8=E6=94=B9=E5=90=8D=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit snapshot create と語を揃える。plugin repo new・plugin new・project new を plugin repo create・plugin create・project create へ改め、コマンドに由来する内部の 名前、作業ブランチの接頭辞 devbase/create-<種類>-<名前>、TUI の副命令の値、補完、 文書、テストを揃える。振る舞いは変えない。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MLNyzXBPxRoJnnnHwA7Guz --- CHANGELOG.md | 4 +- docs/glossary.md | 2 +- docs/glossary/glossary.json | 2 +- docs/plugin-dev/quickstart.md | 8 +- .../specifications/cli-argument-resolution.md | 4 +- docs/specifications/plugin-creation-flow.md | 78 ++++++++--------- docs/user/cli-reference/02-project.md | 10 +-- docs/user/cli-reference/04-plugin.md | 18 ++-- docs/user/cli-reference/README.md | 4 +- etc/_devbase | 12 +-- etc/devbase-completion.bash | 32 +++---- lib/devbase/cli.py | 68 +++++++-------- lib/devbase/commands/plugin.py | 16 ++-- lib/devbase/commands/project.py | 4 +- lib/devbase/plugin/creator.py | 10 +-- lib/devbase/plugin/publish.py | 2 +- lib/devbase/tui/actions_plugin.py | 34 ++++---- tests/cli/test_completion.py | 22 ++--- ...tch.py => test_project_create_dispatch.py} | 34 ++++---- tests/cli/tui/test_actions_plugin.py | 64 +++++++------- tests/plugin/test_create_plugin.py | 68 +++++++-------- tests/plugin/test_create_project.py | 86 +++++++++---------- tests/plugin/test_create_repo.py | 60 ++++++------- tests/plugin/test_github.py | 6 +- tests/plugin/test_publish.py | 8 +- 25 files changed, 328 insertions(+), 328 deletions(-) rename tests/cli/{test_project_new_dispatch.py => test_project_create_dispatch.py} (68%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 127b309b..531b6795 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ ### Added - **リポジトリ・プラグイン・プロジェクトを新規に足すコマンドを足しました(#514)。** - `devbase plugin repo new `・`devbase plugin new `・`devbase project new ` は、GitHub の URL か + `devbase plugin repo create `・`devbase plugin create `・`devbase project create ` は、GitHub の URL か `owner/repo` を受け、権限の確認からファイルの配置・PR・マージ・手元への取り込み・登録までを 1 回で行います。 - 新しいリポジトリは private で作り、`--public` のときだけ公開します。`project new` は入れ先のプラグインとアカウントグループを + 新しいリポジトリは private で作り、`--public` のときだけ公開します。`project create` は入れ先のプラグインとアカウントグループを 引数か既存の値から決め、決まらないときは端末で聞きます。変更の前に作成の計画を示して確認し、端末が無いときは `--yes` が要ります。 コンテナは起動しません。`gh` が要るのはこの 3 つのコマンドだけです。 diff --git a/docs/glossary.md b/docs/glossary.md index 8cb95b60..44eab8a3 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -265,7 +265,7 @@ devbase up / scale がコンテナを起動して待ち、その後にホスト ## プラグインの配布(`plugin-distribution`) -プラグインリポジトリの作成と登録、プラグインとプロジェクトの追加(lib/devbase/plugin/ と devbase plugin / devbase project new) +プラグインリポジトリの作成と登録、プラグインとプロジェクトの追加(lib/devbase/plugin/ と devbase plugin / devbase project create) | 語 | 識別子 | 意味 | 廃止した語 | 廃止した識別子 | 正本 | | --- | --- | --- | --- | --- | --- | diff --git a/docs/glossary/glossary.json b/docs/glossary/glossary.json index 522cef74..d5b0aead 100644 --- a/docs/glossary/glossary.json +++ b/docs/glossary/glossary.json @@ -74,7 +74,7 @@ { "id": "plugin-distribution", "name": "プラグインの配布", - "meaning": "プラグインリポジトリの作成と登録、プラグインとプロジェクトの追加(lib/devbase/plugin/ と devbase plugin / devbase project new)" + "meaning": "プラグインリポジトリの作成と登録、プラグインとプロジェクトの追加(lib/devbase/plugin/ と devbase plugin / devbase project create)" } ], "terms": [ diff --git a/docs/plugin-dev/quickstart.md b/docs/plugin-dev/quickstart.md index ddecd551..a749485a 100644 --- a/docs/plugin-dev/quickstart.md +++ b/docs/plugin-dev/quickstart.md @@ -17,12 +17,12 @@ devbase用のPluginを作成し、公開するまでの手順を解説します GitHub で公開するプラグインは、`gh` が使えればコマンド 1 つで足せます。ファイルの配置・PR・マージ・手元への取り込みまで終わります。 ```bash -devbase plugin repo new your-user/my-plugins # プラグインリポジトリを用意して登録する -devbase plugin new your-user/my-plugins --name my-plugin # プラグインを足して導入する -devbase project new your-user/my-app --plugin my-plugin --group personal # プロジェクトを足す +devbase plugin repo create your-user/my-plugins # プラグインリポジトリを用意して登録する +devbase plugin create your-user/my-plugins --name my-plugin # プラグインを足して導入する +devbase project create your-user/my-app --plugin my-plugin --group personal # プロジェクトを足す ``` -詳しくは [plugin グループ](../user/cli-reference/04-plugin.md#作成フローplugin-new--plugin-repo-new--project-new-に共通)を参照してください。この後の節は、手でファイルを置くときの手順です。 +詳しくは [plugin グループ](../user/cli-reference/04-plugin.md#作成フローplugin-create--plugin-repo-create--project-create-に共通)を参照してください。この後の節は、手でファイルを置くときの手順です。 --- diff --git a/docs/specifications/cli-argument-resolution.md b/docs/specifications/cli-argument-resolution.md index 7105a2e0..44fe359e 100644 --- a/docs/specifications/cli-argument-resolution.md +++ b/docs/specifications/cli-argument-resolution.md @@ -283,7 +283,7 @@ shell が Python を呼ばずに同じ正規表現を文字列で持つのは、 プラグインの同期(`discover_projects`・実ディレクトリの知らせ)、`plugin info` と `status` の プラグインのプロジェクト数(どちらも `discover_projects` を通す)、`status` のコンテナの状態、 `project list`、見つからない名前での `up` の候補、`project migrate-config`、`env export`、 -`env doctor`、`env encrypt` / `env decrypt`、`env backend status` と backend の移行、`project new` の +`env doctor`、`env encrypt` / `env decrypt`、`env backend status` と backend の移行、`project create` の グループの案が、`projects/` を走査するときの名前の条件としてこの述語を呼ぶ。ディレクトリの条件(`is_dir()`・壊れた symlink を 拾う `is_symlink()`・`compose.yml` の有無)は走査ごとに持つ。名前の条件はディレクトリの条件より 先に見る(壊れた symlink を名前だけで外せ、`stat` を打たないため)。同期が張った symlink の掃除と、 @@ -302,7 +302,7 @@ shell が Python を呼ばずに同じ正規表現を文字列で持つのは、 | `env doctor` の重なりと除外設定の確認 | `commands/env_ops.py` | `names.project_dirs` | `is_dir()` | | `env encrypt` / `env decrypt` の対象 | `commands/env_migrate.py` | `names.project_dirs` | `is_dir()` | | `env backend status` と backend の移行の対象 | `commands/env_backend.py` | `names.project_dirs` の後に `SecretRef.for_project`(拒まれた名前は黙って外す) | `is_dir()` | -| `project new` のグループの案(入れ先のプラグインの `projects/` を数える `suggest_group`) | `plugin/creator.py` | `names.project_dirs` | `is_dir()` | +| `project create` のグループの案(入れ先のプラグインの `projects/` を数える `suggest_group`) | `plugin/creator.py` | `names.project_dirs` | `is_dir()` | `plugin info` と `status` のプラグインのプロジェクト数は、述語を個別に持たず `discover_projects` を 通す。同期と同じ関数を呼ぶことで、ディレクトリの条件まで同期と構造的に一致する。 diff --git a/docs/specifications/plugin-creation-flow.md b/docs/specifications/plugin-creation-flow.md index d4e5e3f0..e5421b28 100644 --- a/docs/specifications/plugin-creation-flow.md +++ b/docs/specifications/plugin-creation-flow.md @@ -2,7 +2,7 @@ ## 概要 -`devbase plugin repo new`・`devbase plugin new`・`devbase project new` は、GitHub の URL か `owner/repo` を +`devbase plugin repo create`・`devbase plugin create`・`devbase project create` は、GitHub の URL か `owner/repo` を 1 つ受け、権限の確認からファイルの配置・PR・マージ・手元への取り込み・`plugins.yml` への登録までを 1 回で行う。 `devbase list` の TUI のプラグインのメニューからも同じ操作を実行できる。 @@ -10,7 +10,7 @@ 書かない。コンテナは起動しない(`devbase up` は打たない)。`gh` が要るのはこの 3 つのコマンドだけである。 利用者向けの引数と使い方は [plugin グループ](../user/cli-reference/04-plugin.md) と -[project グループ](../user/cli-reference/02-project.md#devbase-project-new) にある。 +[project グループ](../user/cli-reference/02-project.md#devbase-project-create) にある。 ## 用語 @@ -58,7 +58,7 @@ GitHub 上のプラグインへリポジトリを足すには、`registry.yml` | 既定ブランチへの反映 | `lib/devbase/plugin/publish.py` | 一時の浅い clone で変更を作る。`push_initial`(最初のコミット)、`publish_change`(push・PR・マージ)、`branch_name`、`MergeFailed` | | 計画と実行 | `lib/devbase/plugin/creator.py` | `plan_repo`・`plan_plugin`・`plan_project`(読むだけ)、`execute`(書く)、`CreationPlan`、入れ先とグループの決定 | | 登録の照合と取り込み | `lib/devbase/plugin/repo_manager.py` | `_find_registered`、`_require_default_branch`、`_pull_ff_only`、`_snapshot_repo_projects`。`refresh_repository` は控えを `pre_pull_projects` で受ける | -| CLI の入口 | `lib/devbase/commands/plugin.py`、`lib/devbase/commands/project.py` | `cmd_plugin_new`・`cmd_repo_new`・`cmd_project_new`、計画の確認 `run_creation`、端末で聞く `_TtyPrompter` | +| CLI の入口 | `lib/devbase/commands/plugin.py`、`lib/devbase/commands/project.py` | `cmd_plugin_create`・`cmd_repo_create`・`cmd_project_create`、計画の確認 `run_creation`、端末で聞く `_TtyPrompter` | | パーサと機密の注入 | `lib/devbase/cli.py` | パーサ、`SUBCMD_MAP`、`repo_subcmds`、`_NO_SECRET_INJECTION`、`_injection_subcommand` | | TUI | `lib/devbase/tui/actions_plugin.py` | 2 階層のメニューと新規追加の 3 つの入口 | | シェル補完 | `etc/_devbase`、`etc/devbase-completion.bash` | 3 つのコマンドとオプションの候補 | @@ -78,8 +78,8 @@ graph TD R --> Reg[plugins.yml] ``` -`bin/devbase` は変わらない。`_PROJECT_NAME_SUBCOMMANDS` に `new` が無いので、`project new owner/repo` の引数は -プロジェクト名として解決されない。`new` は `project`・`plugin` の既存の副命令と接頭辞が重ならないため、 +`bin/devbase` は変わらない。`_PROJECT_NAME_SUBCOMMANDS` に `create` が無いので、`project create owner/repo` の引数は +プロジェクト名として解決されない。`create` は `project`・`plugin` の既存の副命令と接頭辞が重ならないため、 `SUBCMD_PREFIX_PREFERENCES` は持たない。 ## 仕様 @@ -113,9 +113,9 @@ graph TD | コマンド | 引数 | 終了コード | | --- | --- | --- | -| `devbase plugin repo new ` | `--public`(既定 private)、`--yes` | 0 成功・push できる登録済み / 1 それ以外 | -| `devbase plugin new ` | `--name`(既定はリポジトリ名)、`--public`、`--yes` | 0 成功 / 1 それ以外 | -| `devbase project new ` | `--plugin`、`--group`、`--name`(既定はリポジトリ名を整えたもの)、`--yes` | 0 成功 / 1 それ以外 | +| `devbase plugin repo create ` | `--public`(既定 private)、`--yes` | 0 成功・push できる登録済み / 1 それ以外 | +| `devbase plugin create ` | `--name`(既定はリポジトリ名)、`--public`、`--yes` | 0 成功 / 1 それ以外 | +| `devbase project create ` | `--plugin`、`--group`、`--name`(既定はリポジトリ名を整えたもの)、`--yes` | 0 成功 / 1 それ以外 | `` は `owner/repo`・`https://github.com/owner/repo[.git]`・`git@github.com:owner/repo[.git]` を受ける。`git@` の形の 入力は clone の URL も `git@` のままにし、ほかは `https://github.com/owner/repo.git` にする。GitHub 以外の URL と形の誤りは @@ -136,7 +136,7 @@ graph TD ### リポジトリの分岐 -`plugin repo new` と、未登録のリポジトリへの `plugin new` が通る。 +`plugin repo create` と、未登録のリポジトリへの `plugin create` が通る。 | リポジトリ | push | `registry.yml` | 動作 | | --- | --- | --- | --- | @@ -146,7 +146,7 @@ graph TD | 空・未登録 | できる | — | 最初のコミットを直接 push → 登録 | | ある・未登録 | できる | 無い | PR → マージ → 登録 | | ある・未登録 | できる | ある | 登録だけ | -| 空・ある・登録済み | できる | — | `plugin repo new` は何もせず 0 | +| 空・ある・登録済み | できる | — | `plugin repo create` は何もせず 0 | | 空・ある | できない | — | 終了(1)。登録済みでも同じ | - push できるのは `viewerPermission` が `ADMIN`・`MAINTAIN`・`WRITE` のときである @@ -171,40 +171,40 @@ graph TD | `_pull_ff_only` | 登録の `repo.local_path` の clone | | `refresh_repository` | 登録の `repo.name` | | `install_plugin` | `:<プラグイン名>`(登録の `repo.url`) | -| 一時の clone と push(`plugin new`・`project new`) | 登録の `repo.url`(SSH の認証だけの利用者が https で止まらない) | +| 一時の clone と push(`plugin create`・`project create`) | 登録の `repo.url`(SSH の認証だけの利用者が https で止まらない) | ### 計画の確定の前の確認 -`plugin new` と `project new` は、計画の確定の前に次を確かめる。対象の登録は、`plugin new` では `_find_registered` が見つけた -登録、`project new` では入れ先のプラグインの登録である。どれも GitHub にも手元にも書かず、終了コード 1 で止まる。 +`plugin create` と `project create` は、計画の確定の前に次を確かめる。対象の登録は、`plugin create` では `_find_registered` が見つけた +登録、`project create` では入れ先のプラグインの登録である。どれも GitHub にも手元にも書かず、終了コード 1 で止まる。 | 確認 | 止まる理由 | 案内 | | --- | --- | --- | | `repo.local_path` が空でなく、`devbase_root / repo.local_path` がディレクトリである | 空のまま進むと `devbase_root` そのものを指し、devbase 本体を取り込む | `plugin repo remove ` と `plugin repo add `。導入し直す `plugin install` も案内する | | clone が GitHub の既定ブランチにいて、`origin` の同じブランチを追っている | clone の `origin/HEAD` は既定ブランチの変更に追従せず、取り込みが成功しても足したものが手元に現れない | 切り替えのコマンド | -| `plugin new`: 登録済みのリポジトリの既定ブランチに `registry.yml` がある | 登録済みの経路は 1 項目の追記だけで、リポジトリの分岐を通らない | — | -| `project new`: 登録の `path` が既定ブランチの `registry.yml` の項目と同じである | 古い `path` へマージすると、足したプロジェクトが `projects/` に現れないまま 0 で終わる | `plugin repo refresh ` | +| `plugin create`: 登録済みのリポジトリの既定ブランチに `registry.yml` がある | 登録済みの経路は 1 項目の追記だけで、リポジトリの分岐を通らない | — | +| `project create`: 登録の `path` が既定ブランチの `registry.yml` の項目と同じである | 古い `path` へマージすると、足したプロジェクトが `projects/` に現れないまま 0 で終わる | `plugin repo refresh ` | -`plugin repo new` はこれらを確かめない。登録済みの経路は clone に触らないので、`local_path` が空でも push できれば何もせず 0 で終わる。 +`plugin repo create` はこれらを確かめない。登録済みの経路は clone に触らないので、`local_path` が空でも push できれば何もせず 0 で終わる。 ### 経路ごとの反映と登録 | コマンド | リポジトリ | 既定ブランチへの反映 | 登録と反映(反映の後に行う) | 通るイベント(E4 の後) | | --- | --- | --- | --- | --- | -| `plugin repo new` | 無い | 最初のコミットの直接の push | `add_repository` | E5 → E6 → E9 | -| `plugin repo new` | 空 | 最初のコミットの直接の push | `add_repository` | E6 → E9 | -| `plugin repo new` | `registry.yml` が無い | PR のマージ | `add_repository` | E6 → E7 → E9 | -| `plugin repo new` | `registry.yml` がある・未登録 | 無し | `add_repository` | E9 | -| `plugin new` | 登録済み | プラグインの PR のマージ | `_pull_ff_only` → `refresh_repository` → `install_plugin` | E6 → E7 → E8 → E9 | -| `plugin new` | 無い | 最初のコミット → プラグインの PR のマージ | `add_repository` → `install_plugin` | E5 → E6 → E6 → E7 → E9 | -| `plugin new` | 空 | 最初のコミット → プラグインの PR のマージ | `add_repository` → `install_plugin` | E6 → E6 → E7 → E9 | -| `plugin new` | `registry.yml` が無い | `registry.yml` の PR のマージ → プラグインの PR のマージ | `add_repository` → `install_plugin` | E6 → E7 → E6 → E7 → E9 | -| `plugin new` | `registry.yml` がある・未登録 | プラグインの PR のマージ | `add_repository` → `install_plugin` | E6 → E7 → E9 | -| `project new` | 入れ先のプラグインのリポジトリ(登録済み) | プロジェクトの PR のマージ | `_pull_ff_only` → `refresh_repository` | E6 → E7 → E8 → E9 | +| `plugin repo create` | 無い | 最初のコミットの直接の push | `add_repository` | E5 → E6 → E9 | +| `plugin repo create` | 空 | 最初のコミットの直接の push | `add_repository` | E6 → E9 | +| `plugin repo create` | `registry.yml` が無い | PR のマージ | `add_repository` | E6 → E7 → E9 | +| `plugin repo create` | `registry.yml` がある・未登録 | 無し | `add_repository` | E9 | +| `plugin create` | 登録済み | プラグインの PR のマージ | `_pull_ff_only` → `refresh_repository` → `install_plugin` | E6 → E7 → E8 → E9 | +| `plugin create` | 無い | 最初のコミット → プラグインの PR のマージ | `add_repository` → `install_plugin` | E5 → E6 → E6 → E7 → E9 | +| `plugin create` | 空 | 最初のコミット → プラグインの PR のマージ | `add_repository` → `install_plugin` | E6 → E6 → E7 → E9 | +| `plugin create` | `registry.yml` が無い | `registry.yml` の PR のマージ → プラグインの PR のマージ | `add_repository` → `install_plugin` | E6 → E7 → E6 → E7 → E9 | +| `plugin create` | `registry.yml` がある・未登録 | プラグインの PR のマージ | `add_repository` → `install_plugin` | E6 → E7 → E9 | +| `project create` | 入れ先のプラグインのリポジトリ(登録済み) | プロジェクトの PR のマージ | `_pull_ff_only` → `refresh_repository` | E6 → E7 → E8 → E9 | 未登録のリポジトリには手元の clone が無いので E8 を通らず、`add_repository` が clone する。 -未登録のリポジトリへの `plugin new` は、リポジトリの分の反映とプラグインの追加を別の変更として順に行い、プラグインの PR の +未登録のリポジトリへの `plugin create` は、リポジトリの分の反映とプラグインの追加を別の変更として順に行い、プラグインの PR の マージが成功してから登録する。先に登録すると、マージの失敗で `plugins.yml` が変わったまま残るためである。 登録済みの経路は `_pull_ff_only` の前に、導入済みのプラグインのプロジェクト一覧を `_snapshot_repo_projects` で控え、 @@ -233,7 +233,7 @@ sequenceDiagram else registry.yml がある Note over C,T: リポジトリの分岐では GitHub へ書かない end - opt plugin new・project new + opt plugin create・project create C->>T: 浅い clone → ブランチ → プラグインかプロジェクトのファイル → commit → push C->>G: PR 作成 → マージ end @@ -314,9 +314,9 @@ sequenceDiagram | プラグイン | リポジトリ → 名前(空で既定)→ 計画の確認 | | リポジトリ | リポジトリ → 公開するかの確認(既定 いいえ)→ 計画の確認 | -TUI は `creator` の読むだけの関数で候補・案・計画を得て、確かめた値を `yes=True` で `cmd_plugin`・`cmd_project_new` へ渡す。 +TUI は `creator` の読むだけの関数で候補・案・計画を得て、確かめた値を `yes=True` で `cmd_plugin`・`cmd_project_create` へ渡す。 入力の差を CLI と TUI で分けないため、ロジックは二重に持たない。TUI のプラグインの入口は `--public` を持たない。 -`plugin repo new` の計画が `noop_reason` を持つときは、確認を出さずに渡す。 +`plugin repo create` の計画が `noop_reason` を持つときは、確認を出さずに渡す。 ## データ・設定 @@ -354,7 +354,7 @@ TUI は `creator` の読むだけの関数で候補・案・計画を得て、 ### 作業ブランチと PR -作業ブランチは `devbase/new-<種類>-<名前>`、PR の題は `devbase: <種類> <名前> を足す` である。種類は `repo`・`plugin`・`project` で、 +作業ブランチは `devbase/create-<種類>-<名前>`、PR の題は `devbase: <種類> <名前> を足す` である。種類は `repo`・`plugin`・`project` で、 PR の本文は固定の 1 行である。 名前の形は git のブランチ名より広いので、`..` を含むか `.`・`.lock` で終わる名前は、ブランチの `<名前>` の `.` を `-` に置き換えて @@ -403,9 +403,9 @@ CI は待たず、`--auto` と `--admin` は使わない。必須の検査やレ | 作ったリポジトリへの反映 | 作ったリポジトリ | 作成済みであることと、同じコマンドの打ち直し | | 同じブランチが既にある | 既存のブランチと PR | 開いている PR があればその URL。無ければブランチを消して打ち直す案内 | | PR の作成 | GitHub のブランチ | ブランチを消して打ち直す案内 | -| マージ | PR とブランチ | PR の URL と、マージの後に打つコマンド(未登録は `plugin repo add`、登録済みは `plugin repo refresh`。`plugin new` は `plugin install` も) | -| `plugin new` の `registry.yml` の PR | PR とブランチ。プラグインの PR はまだ無い。`plugins.yml` は元のまま | PR の URL と、マージの後に同じ `plugin new` を打ち直す案内 | -| 未登録のリポジトリへの `plugin new` のプラグインの PR | 先に反映した最初のコミットか `registry.yml` は既定ブランチに残る。`plugins.yml` は元のまま | PR の URL と、マージの後に打つコマンド(`plugin repo add`・`plugin install`) | +| マージ | PR とブランチ | PR の URL と、マージの後に打つコマンド(未登録は `plugin repo add`、登録済みは `plugin repo refresh`。`plugin create` は `plugin install` も) | +| `plugin create` の `registry.yml` の PR | PR とブランチ。プラグインの PR はまだ無い。`plugins.yml` は元のまま | PR の URL と、マージの後に同じ `plugin create` を打ち直す案内 | +| 未登録のリポジトリへの `plugin create` のプラグインの PR | 先に反映した最初のコミットか `registry.yml` は既定ブランチに残る。`plugins.yml` は元のまま | PR の URL と、マージの後に打つコマンド(`plugin repo add`・`plugin install`) | | 取り込み | マージ済み。手元は元のまま | 原因と `git -C status`、続けて打つコマンド | | 登録 | マージと取り込み済み | 既存のコマンドのエラーと、続けて打つコマンド | @@ -438,22 +438,22 @@ CI は待たず、`--auto` と `--admin` は使わない。必須の検査やレ | プラグイン | `plugin.yml`・`registry.yml` の項目が入り、`plugin list` に出る。重複名と名前の形の誤りは何も変えない | `tests/plugin/test_create_plugin.py` | | 未登録へのプラグイン | 4 状態で、リポジトリの分 → プラグインの PR → 登録の順である | `tests/plugin/test_create_plugin.py` | | 登録の照合 | URL の形が違っても登録済みの経路を通り、`plugins.yml` の `url` が変わらない。push できない登録は何も書かず 1 で終わる | `tests/plugin/test_create_plugin.py`、`tests/plugin/test_create_repo.py` | -| 登録の clone | `local_path` が空か clone が無い登録は、確認の前に止まり、書き込みの呼び出しが 0 回で、devbase 本体が変わらない。`plugin repo new` は 0 で終わる | `tests/plugin/test_create_plugin.py`、`tests/plugin/test_create_project.py` | +| 登録の clone | `local_path` が空か clone が無い登録は、確認の前に止まり、書き込みの呼び出しが 0 回で、devbase 本体が変わらない。`plugin repo create` は 0 で終わる | `tests/plugin/test_create_plugin.py`、`tests/plugin/test_create_project.py` | | プロジェクト | 3 ファイルと `projects/<名前>` の反映。読めないとき・重複のときは何も変わらない | `tests/plugin/test_create_project.py` | | 入れ先とグループ | 決定の 4 段を満たす。同数で片方を選ばず、どの出所でもグループの規則を通す | `tests/plugin/test_create_project.py` | | 名前 | Compose・Docker の参照・git のブランチ名の規則に合う | `tests/plugin/test_create_project.py`、`tests/plugin/test_create_plugin.py`、`tests/plugin/test_publish.py` | | コンテナ | どの経路でも `docker` と `compose` を呼ばない | `tests/plugin/test_create_project.py` ほか | | `gh` と確認 | `gh` が無い・未認証・確認の前は書き込みの呼び出しが 0 回である。端末が無く `--yes` が無ければ 1 である | `tests/plugin/test_create_repo.py` ほか | | 手元の clone | 未コミットの変更が残り、分岐した clone と既定ブランチを追わない clone は止まる。`creator`・`publish` は手元の作業ツリーへ書かない | `tests/plugin/test_repo_manager_creation.py`、`tests/plugin/test_create_plugin.py` | -| マージの失敗 | `plugins.yml` が同じで URL が出る。未登録のリポジトリへの `plugin new` でも同じである。成功のとき作業場所が残らない | `tests/plugin/test_create_plugin.py`、`tests/plugin/test_create_project.py` | +| マージの失敗 | `plugins.yml` が同じで URL が出る。未登録のリポジトリへの `plugin create` でも同じである。成功のとき作業場所が残らない | `tests/plugin/test_create_plugin.py`、`tests/plugin/test_create_project.py` | | `registry.yml` | コメント付きのファイルで既存の行が残り、壊れる追記は止まる | `tests/plugin/test_scaffold.py` | | TUI | メニューの全項目が既存の操作へ届き、Esc と Ctrl-C の戻り値が既存どおりに伝わる | `tests/cli/tui/test_actions_plugin.py` | -| 退行 | 既存の `plugin` のサブコマンドが変わらない。`project new owner/repo` がプロジェクトの切替を通らない。補完の候補が CLI と一致する | `tests/cli/test_project_new_dispatch.py`、`tests/cli/test_completion.py` | +| 退行 | 既存の `plugin` のサブコマンドが変わらない。`project create owner/repo` がプロジェクトの切替を通らない。補完の候補が CLI と一致する | `tests/cli/test_project_create_dispatch.py`、`tests/cli/test_completion.py` | ## 関連リンク -- [CLI リファレンス: 作成フロー](../user/cli-reference/04-plugin.md#作成フローplugin-new--plugin-repo-new--project-new-に共通) -- [CLI リファレンス: `devbase project new`](../user/cli-reference/02-project.md#devbase-project-new) +- [CLI リファレンス: 作成フロー](../user/cli-reference/04-plugin.md#作成フローplugin-create--plugin-repo-create--project-create-に共通) +- [CLI リファレンス: `devbase project create`](../user/cli-reference/02-project.md#devbase-project-create) - [プラグイン開発クイックスタート: コマンドで足す](../plugin-dev/quickstart.md#コマンドで足す) - [plugin.yml リファレンス](../plugin-dev/plugin-yml-reference.md) - [位置引数の解決](cli-argument-resolution.md) diff --git a/docs/user/cli-reference/02-project.md b/docs/user/cli-reference/02-project.md index 3f523a98..65f5c69c 100644 --- a/docs/user/cli-reference/02-project.md +++ b/docs/user/cli-reference/02-project.md @@ -447,17 +447,17 @@ devbase rebuild [name] |-----------|------|------| | `name` | いいえ | 対象プロジェクト名(省略時はカレント) | -## `devbase project new` +## `devbase project create` GitHub のリポジトリのプロジェクトをプラグインへ足し、手元へ反映します。コンテナは起動しません。 ``` -devbase project new [--plugin <名前>] [--group <名前>] [--name <名前>] [--yes] +devbase project create [--plugin <名前>] [--group <名前>] [--name <名前>] [--yes] ``` | パラメータ | 必須 | 説明 | |-----------|------|------| -| `repo` | はい | 対象の GitHub のリポジトリ(`owner/repo`・URL。[作成フロー](04-plugin.md#作成フローplugin-new--plugin-repo-new--project-new-に共通)) | +| `repo` | はい | 対象の GitHub のリポジトリ(`owner/repo`・URL。[作成フロー](04-plugin.md#作成フローplugin-create--plugin-repo-create--project-create-に共通)) | | `--plugin` | いいえ | 入れ先のプラグイン | | `--group` | いいえ | アカウントグループ | | `--name` | いいえ | プロジェクトの名前。小文字の英数字で始まり、小文字の英数字・`-`・`_` だけからなる形(Compose のプロジェクト名の規則)で、合わなければ何も変えずに終了コード 1 で止まります。既定はリポジトリ名を小文字にし、使えない文字の並びを `-` に置き換えたものです(`MyApp` は `myapp`、`foo.github.io` は `foo-github-io`) | @@ -536,14 +536,14 @@ build / rebuild を選べます。先頭(Enter 1 回で決まる位置)は * | 削除 | アンインストール / リポジトリ削除 | | 保守 | リンクの再同期 / レガシー構成の移行 | -新規追加は、CLI の `project new`・`plugin new`・`plugin repo new` と同じ値を順に聞きます。入れ先のプラグインは候補が 2 件以上のときに選択肢で出し、グループは入れ先の案を既定値にします。最後に作成の計画を示して確認します。 +新規追加は、CLI の `project create`・`plugin create`・`plugin repo create` と同じ値を順に聞きます。入れ先のプラグインは候補が 2 件以上のときに選択肢で出し、グループは入れ先の案を既定値にします。最後に作成の計画を示して確認します。 - 確認プロンプト (y/N) が出るのは破壊的操作(plugin uninstall / plugin repo remove / snapshot restore / snapshot delete / 環境変数のキーの削除)と新規追加の計画だけで、その他は CLI 既定値で即実行します - 操作の出力後は Enter キーで一覧へ戻ります(出力が流れて読めなくなるのを防ぐため) - 環境変数の「キーの一覧と編集」と「OpenBao の接続設定」は [環境変数の TUI](03-env.md#tui-でのキーの編集と-openbao-の接続設定) を参照してください - TUI が提供しない細かいオプション(`env get/export/import`、 - `plugin install --link/--all`、`plugin new --public`、`snapshot create --full`、`logs --follow` 等)は + `plugin install --link/--all`、`plugin create --public`、`snapshot create --full`、`logs --follow` 等)は CLI を使用してください - questionary 未導入時は従来の番号入力(選択 → up)にフォールバックします diff --git a/docs/user/cli-reference/04-plugin.md b/docs/user/cli-reference/04-plugin.md index b571632a..56ddf16c 100644 --- a/docs/user/cli-reference/04-plugin.md +++ b/docs/user/cli-reference/04-plugin.md @@ -87,7 +87,7 @@ devbase plugin migrate `--link` でインストールしたプラグインは移行対象外です。 -## 作成フロー(`plugin new` / `plugin repo new` / `project new` に共通) +## 作成フロー(`plugin create` / `plugin repo create` / `project create` に共通) リポジトリ・プラグイン・プロジェクトを足すコマンドは、権限の確認からマージ、手元への取り込み、登録までを 1 回で行います。振る舞いの正本は[確定仕様](../../specifications/plugin-creation-flow.md)にあります。 @@ -98,40 +98,40 @@ devbase plugin migrate - **マージは 1 回だけ試します。** CI を待たず、`--auto` と `--admin` を使いません。必須のレビューや検査でマージできないときは、PR の URL とマージの後に打つコマンドを出して終了コード 1 で止まり、`plugins.yml` は変わりません - **コンテナは起動しません。** 起動は `devbase up` を別に打ちます -作業ブランチは `devbase/new-<種類>-<名前>` で、マージのときに消えます。git のブランチ名にできない名前(`..` を含むか `.`・`.lock` で終わる)は、`.` を `-` に置き換えてハッシュを足した形になります。同じブランチが既にあると止まり、開いている PR があればその URL を出します。 +作業ブランチは `devbase/create-<種類>-<名前>` で、マージのときに消えます。git のブランチ名にできない名前(`..` を含むか `.`・`.lock` で終わる)は、`.` を `-` に置き換えてハッシュを足した形になります。同じブランチが既にあると止まり、開いている PR があればその URL を出します。 -## `devbase plugin new` +## `devbase plugin create` GitHub のリポジトリへプラグインを足して導入します。 ``` -devbase plugin new [--name <名前>] [--public] [--yes] +devbase plugin create [--name <名前>] [--public] [--yes] ``` | パラメータ | 必須 | 説明 | |-----------|------|------| -| `repo` | はい | GitHub のリポジトリ([作成フロー](#作成フローplugin-new--plugin-repo-new--project-new-に共通)) | +| `repo` | はい | GitHub のリポジトリ([作成フロー](#作成フローplugin-create--plugin-repo-create--project-create-に共通)) | | `--name` | いいえ | プラグインの名前(既定: リポジトリ名)。英数字で始まり英数字・`.`・`-`・`_` だけからなる形 | | `--public` | いいえ | リポジトリを新しく作るときに公開する(既定: private)。既存のリポジトリの公開範囲は変えない | | `--yes` | いいえ | 計画の確認を省く。端末が無いときは必須 | `<名前>/plugin.yml`・`<名前>/projects/.gitkeep`・`registry.yml` の項目を足す PR を作ってマージし、手元へ取り込んで導入します。 -未登録のリポジトリは、先に `plugin repo new` と同じ分岐を通します。リポジトリの分の変更とプラグインの PR は別の変更として順に入り、登録はプラグインの PR のマージの後です。 +未登録のリポジトリは、先に `plugin repo create` と同じ分岐を通します。リポジトリの分の変更とプラグインの PR は別の変更として順に入り、登録はプラグインの PR のマージの後です。 同じ名前のプラグインが `registry.yml` か導入済みの中にあるとき、同じ名前のパスがリポジトリにあるときは、何も変えずに終了コード 1 で止まります。登録の手元の clone が無いときは、登録し直すコマンドを出して止まります。登録の手元の clone が GitHub の既定ブランチを追っていないときは、切り替えのコマンドを出して止まります。 -## `devbase plugin repo new` +## `devbase plugin repo create` プラグインリポジトリを用意して登録します。 ``` -devbase plugin repo new [--public] [--yes] +devbase plugin repo create [--public] [--yes] ``` | パラメータ | 必須 | 説明 | |-----------|------|------| -| `repo` | はい | GitHub のリポジトリ([作成フロー](#作成フローplugin-new--plugin-repo-new--project-new-に共通)) | +| `repo` | はい | GitHub のリポジトリ([作成フロー](#作成フローplugin-create--plugin-repo-create--project-create-に共通)) | | `--public` | いいえ | リポジトリを新しく作るときに公開する(既定: private) | | `--yes` | いいえ | 計画の確認を省く。端末が無いときは必須 | diff --git a/docs/user/cli-reference/README.md b/docs/user/cli-reference/README.md index b65e6a3e..56d815ce 100644 --- a/docs/user/cli-reference/README.md +++ b/docs/user/cli-reference/README.md @@ -5,9 +5,9 @@ devbase の全コマンドの構文、オプション、使用例をまとめた | ファイル | 内容 | |---------|------| | [トップレベルコマンド](01-toplevel.md) | `init` / `status` / `bin/rc` | -| [project グループ](02-project.md) | コンテナのライフサイクル管理・一覧(`up` / `down` / `login` / `ps` / `logs` / `scale` / `build` / `rebuild` / `open` / `post-start` / `profile` / `list` / `new`)と非推奨の `container` グループ | +| [project グループ](02-project.md) | コンテナのライフサイクル管理・一覧(`up` / `down` / `login` / `ps` / `logs` / `scale` / `build` / `rebuild` / `open` / `post-start` / `profile` / `list` / `create`)と非推奨の `container` グループ | | [env グループ](03-env.md) | 環境変数の管理(`init` / `sync` / `list` / `set` / `get` / `delete` / `edit` / `project` / `keygen` / `encrypt` / `decrypt` / `exec` / `token` / `rekey` / `doctor` / `export` / `import`) | -| [plugin グループ](04-plugin.md) | プラグインの管理(`list` / `install` / `uninstall` / `update` / `info` / `sync` / `migrate` / `new` / `repo *`) | +| [plugin グループ](04-plugin.md) | プラグインの管理(`list` / `install` / `uninstall` / `update` / `info` / `sync` / `migrate` / `create` / `repo *`) | | [snapshot グループ](05-snapshot.md) | スナップショットの管理(`create` / `list` / `restore` / `copy` / `delete` / `rotate`) | ## コマンド体系 diff --git a/etc/_devbase b/etc/_devbase index cbb79eef..5f4c5a5d 100644 --- a/etc/_devbase +++ b/etc/_devbase @@ -99,7 +99,7 @@ _devbase() { 'profile:Start / stop compose profile services' 'open:Open the editor attached to the dev container' 'post-start:Redo the post-start steps on running instances' - 'new:Add a project for a GitHub repository to a plugin' + 'create:Add a project for a GitHub repository to a plugin' ) container_subcommands=( @@ -144,11 +144,11 @@ _devbase() { 'info:Show plugin details' 'sync:Resync project symlinks' 'repo:Manage plugin repositories' - 'new:Add a new plugin to a repository on GitHub' + 'create:Add a new plugin to a repository on GitHub' ) repo_subcommands=( - 'new:Create (if needed) and register a repository on GitHub' + 'create:Create (if needed) and register a repository on GitHub' 'add:Register a repository' 'remove:Unregister a repository' 'list:List registered repositories' @@ -279,7 +279,7 @@ _devbase() { '--context[Docker context]:context:' \ '1:name:_devbase_project_names' ;; - new) + create) _devbase_arguments 3 \ '1:repository:' \ '--plugin[Plugin to add the project to]:plugin:' \ @@ -452,7 +452,7 @@ _devbase() { uninstall|update|info) _devbase_plugin_names ;; - new) + create) _devbase_arguments 3 \ '1:repository:' \ '--name[Plugin name]:name:' \ @@ -461,7 +461,7 @@ _devbase() { ;; repo) case "$words[4]" in - new) + create) _devbase_arguments 4 \ '1:repository:' \ '--public[Make the repository public when it is created]' \ diff --git a/etc/devbase-completion.bash b/etc/devbase-completion.bash index 3a00c375..07112c51 100644 --- a/etc/devbase-completion.bash +++ b/etc/devbase-completion.bash @@ -42,16 +42,16 @@ _devbase_complete_flags() { } # 以下の _devbase_complete_* は引数を取らず、cur・prev・words・cword とフラグの一覧 -# (ctx_flags・ps_flags・logs_flags・open_flags・plugin_new_flags・project_new_flags) を _devbase_completions の local から読む。 +# (ctx_flags・ps_flags・logs_flags・open_flags・plugin_create_flags・project_create_flags) を _devbase_completions の local から読む。 # どの関数も最後の文を if / case にし、当たらないときも終了の状態を 0 に保つ。 # 位置 2: 1 語目ごとのサブコマンド・フラグ・プロジェクト名。 _devbase_complete_subcommands() { # project / container は同じサブコマンド群 (container は非推奨だが補完は維持)。 - local project_subcommands="up down ps login logs scale build rebuild list profile open post-start new" + local project_subcommands="up down ps login logs scale build rebuild list profile open post-start create" local container_subcommands="up down ps login logs scale build rebuild profile open" local env_subcommands="init sync list set get delete edit project export import keygen exec token encrypt decrypt rekey doctor backend" - local plugin_subcommands="list install uninstall update info sync repo new" + local plugin_subcommands="list install uninstall update info sync repo create" local snapshot_subcommands="create list restore copy delete rotate" case "$prev" in login) @@ -167,9 +167,9 @@ _devbase_complete_project_args() { post-start) _devbase_complete_flags "$ctx_flags" "$cur" names ;; - # new の引数は GitHub のリポジトリなので、プロジェクト名は出さない (#514) - new) - _devbase_complete_flags "$project_new_flags" "$cur" + # create の引数は GitHub のリポジトリなので、プロジェクト名は出さない (#514) + create) + _devbase_complete_flags "$project_create_flags" "$cur" ;; esac } @@ -228,7 +228,7 @@ _devbase_complete_env_args() { # plugin subcommand arguments _devbase_complete_plugin_args() { - local repo_subcommands="new add remove list refresh" + local repo_subcommands="create add remove list refresh" case "$prev" in list) COMPREPLY=($(compgen -W "--available" -- "$cur")) @@ -236,8 +236,8 @@ _devbase_complete_plugin_args() { install) _devbase_complete_flags "--link --all" "$cur" ;; - new) - _devbase_complete_flags "$plugin_new_flags" "$cur" + create) + _devbase_complete_flags "$plugin_create_flags" "$cur" ;; uninstall|update|info) local devbase_root @@ -302,8 +302,8 @@ _devbase_complete_project_flags() { up|down|rebuild|scale|post-start) _devbase_complete_flags "$ctx_flags" "$cur" ;; - new) - _devbase_complete_flags "$project_new_flags" "$cur" + create) + _devbase_complete_flags "$project_create_flags" "$cur" ;; esac } @@ -325,8 +325,8 @@ _devbase_complete_plugin_after_args() { if [ "${words[2]}" = "install" ]; then _devbase_complete_flags "--link --all" "$cur" fi - if [ "${words[2]}" = "new" ]; then - _devbase_complete_flags "$plugin_new_flags" "$cur" + if [ "${words[2]}" = "create" ]; then + _devbase_complete_flags "$plugin_create_flags" "$cur" fi # plugin repo subcommand arguments if [ "${words[2]}" = "repo" ]; then @@ -334,7 +334,7 @@ _devbase_complete_plugin_after_args() { add) _devbase_complete_flags "--name" "$cur" ;; - new) + create) _devbase_complete_flags "--public --yes" "$cur" ;; remove|refresh) @@ -375,8 +375,8 @@ _devbase_completions() { local ps_flags="--all -a --context" local logs_flags="--follow -f --tail --context" local open_flags="--open-index --context" - local plugin_new_flags="--name --public --yes" - local project_new_flags="--plugin --group --name --yes" + local plugin_create_flags="--name --public --yes" + local project_create_flags="--plugin --group --name --yes" # --context の値 (docker context の名前) は補完しない。 if [ "$prev" = "--context" ]; then diff --git a/lib/devbase/cli.py b/lib/devbase/cli.py index 84bf92eb..5e81b93c 100644 --- a/lib/devbase/cli.py +++ b/lib/devbase/cli.py @@ -58,14 +58,14 @@ # Subcommand map for prefix resolution: {(aliases...): [subcmds]} SUBCMD_MAP = { ('project',): ['up', 'down', 'ps', 'login', 'logs', 'scale', 'build', 'rebuild', 'list', - 'profile', 'open', 'post-start', 'new'], + 'profile', 'open', 'post-start', 'create'], ('container', 'ct'): ['up', 'down', 'ps', 'login', 'logs', 'scale', 'build', 'rebuild', 'profile', 'open'], ('env',): ['init', 'sync', 'list', 'set', 'get', 'delete', 'edit', 'project', 'keygen', 'exec', 'token', 'encrypt', 'decrypt', 'rekey', 'doctor', 'export', 'import', 'backend'], ('plugin', 'pl'): ['list', 'install', 'uninstall', 'update', 'info', 'sync', 'repo', 'migrate', - 'new'], + 'create'], ('snapshot', 'ss'): ['create', 'list', 'restore', 'copy', 'delete', 'rotate'], } @@ -346,16 +346,16 @@ def _add_project_parser(subparsers): # 取らない (wrapper の _PROJECT_NAME_SUBCOMMANDS にも含めない)。 _add_list_subparser(pj_sub) - # `new` はプラグインへプロジェクトを足す作成フロー (#514)。lifecycle ではなく、引数は + # `create` はプラグインへプロジェクトを足す作成フロー (#514)。lifecycle ではなく、引数は # GitHub のリポジトリなので wrapper の _PROJECT_NAME_SUBCOMMANDS には含めない。 - pj_new = pj_sub.add_parser( - 'new', help='Add a project for a GitHub repository to a plugin (does not start it)') - _add_new_target_arg(pj_new) - pj_new.add_argument('--plugin', default=None, help='Plugin to add the project to') - pj_new.add_argument('--group', default=None, help='Account group of the project') - pj_new.add_argument('--name', default=None, - help='Project name (default: the repository name)') - _add_yes_arg(pj_new) + pj_create = pj_sub.add_parser( + 'create', help='Add a project for a GitHub repository to a plugin (does not start it)') + _add_create_target_arg(pj_create) + pj_create.add_argument('--plugin', default=None, help='Plugin to add the project to') + pj_create.add_argument('--group', default=None, help='Account group of the project') + pj_create.add_argument('--name', default=None, + help='Project name (default: the repository name)') + _add_yes_arg(pj_create) # `migrate-config` は旧 env 形式から project.yml への変換 (PLAN32)。lifecycle # ではないため wrapper の _PROJECT_NAME_SUBCOMMANDS には含めない。 @@ -681,7 +681,7 @@ def _add_env_import_parser(env_sub): help='Keep only the last N backup directories (default: 10, 0 to disable)') -def _add_new_target_arg(parser): +def _add_create_target_arg(parser): """作成フロー (#514) の共通の引数。GitHub のリポジトリを 1 つ取る。""" parser.add_argument('repo', help='GitHub URL or owner/repo') @@ -723,25 +723,25 @@ def _add_plugin_parser(subparsers): pl_sub.add_parser('migrate', help='Migrate legacy plugins/ installs to repos/ clones') - p_new = pl_sub.add_parser( - 'new', help='Add a new plugin to a repository on GitHub and install it') - _add_new_target_arg(p_new) - p_new.add_argument('--name', default=None, - help='Plugin name (default: the repository name)') - p_new.add_argument('--public', action='store_true', - help='Make the repository public when it is created (default: private)') - _add_yes_arg(p_new) + p_create = pl_sub.add_parser( + 'create', help='Add a new plugin to a repository on GitHub and install it') + _add_create_target_arg(p_create) + p_create.add_argument('--name', default=None, + help='Plugin name (default: the repository name)') + p_create.add_argument('--public', action='store_true', + help='Make the repository public when it is created (default: private)') + _add_yes_arg(p_create) # Plugin repo sub-subcommands pl_repo = pl_sub.add_parser('repo', help='Manage plugin repositories') pl_repo_sub = pl_repo.add_subparsers(dest='repo_command') - r_new = pl_repo_sub.add_parser( - 'new', help='Create (if needed) and register a plugin repository on GitHub') - _add_new_target_arg(r_new) - r_new.add_argument('--public', action='store_true', - help='Make the repository public when it is created (default: private)') - _add_yes_arg(r_new) + r_create = pl_repo_sub.add_parser( + 'create', help='Create (if needed) and register a plugin repository on GitHub') + _add_create_target_arg(r_create) + r_create.add_argument('--public', action='store_true', + help='Make the repository public when it is created (default: private)') + _add_yes_arg(r_create) r_add = pl_repo_sub.add_parser('add', help='Register a repository') r_add.add_argument('url', help='Repository URL or GitHub shorthand') @@ -921,7 +921,7 @@ def _expand_argv(): commands = ['init', 'status', 'project', 'container', 'ct', 'env', 'plugin', 'pl', 'snapshot', 'ss', 'up', 'down', 'login', 'ps', 'scale', 'rebuild', 'open', 'list', 'help'] - repo_subcmds = ['new', 'add', 'remove', 'list', 'refresh'] + repo_subcmds = ['create', 'add', 'remove', 'list', 'refresh'] if len(sys.argv) >= 2 and not sys.argv[1].startswith('-'): sys.argv[1] = _resolve_prefix(sys.argv[1], commands, TOP_PREFIX_PREFERENCES) @@ -983,9 +983,9 @@ def main(): ('env', 'token'), # 作成フローの認証は利用者の gh の設定に任せる (#514 の決定 11)。機密の GH_TOKEN が # 環境変数に載ると、gh は利用者のログインではなくそのトークンで作成・マージする。 - ('project', 'new'), - ('plugin', 'new'), - ('plugin', 'repo new'), + ('project', 'create'), + ('plugin', 'create'), + ('plugin', 'repo create'), }) @@ -1034,7 +1034,7 @@ def _undeclared_current_project(root: Path) -> bool: def _injection_subcommand(args) -> Optional[str]: - """注入の判定に使うサブコマンド。``plugin repo new`` は ``repo new`` の形で渡す""" + """注入の判定に使うサブコマンド。``plugin repo create`` は ``repo create`` の形で渡す""" subcommand = getattr(args, 'subcommand', None) repo_command = getattr(args, 'repo_command', None) return f"{subcommand} {repo_command}" if repo_command else subcommand @@ -1144,10 +1144,10 @@ def _dispatch(cmd, args): from devbase.commands.project import cmd_project_list return cmd_project_list(devbase_root, args) # `project migrate-config` も lifecycle ではなく projects/ 全体の変換。 - if getattr(args, 'subcommand', None) == 'new': + if getattr(args, 'subcommand', None) == 'create': devbase_root = _require_devbase_root() - from devbase.commands.project import cmd_project_new - return cmd_project_new(devbase_root, args) + from devbase.commands.project import cmd_project_create + return cmd_project_create(devbase_root, args) if getattr(args, 'subcommand', None) == 'migrate-config': devbase_root = _require_devbase_root() from devbase.commands.project import cmd_project_migrate_config diff --git a/lib/devbase/commands/plugin.py b/lib/devbase/commands/plugin.py index 02b7f3da..3bf01b20 100644 --- a/lib/devbase/commands/plugin.py +++ b/lib/devbase/commands/plugin.py @@ -40,7 +40,7 @@ def cmd_plugin(devbase_root: Path, args) -> int: 'sync': lambda: cmd_sync(devbase_root), 'migrate': lambda: cmd_plugin_migrate(devbase_root), 'repo': lambda: cmd_repo(devbase_root, args), - 'new': lambda: cmd_plugin_new(devbase_root, args), + 'create': lambda: cmd_plugin_create(devbase_root, args), } handler = handlers.get(subcmd) @@ -200,8 +200,8 @@ def _confirmed() -> bool: return False -def cmd_plugin_new(devbase_root: Path, args) -> int: - """`plugin new`: リポジトリへプラグインを足して導入する""" +def cmd_plugin_create(devbase_root: Path, args) -> int: + """`plugin create`: リポジトリへプラグインを足して導入する""" registry = PluginRegistry(devbase_root) gh = GhClient() try: @@ -214,8 +214,8 @@ def cmd_plugin_new(devbase_root: Path, args) -> int: return 1 -def cmd_repo_new(devbase_root: Path, args) -> int: - """`plugin repo new`: プラグインリポジトリを用意して登録する""" +def cmd_repo_create(devbase_root: Path, args) -> int: + """`plugin repo create`: プラグインリポジトリを用意して登録する""" registry = PluginRegistry(devbase_root) gh = GhClient() try: @@ -233,11 +233,11 @@ def cmd_repo(devbase_root: Path, args) -> int: repo_cmd = getattr(args, 'repo_command', None) if not repo_cmd: - logger.error("Usage: devbase plugin repo ") + logger.error("Usage: devbase plugin repo ") return 1 - if repo_cmd == 'new': - return cmd_repo_new(devbase_root, args) + if repo_cmd == 'create': + return cmd_repo_create(devbase_root, args) handlers = { 'add': lambda: add_repository(registry, args.url, name=args.name), diff --git a/lib/devbase/commands/project.py b/lib/devbase/commands/project.py index 4dffefd7..2fd8445a 100644 --- a/lib/devbase/commands/project.py +++ b/lib/devbase/commands/project.py @@ -82,8 +82,8 @@ def ask(self, message: str) -> str | None: return None -def cmd_project_new(devbase_root: Path, args) -> int: - """`project new`: 入れ先のプラグインへプロジェクトを足し、手元へ反映する。 +def cmd_project_create(devbase_root: Path, args) -> int: + """`project create`: 入れ先のプラグインへプロジェクトを足し、手元へ反映する。 コンテナは起動しない (``devbase up`` は打たない)。 """ diff --git a/lib/devbase/plugin/creator.py b/lib/devbase/plugin/creator.py index 7a7d03fc..c5dd2b12 100644 --- a/lib/devbase/plugin/creator.py +++ b/lib/devbase/plugin/creator.py @@ -148,7 +148,7 @@ def _reject_stale_clone(registry: PluginRegistry, ref: GitHubRef) -> None: def plan_repo( registry: PluginRegistry, gh: GhClient, value: str, *, public: bool = False, ) -> CreationPlan: - """``plugin repo new`` の計画 (読むだけ)""" + """``plugin repo create`` の計画 (読むだけ)""" ref = GitHubRef.parse(value) gh.ensure_ready() registered = _find_registered(registry, ref.clone_url) @@ -214,7 +214,7 @@ def plan_plugin( registry: PluginRegistry, gh: GhClient, value: str, *, name: Optional[str] = None, public: bool = False, ) -> CreationPlan: - """``plugin new`` の計画 (読むだけ)。未登録ならリポジトリの分岐も計画に入る""" + """``plugin create`` の計画 (読むだけ)。未登録ならリポジトリの分岐も計画に入る""" ref = GitHubRef.parse(value) gh.ensure_ready() plugin = _checked_name(name or ref.repo, "プラグイン") @@ -344,7 +344,7 @@ def _decide_target( if not candidates: raise RepositoryError( "入れ先のプラグインがありません。push できるプラグインを導入するか、" - "devbase plugin new で足してください" + "devbase plugin create で足してください" ) if len(candidates) == 1: return candidates[0] @@ -417,7 +417,7 @@ def plan_project( plugin: Optional[str] = None, group: Optional[str] = None, name: Optional[str] = None, prompter: Optional[Prompter] = None, ) -> CreationPlan: - """``project new`` の計画 (読むだけ)""" + """``project create`` の計画 (読むだけ)""" ref = GitHubRef.parse(value) gh.ensure_ready() project = _project_name(name, ref.repo) @@ -461,7 +461,7 @@ def _reflect_repository(gh: GhClient, plan: CreationPlan) -> None: # プラグインの PR はまだ無いので、登録と導入ではなく打ち直しを案内する raise RepositoryError( f"{e}\nこの PR をマージした後に、同じコマンドを打ち直してください:\n" - f" devbase plugin new {plan.ref.clone_url} --name {plan.name}" + f" devbase plugin create {plan.ref.clone_url} --name {plan.name}" ) from e diff --git a/lib/devbase/plugin/publish.py b/lib/devbase/plugin/publish.py index 293692a0..eb3979bf 100644 --- a/lib/devbase/plugin/publish.py +++ b/lib/devbase/plugin/publish.py @@ -47,7 +47,7 @@ def branch_name(kind: str, name: str) -> str: if _BRANCH_UNSAFE.search(name): digest = hashlib.sha256(name.encode()).hexdigest()[:_BRANCH_DIGEST_LENGTH] name = f"{name.replace('.', '-')}-{digest}" - return f"devbase/new-{kind}-{name}" + return f"devbase/create-{kind}-{name}" def pr_title(kind: str, name: str) -> str: diff --git a/lib/devbase/tui/actions_plugin.py b/lib/devbase/tui/actions_plugin.py index 6e317a93..282ef97f 100644 --- a/lib/devbase/tui/actions_plugin.py +++ b/lib/devbase/tui/actions_plugin.py @@ -1,7 +1,7 @@ """plugin カテゴリの TUI 操作フロー (PLAN31_2 PR4)。 -``devbase plugin`` の全サブコマンド (list/install/uninstall/update/info/sync/migrate/new)、 -``plugin repo`` のサブコマンド (new/add/remove/list/refresh) と ``project new`` を、 +``devbase plugin`` の全サブコマンド (list/install/uninstall/update/info/sync/migrate/create)、 +``plugin repo`` のサブコマンド (create/add/remove/list/refresh) と ``project create`` を、 用途で分けた 2 階層のメニューから実行できるようにする (#514)。 引数は ``tui.menu`` の収集ヘルパで CLI parser と同じ属性値 (plan 2.3 契約表) を集め、 ``tui.dispatch.dispatch_group`` 経由で既存ハンドラ ``cmd_plugin`` へ委譲する @@ -30,7 +30,7 @@ # Enter 連打で安全な一覧表示へ到達できるようにする。 _PLUGIN_GROUPS: list[tuple[str, str]] = [ ("見る", "view"), - ("新規追加", "new"), + ("新規追加", "create"), ("導入・更新", "install-update"), ("削除", "remove"), ("保守", "maintain"), @@ -45,10 +45,10 @@ ("詳細表示 (info)", "info"), ("リポジトリ一覧 (repo list)", "repo-list"), ], - "new": [ - ("プロジェクト (project new)", "new-project"), - ("プラグイン (plugin new)", "new-plugin"), - ("リポジトリ (plugin repo new)", "new-repo"), + "create": [ + ("プロジェクト (project create)", "create-project"), + ("プラグイン (plugin create)", "create-plugin"), + ("リポジトリ (plugin repo create)", "create-repo"), ], "install-update": [ ("インストール (install)", "install"), @@ -270,7 +270,7 @@ def _confirm_plan(plan) -> None: flow.confirm_or_back("この計画で進めますか?") -def _op_new_repo(devbase_root: Path): +def _op_create_repo(devbase_root: Path): from devbase.plugin import creator repo = flow.need(menu.text(_NEW_REPOSITORY_PROMPT, allow_empty=False)) @@ -284,11 +284,11 @@ def _op_new_repo(devbase_root: Path): return 1 if not plan.noop_reason: _confirm_plan(plan) - return _dispatch(devbase_root, "repo", repo_command="new", + return _dispatch(devbase_root, "repo", repo_command="create", repo=repo, public=public, yes=True) -def _op_new_plugin(devbase_root: Path): +def _op_create_plugin(devbase_root: Path): from devbase.plugin import creator repo = flow.need(menu.text(_NEW_REPOSITORY_PROMPT, allow_empty=False)) @@ -300,7 +300,7 @@ def _op_new_plugin(devbase_root: Path): logger.error("%s", e) return 1 _confirm_plan(plan) - return _dispatch(devbase_root, "new", repo=repo, name=name, public=False, yes=True) + return _dispatch(devbase_root, "create", repo=repo, name=name, public=False, yes=True) def _select_target(candidates): @@ -312,8 +312,8 @@ def _select_target(candidates): f"入れ先のプラグインを選択 {menu.HINT_BACK}:", choices, back=True, search=False)) -def _op_new_project(devbase_root: Path): - from devbase.commands.project import cmd_project_new +def _op_create_project(devbase_root: Path): + from devbase.commands.project import cmd_project_create from devbase.plugin import creator from devbase.plugin.github import GitHubRef @@ -337,7 +337,7 @@ def _op_new_project(devbase_root: Path): logger.error("%s", e) return 1 _confirm_plan(plan) - return dispatch_group(cmd_project_new, devbase_root, "new", repo=repo, name=name, + return dispatch_group(cmd_project_create, devbase_root, "create", repo=repo, name=name, plugin=plugin, group=group, yes=True) @@ -352,9 +352,9 @@ def _op_new_project(devbase_root: Path): # sync / migrate は引数なし (plan 2.3: 属性なし)。即実行。 "sync": lambda root: _dispatch(root, "sync"), "migrate": lambda root: _dispatch(root, "migrate"), - "new-project": _op_new_project, - "new-plugin": _op_new_plugin, - "new-repo": _op_new_repo, + "create-project": _op_create_project, + "create-plugin": _op_create_plugin, + "create-repo": _op_create_repo, "repo-list": lambda root: _run_repo_operation(root, "list"), "repo-add": lambda root: _run_repo_operation(root, "add"), "repo-remove": lambda root: _run_repo_operation(root, "remove"), diff --git a/tests/cli/test_completion.py b/tests/cli/test_completion.py index ee7d36b4..6c06864b 100644 --- a/tests/cli/test_completion.py +++ b/tests/cli/test_completion.py @@ -213,11 +213,11 @@ def test_bash_open_completes_its_flags(fake_root, words, cword): assert set(_bash_complete(words, cword, fake_root)) == {"--open-index", "--context"} -def test_zsh_completion_mentions_new(): +def test_zsh_completion_mentions_create(): text = ZSH_COMPLETION.read_text() for flag in ("--plugin", "--group", "--public", "--yes"): assert f"'{flag}[" in text - assert "'new:" in text + assert "'create:" in text def test_zsh_completion_mentions_open(): @@ -288,7 +288,7 @@ def test_bash_context_value_is_not_completed(fake_root, words, cword): _CONTAINER_SUBCOMMANDS = ["up", "down", "ps", "login", "logs", "scale", "build", "rebuild", "profile", "open"] _ENV_SUBCOMMANDS = ["init", "sync", "list", "set", "get", "delete", "edit", "project", "export", "import", "keygen", "exec", "token", "encrypt", "decrypt", "rekey", "doctor", "backend"] -_PLUGIN_SUBCOMMANDS = ["list", "install", "uninstall", "update", "info", "sync", "repo", "new"] +_PLUGIN_SUBCOMMANDS = ["list", "install", "uninstall", "update", "info", "sync", "repo", "create"] _SNAPSHOT_SUBCOMMANDS = ["create", "list", "restore", "copy", "delete", "rotate"] @@ -360,11 +360,11 @@ def fake_root_with_plugins(fake_root): ("devbase plugin uninstall ''", 3, _PLUGINS), ("devbase pl update ''", 3, _PLUGINS), ("devbase plugin info ''", 3, _PLUGINS), - ("devbase plugin repo ''", 3, ["new", "add", "remove", "list", "refresh"]), - ("devbase plugin new '-'", 3, ["--name", "--public", "--yes"]), - ("devbase pl new ''", 3, []), - ("devbase project new '-'", 3, ["--plugin", "--group", "--name", "--yes"]), - ("devbase project new ''", 3, []), + ("devbase plugin repo ''", 3, ["create", "add", "remove", "list", "refresh"]), + ("devbase plugin create '-'", 3, ["--name", "--public", "--yes"]), + ("devbase pl create ''", 3, []), + ("devbase project create '-'", 3, ["--plugin", "--group", "--name", "--yes"]), + ("devbase project create ''", 3, []), # 位置 3: snapshot / ss ("devbase snapshot create '-'", 3, ["--name", "--full"]), ("devbase ss restore '-'", 3, ["--point"]), @@ -385,9 +385,9 @@ def fake_root_with_plugins(fake_root): ("devbase plugin install src '-'", 4, ["--link", "--all"]), ("devbase pl install src ''", 4, []), ("devbase plugin repo add '-'", 4, ["--name"]), - ("devbase plugin repo new '-'", 4, ["--public", "--yes"]), - ("devbase plugin new owner/repo '-'", 4, ["--name", "--public", "--yes"]), - ("devbase project new owner/repo '-'", 4, ["--plugin", "--group", "--name", "--yes"]), + ("devbase plugin repo create '-'", 4, ["--public", "--yes"]), + ("devbase plugin create owner/repo '-'", 4, ["--name", "--public", "--yes"]), + ("devbase project create owner/repo '-'", 4, ["--plugin", "--group", "--name", "--yes"]), ("devbase env set KEY '-'", 4, []), ]) def test_bash_completion_branches(fake_root_with_plugins, words, cword, expected): diff --git a/tests/cli/test_project_new_dispatch.py b/tests/cli/test_project_create_dispatch.py similarity index 68% rename from tests/cli/test_project_new_dispatch.py rename to tests/cli/test_project_create_dispatch.py index a023da1a..e6135d7b 100644 --- a/tests/cli/test_project_new_dispatch.py +++ b/tests/cli/test_project_create_dispatch.py @@ -1,4 +1,4 @@ -"""``devbase project new`` の入口のテスト (#514 の受け入れ条件 22)。""" +"""``devbase project create`` の入口のテスト (#514 の受け入れ条件 22)。""" from __future__ import annotations @@ -16,28 +16,28 @@ def test_wrapper_does_not_resolve_the_argument_as_a_project(exec_wrapper, target """同じ名前のプロジェクトがあっても、引数をプロジェクト名として解決しない。""" exec_wrapper.project("myapp") (exec_wrapper.root / "projects" / "owner").mkdir() - r = exec_wrapper(["project", "new", target]) + r = exec_wrapper(["project", "create", target]) assert "/projects/" not in stdout_field(r, "PWD:"), r.stdout - assert python_args(r) == f"project new {target}", r.stdout + assert python_args(r) == f"project create {target}", r.stdout -def test_new_is_in_the_prefix_map(): - assert "new" in cli.SUBCMD_MAP[("project",)] - assert "new" in cli.SUBCMD_MAP[("plugin", "pl")] +def test_create_is_in_the_prefix_map(): + assert "create" in cli.SUBCMD_MAP[("project",)] + assert "create" in cli.SUBCMD_MAP[("plugin", "pl")] -def test_prefix_resolves_to_new(monkeypatch): - monkeypatch.setattr(sys, "argv", ["devbase", "project", "n", "owner/repo"]) +def test_prefix_resolves_to_create(monkeypatch): + monkeypatch.setattr(sys, "argv", ["devbase", "project", "c", "owner/repo"]) cli._expand_argv() - assert sys.argv == ["devbase", "project", "new", "owner/repo"] + assert sys.argv == ["devbase", "project", "create", "owner/repo"] @pytest.mark.parametrize("argv", [ - ["project", "new", "owner/repo"], - ["plugin", "new", "owner/repo"], - ["pl", "new", "owner/repo"], - ["plugin", "repo", "new", "owner/repo"], - ["pl", "repo", "new", "owner/repo"], + ["project", "create", "owner/repo"], + ["plugin", "create", "owner/repo"], + ["pl", "create", "owner/repo"], + ["plugin", "repo", "create", "owner/repo"], + ["pl", "repo", "create", "owner/repo"], ]) def test_creation_flows_leave_gh_to_the_users_login(argv): """機密の GH_TOKEN が載ると、gh は利用者のログインではなくそのトークンで動く (決定 11)。""" @@ -57,7 +57,7 @@ def test_other_plugin_commands_still_inject(argv): def test_parser_arguments(): args = cli._create_parser().parse_args( - ["project", "new", "owner/repo", "--plugin", "p", "--group", "g", + ["project", "create", "owner/repo", "--plugin", "p", "--group", "g", "--name", "n", "--yes"]) assert (args.repo, args.plugin, args.group, args.name, args.yes) == ( "owner/repo", "p", "g", "n", True) @@ -73,9 +73,9 @@ def _fake(root, args): return 0 from devbase.commands import container, project - monkeypatch.setattr(project, "cmd_project_new", _fake) + monkeypatch.setattr(project, "cmd_project_create", _fake) monkeypatch.setattr(container, "cmd_project", lambda *_a: pytest.fail("lifecycle へ流れた")) - args = cli._create_parser().parse_args(["project", "new", "owner/repo"]) + args = cli._create_parser().parse_args(["project", "create", "owner/repo"]) assert cli._dispatch("project", args) == 0 assert seen == {"root": tmp_path, "repo": "owner/repo"} diff --git a/tests/cli/tui/test_actions_plugin.py b/tests/cli/tui/test_actions_plugin.py index ff8de263..b71b6ea3 100644 --- a/tests/cli/tui/test_actions_plugin.py +++ b/tests/cli/tui/test_actions_plugin.py @@ -198,7 +198,7 @@ def fake_select(message, choices, *, back, search): @pytest.mark.parametrize("group, values", [ ("view", ["list", "list-available", "info", "repo-list"]), - ("new", ["new-project", "new-plugin", "new-repo"]), + ("create", ["create-project", "create-plugin", "create-repo"]), ("install-update", ["install", "update", "repo-add", "repo-refresh"]), ("remove", ["uninstall", "repo-remove"]), ("maintain", ["sync", "migrate"]), @@ -263,7 +263,7 @@ def _spy(root, args): captured.update(vars(args)) return 0 - monkeypatch.setattr(project_mod, "cmd_project_new", _spy) + monkeypatch.setattr(project_mod, "cmd_project_create", _spy) return captured @@ -289,7 +289,7 @@ def _record(registry, gh, value, **kwargs): return calls -def test_new_repo_passes_values_with_yes(monkeypatch, tmp_path, creation, capsys): +def test_create_repo_passes_values_with_yes(monkeypatch, tmp_path, creation, capsys): from devbase.commands import plugin as plugin_mod captured = {} monkeypatch.setattr(plugin_mod, "cmd_plugin", @@ -297,14 +297,14 @@ def test_new_repo_passes_values_with_yes(monkeypatch, tmp_path, creation, capsys _texts(monkeypatch, "owner/repo") answers = _seq(True, True) monkeypatch.setattr(menu, "confirm", lambda *a, **k: answers()) - assert actions_plugin._run_operation(tmp_path, "new-repo") == 0 - assert captured == {"subcommand": "repo", "repo_command": "new", "repo": "owner/repo", + assert actions_plugin._run_operation(tmp_path, "create-repo") == 0 + assert captured == {"subcommand": "repo", "repo_command": "create", "repo": "owner/repo", "public": True, "yes": True} assert creation["repo"] == ("owner/repo", {"public": True}) assert "作成の計画" in capsys.readouterr().out -def test_new_repo_public_defaults_to_no(monkeypatch, tmp_path, creation): +def test_create_repo_public_defaults_to_no(monkeypatch, tmp_path, creation): _capture_dispatch(monkeypatch) _texts(monkeypatch, "owner/repo") defaults = [] @@ -314,11 +314,11 @@ def fake_confirm(message, *, default=False): return True monkeypatch.setattr(menu, "confirm", fake_confirm) - assert actions_plugin._run_operation(tmp_path, "new-repo") == 0 + assert actions_plugin._run_operation(tmp_path, "create-repo") == 0 assert defaults[0] is False -def test_new_repo_noop_skips_the_confirmation(monkeypatch, tmp_path): +def test_create_repo_noop_skips_the_confirmation(monkeypatch, tmp_path): from devbase.plugin import creator from devbase.plugin.github import GhClient monkeypatch.setattr(GhClient, "ensure_ready", lambda self: None) @@ -327,33 +327,33 @@ def test_new_repo_noop_skips_the_confirmation(monkeypatch, tmp_path): _texts(monkeypatch, "owner/repo") answers = [] monkeypatch.setattr(menu, "confirm", lambda *a, **k: answers.append(1) or False) - assert actions_plugin._run_operation(tmp_path, "new-repo") == 0 + assert actions_plugin._run_operation(tmp_path, "create-repo") == 0 assert len(answers) == 1, "公開の確認だけで、計画の確認は出さない" - assert captured["repo_command"] == "new" + assert captured["repo_command"] == "create" -def test_new_plugin_passes_values(monkeypatch, tmp_path, creation): +def test_create_plugin_passes_values(monkeypatch, tmp_path, creation): from devbase.commands import plugin as plugin_mod captured = {} monkeypatch.setattr(plugin_mod, "cmd_plugin", lambda root, args: captured.update(vars(args)) or 0) _texts(monkeypatch, "owner/repo", "team-a") monkeypatch.setattr(menu, "confirm", lambda *a, **k: True) - assert actions_plugin._run_operation(tmp_path, "new-plugin") == 0 - assert captured == {"subcommand": "new", "repo": "owner/repo", "name": "team-a", + assert actions_plugin._run_operation(tmp_path, "create-plugin") == 0 + assert captured == {"subcommand": "create", "repo": "owner/repo", "name": "team-a", "public": False, "yes": True} -def test_new_plugin_empty_name_is_none(monkeypatch, tmp_path, creation): +def test_create_plugin_empty_name_is_none(monkeypatch, tmp_path, creation): captured = _capture_dispatch(monkeypatch) _texts(monkeypatch, "owner/repo", "") monkeypatch.setattr(menu, "confirm", lambda *a, **k: True) - assert actions_plugin._run_operation(tmp_path, "new-plugin") == 0 + assert actions_plugin._run_operation(tmp_path, "create-plugin") == 0 assert captured["name"] is None assert creation["plugin"][1]["name"] is None -def test_new_project_single_candidate_shows_no_select(monkeypatch, tmp_path, creation): +def test_create_project_single_candidate_shows_no_select(monkeypatch, tmp_path, creation): captured = _capture_project(monkeypatch) prompts = [] @@ -364,15 +364,15 @@ def fake_text(message, *, default=None, allow_empty=True): monkeypatch.setattr(menu, "text", fake_text) monkeypatch.setattr(menu, "select", lambda *a, **k: pytest.fail("候補 1 件で選択を出した")) monkeypatch.setattr(menu, "confirm", lambda *a, **k: True) - assert actions_plugin._run_operation(tmp_path, "new-project") == 0 - assert captured == {"subcommand": "new", "repo": "owner/app", "name": "web", + assert actions_plugin._run_operation(tmp_path, "create-project") == 0 + assert captured == {"subcommand": "create", "repo": "owner/app", "name": "web", "plugin": "one", "group": "typed", "yes": True} assert prompts[2][1] == "acme", "グループは案を既定値にする" assert creation["project"] == ("owner/app", {"plugin": "one", "group": "typed", "name": "web"}) -def test_new_project_multiple_candidates_select(monkeypatch, tmp_path, creation): +def test_create_project_multiple_candidates_select(monkeypatch, tmp_path, creation): from devbase.plugin import creator monkeypatch.setattr(creator, "plugin_candidates", lambda *a: [_Target("one"), _Target("two")]) @@ -386,32 +386,32 @@ def fake_select(message, choices, *, back, search): monkeypatch.setattr(menu, "select", fake_select) monkeypatch.setattr(menu, "confirm", lambda *a, **k: True) - assert actions_plugin._run_operation(tmp_path, "new-project") == 0 + assert actions_plugin._run_operation(tmp_path, "create-project") == 0 assert offered == {"values": ["one", "two"], "back": True} assert captured["plugin"] == "two" assert captured["name"] is None -def test_new_project_without_candidates_reports(monkeypatch, tmp_path, creation, caplog): +def test_create_project_without_candidates_reports(monkeypatch, tmp_path, creation, caplog): from devbase.plugin import creator monkeypatch.setattr(creator, "plugin_candidates", lambda *a: []) captured = _capture_project(monkeypatch) _texts(monkeypatch, "owner/app", "") - assert actions_plugin._run_operation(tmp_path, "new-project") == 1 + assert actions_plugin._run_operation(tmp_path, "create-project") == 1 assert captured == {} assert "入れ先" in caplog.text -@pytest.mark.parametrize("op", ["new-project", "new-plugin", "new-repo"]) -def test_new_esc_at_the_repository_goes_back(monkeypatch, tmp_path, creation, op): +@pytest.mark.parametrize("op", ["create-project", "create-plugin", "create-repo"]) +def test_create_esc_at_the_repository_goes_back(monkeypatch, tmp_path, creation, op): called = _no_dispatch(monkeypatch) monkeypatch.setattr(menu, "text", lambda *a, **k: menu.MENU_BACK) assert actions_plugin._run_operation(tmp_path, op) is actions_plugin._ARG_CANCEL assert called == [] -@pytest.mark.parametrize("op", ["new-project", "new-plugin", "new-repo"]) -def test_new_ctrl_c_at_the_repository_aborts(monkeypatch, tmp_path, creation, op): +@pytest.mark.parametrize("op", ["create-project", "create-plugin", "create-repo"]) +def test_create_ctrl_c_at_the_repository_aborts(monkeypatch, tmp_path, creation, op): called = _no_dispatch(monkeypatch) monkeypatch.setattr(menu, "text", lambda *a, **k: None) assert actions_plugin._run_operation(tmp_path, op) is None @@ -423,18 +423,18 @@ def test_new_ctrl_c_at_the_repository_aborts(monkeypatch, tmp_path, creation, op (menu.MENU_BACK, actions_plugin._ARG_CANCEL), (None, None), ]) -def test_new_plan_confirmation_refused(monkeypatch, tmp_path, creation, answer, expected): +def test_create_plan_confirmation_refused(monkeypatch, tmp_path, creation, answer, expected): called = _no_dispatch(monkeypatch) captured = _capture_project(monkeypatch) _texts(monkeypatch, "owner/app", "", "acme") monkeypatch.setattr(menu, "confirm", lambda *a, **k: answer) - assert actions_plugin._run_operation(tmp_path, "new-project") is expected + assert actions_plugin._run_operation(tmp_path, "create-project") is expected assert called == [] assert captured == {} @pytest.mark.parametrize("step", ["select", "group"]) -def test_new_project_esc_in_the_middle_goes_back(monkeypatch, tmp_path, creation, step): +def test_create_project_esc_in_the_middle_goes_back(monkeypatch, tmp_path, creation, step): from devbase.plugin import creator monkeypatch.setattr(creator, "plugin_candidates", lambda *a: [_Target("one"), _Target("two")]) @@ -445,11 +445,11 @@ def test_new_project_esc_in_the_middle_goes_back(monkeypatch, tmp_path, creation else: _texts(monkeypatch, "owner/app", "", menu.MENU_BACK) monkeypatch.setattr(menu, "select", lambda *a, **k: "one") - assert actions_plugin._run_operation(tmp_path, "new-project") is actions_plugin._ARG_CANCEL + assert actions_plugin._run_operation(tmp_path, "create-project") is actions_plugin._ARG_CANCEL assert captured == {} -def test_new_plan_error_is_reported_with_rc_1(monkeypatch, tmp_path, creation, caplog): +def test_create_plan_error_is_reported_with_rc_1(monkeypatch, tmp_path, creation, caplog): from devbase.errors import RepositoryError from devbase.plugin import creator @@ -459,7 +459,7 @@ def _boom(*_a, **_k): monkeypatch.setattr(creator, "plan_plugin", _boom) called = _no_dispatch(monkeypatch) _texts(monkeypatch, "owner/repo", "") - assert actions_plugin._run_operation(tmp_path, "new-plugin") == 1 + assert actions_plugin._run_operation(tmp_path, "create-plugin") == 1 assert called == [] assert "push する権限がありません" in caplog.text diff --git a/tests/plugin/test_create_plugin.py b/tests/plugin/test_create_plugin.py index efc61ec8..1fa590f8 100644 --- a/tests/plugin/test_create_plugin.py +++ b/tests/plugin/test_create_plugin.py @@ -1,4 +1,4 @@ -"""``devbase plugin new`` のテスト (#514 の受け入れ条件 6〜8・16・17、決定 8・9)。""" +"""``devbase plugin create`` のテスト (#514 の受け入れ条件 6〜8・16・17、決定 8・9)。""" from __future__ import annotations @@ -45,7 +45,7 @@ def _assert_installed(root, name="team-a", source=URL): @pytest.mark.parametrize("name", ["app..web", "app.", "app.lock"]) def test_name_outside_branch_rules_is_installed(github, root, registered, run_cli, name): - assert run_cli("plugin", "new", FULL, "--name", name, "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--name", name, "--yes") == 0 assert github.prs()[0]["state"] == "MERGED" assert name in _registry_names(github) @@ -53,9 +53,9 @@ def test_name_outside_branch_rules_is_installed(github, root, registered, run_cl def test_registered_repo_gets_a_plugin(github, root, registered, run_cli, capsys): - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 0 pr = github.prs()[0] - assert pr["head"] == "devbase/new-plugin-team-a" + assert pr["head"] == "devbase/create-plugin-team-a" assert pr["state"] == "MERGED" assert github.file(FULL, "team-a/plugin.yml") is not None assert github.file(FULL, "team-a/projects/.gitkeep") is not None @@ -70,14 +70,14 @@ def test_registered_repo_gets_a_plugin(github, root, registered, run_cli, capsys def test_default_name_is_the_repo_name(github, root, registered, run_cli): - assert run_cli("plugin", "new", FULL, "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--yes") == 0 _assert_installed(root, "repo") @pytest.mark.parametrize("prepare, first_pushes, first_titles", [ ("absent", ["refs/heads/main"], ["devbase: repo repo を足す"]), ("empty", ["refs/heads/main"], ["devbase: repo repo を足す"]), - ("no-registry", ["refs/heads/devbase/new-repo-repo"], ["seed", "devbase: repo repo を足す"]), + ("no-registry", ["refs/heads/devbase/create-repo-repo"], ["seed", "devbase: repo repo を足す"]), ("registry", [], ["seed"]), ]) def test_unregistered_goes_through_the_repo_branch_first( @@ -90,9 +90,9 @@ def test_unregistered_goes_through_the_repo_branch_first( elif prepare == "registry": github.add_repo(FULL, {"registry.yml": REGISTRY}) - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 0 - assert github.pushed_refs(FULL) == [*first_pushes, "refs/heads/devbase/new-plugin-team-a"] + assert github.pushed_refs(FULL) == [*first_pushes, "refs/heads/devbase/create-plugin-team-a"] assert github.subjects(FULL) == [*first_titles, "devbase: plugin team-a を足す"], \ "リポジトリの分岐 → プラグインの PR の順に別の変更で入る (決定 8)" _assert_installed(root) @@ -100,12 +100,12 @@ def test_unregistered_goes_through_the_repo_branch_first( def test_absent_is_private_unless_public(github, root, run_cli): github.add_org("owner", role="admin") - assert run_cli("plugin", "new", FULL, "--public", "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--public", "--yes") == 0 assert github.state()["repos"][FULL]["visibility"] == "public" def test_public_does_not_change_an_existing_repo(github, root, registered, run_cli): - assert run_cli("plugin", "new", FULL, "--public", "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--public", "--yes") == 0 assert [c for c in github.write_calls() if c[:2] == ["repo", "create"]] == [] @@ -115,7 +115,7 @@ def test_repo_branch_that_ends_writes_nothing(github, root, run_cli, setup): github.add_repo(FULL, {"README.md": "x\n"}, permission="READ") else: github.add_org("owner", role="member", state="pending") - assert run_cli("plugin", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "create", FULL, "--yes") == 1 assert github.write_calls() == [] assert _plugins_yml(root) is None @@ -123,7 +123,7 @@ def test_repo_branch_that_ends_writes_nothing(github, root, run_cli, setup): def test_duplicate_in_registry_changes_nothing(github, root, run_cli, caplog): text = "name: repo\nplugins:\n - name: team-a\n path: other\n" github.add_repo(FULL, {"registry.yml": text}) - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 1 assert github.write_calls() == [] assert _plugins_yml(root) is None assert "team-a" in caplog.text @@ -131,7 +131,7 @@ def test_duplicate_in_registry_changes_nothing(github, root, run_cli, caplog): def test_duplicate_directory_changes_nothing(github, root, run_cli): github.add_repo(FULL, {"registry.yml": REGISTRY, "team-a/README.md": "x\n"}) - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 1 assert github.write_calls() == [] @@ -146,14 +146,14 @@ def test_duplicate_installed_name_changes_nothing(github, root, registered, run_ from devbase.plugin.installer import install_plugin install_plugin(registry, f"https://github.com/{other}.git:team-a") before = _plugins_yml(root) - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 1 assert _plugins_yml(root) == before assert github.write_calls() == [] @pytest.mark.parametrize("name", ["../up", "a/b", "-x", ".hidden", "a b"]) def test_bad_name_form_stops_before_gh_writes(github, root, registered, run_cli, name): - assert run_cli("plugin", "new", FULL, f"--name={name}", "--yes") == 1 + assert run_cli("plugin", "create", FULL, f"--name={name}", "--yes") == 1 assert github.write_calls() == [] @@ -166,13 +166,13 @@ def test_url_form_difference_uses_the_registered_path( github, root, run_cli, registered_url, value): github.add_repo(FULL, {"registry.yml": REGISTRY}) add_repository(PluginRegistry(root), registered_url) - assert run_cli("plugin", "new", value, "--name", "team-a", "--yes") == 0 + assert run_cli("plugin", "create", value, "--name", "team-a", "--yes") == 0 urls = [r.url for r in PluginRegistry(root).list_repositories()] assert urls == [registered_url], "plugins.yml の url は変わらない" _assert_installed(root, source=registered_url) - # 同じ入力の repo new は何もしない + # 同じ入力の repo create は何もしない calls = len(github.write_calls()) - assert run_cli("plugin", "repo", "new", value) == 0 + assert run_cli("plugin", "repo", "create", value) == 0 assert len(github.write_calls()) == calls @@ -183,18 +183,18 @@ def test_registration_without_clone_stops_before_writing(github, root, run_cli, PluginRegistry(root).add_repository(RegisteredRepository( name="r", url=URL, local_path=local_path)) before = _plugins_yml(root) - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 1 assert github.write_calls() == [] assert _plugins_yml(root) == before assert "plugin repo remove r" in caplog.text assert f"plugin repo add {URL}" in caplog.text - # 同じ登録へ repo new は何もせず 0 - assert run_cli("plugin", "repo", "new", FULL) == 0 + # 同じ登録へ repo create は何もせず 0 + assert run_cli("plugin", "repo", "create", FULL) == 0 def test_uncommitted_changes_survive(github, root, registered, run_cli): (registered / "note.txt").write_text("mine\n") - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 0 assert (registered / "note.txt").read_text() == "mine\n" status = subprocess.run(["git", "status", "--porcelain"], cwd=registered, check=True, capture_output=True, text=True).stdout @@ -205,7 +205,7 @@ def test_colliding_change_stops_and_is_kept(github, root, registered, run_cli, c edited = REGISTRY + "# 手元の編集\n" (registered / "registry.yml").write_text(edited) before = _plugins_yml(root) - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 1 assert (registered / "registry.yml").read_text() == edited assert _plugins_yml(root) == before assert "git -C" in caplog.text @@ -218,7 +218,7 @@ def test_diverged_clone_stops_with_commands(github, root, registered, run_cli, c head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=registered, check=True, capture_output=True, text=True).stdout github.commit(FULL, {"other.txt": "x\n"}) - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 1 assert _plugins_yml(root) == before assert subprocess.run(["git", "rev-parse", "HEAD"], cwd=registered, check=True, capture_output=True, text=True).stdout == head @@ -233,7 +233,7 @@ def test_merge_failure_keeps_plugins_yml(github, root, run_cli, caplog, prepare) if prepare == "registered": add_repository(PluginRegistry(root), URL) before = _plugins_yml(root) - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 1 assert _plugins_yml(root) == before assert github.prs()[0]["url"] in caplog.text assert "devbase plugin install" in caplog.text @@ -243,10 +243,10 @@ def test_merge_failure_keeps_plugins_yml(github, root, run_cli, caplog, prepare) def test_registry_pr_merge_failure_asks_to_rerun(github, root, run_cli, caplog): """プラグインの PR がまだ無いので、登録と導入ではなく打ち直しを案内する。""" github.add_repo(FULL, {"README.md": "x\n"}, merge_error="required reviews") - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 1 - assert [pr["head"] for pr in github.prs()] == ["devbase/new-repo-repo"] + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 1 + assert [pr["head"] for pr in github.prs()] == ["devbase/create-repo-repo"] assert github.prs()[0]["url"] in caplog.text - assert f"devbase plugin new {URL} --name team-a" in caplog.text + assert f"devbase plugin create {URL} --name team-a" in caplog.text assert "devbase plugin install" not in caplog.text assert "devbase plugin repo add" not in caplog.text assert _plugins_yml(root) is None @@ -258,7 +258,7 @@ def test_ssh_registration_clones_and_pushes_over_ssh(github, root, run_cli): github.add_repo(FULL, {"registry.yml": REGISTRY}) add_repository(PluginRegistry(root), url) github.ssh_only() - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 0 _assert_installed(root, source=url) @@ -279,7 +279,7 @@ def test_rename_in_the_pulled_update_keeps_the_project(github, root, run_cli): "moved/plugin.yml": "name: moved\nversion: '1.0.0'\n", "moved/projects/p1/compose.yml": "services: {}\n", }, remove=["old"]) - assert run_cli("plugin", "new", FULL, "--name", "team-a", "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--name", "team-a", "--yes") == 0 registry = PluginRegistry(root) assert registry.get("old") is None @@ -288,14 +288,14 @@ def test_rename_in_the_pulled_update_keeps_the_project(github, root, run_cli): def test_never_touches_docker(github, root, registered, run_cli): - assert run_cli("plugin", "new", FULL, "--yes") == 0 + assert run_cli("plugin", "create", FULL, "--yes") == 0 assert github.docker_calls() == [] -def test_prefix_of_new_resolves(github, root, registered, run_cli): - assert run_cli("pl", "n", FULL, "--yes") == 0 +def test_prefix_of_create_resolves(github, root, registered, run_cli): + assert run_cli("pl", "c", FULL, "--yes") == 0 def test_no_tty_without_yes_stops(github, root, registered, run_cli): - assert run_cli("plugin", "new", FULL) == 1 + assert run_cli("plugin", "create", FULL) == 1 assert github.write_calls() == [] diff --git a/tests/plugin/test_create_project.py b/tests/plugin/test_create_project.py index ad690a0d..af20f347 100644 --- a/tests/plugin/test_create_project.py +++ b/tests/plugin/test_create_project.py @@ -1,4 +1,4 @@ -"""``devbase project new`` のテスト (#514 の受け入れ条件 9〜13)。""" +"""``devbase project create`` のテスト (#514 の受け入れ条件 9〜13)。""" from __future__ import annotations @@ -52,7 +52,7 @@ def app(github): def test_name_outside_docker_rules_gets_a_valid_image(github, root, app, run_cli): clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", APP, "--name", "app-", "--yes") == 0 + assert run_cli("project", "create", APP, "--name", "app-", "--yes") == 0 compose = yaml.safe_load((clone / "team-a/projects/app-/compose.yml").read_text()) assert compose["services"]["dev"]["image"] == "app:latest" @@ -66,7 +66,7 @@ def test_name_outside_docker_rules_gets_a_valid_image(github, root, app, run_cli def test_default_name_follows_compose_rules(github, root, run_cli, repo, project): github.add_repo(f"owner/{repo}", {"README.md": "x\n"}, permission="READ") clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", f"owner/{repo}", "--yes") == 0 + assert run_cli("project", "create", f"owner/{repo}", "--yes") == 0 assert (clone / f"team-a/projects/{project}/project.yml").is_file() assert (root / "projects" / project).exists() @@ -78,7 +78,7 @@ def test_name_outside_compose_rules_stops_before_writing( github, root, app, run_cli, caplog, name): clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) before = _plugins_yml(root) - assert run_cli("project", "new", APP, "--name", name, "--yes") == 1 + assert run_cli("project", "create", APP, "--name", name, "--yes") == 1 assert "小文字の英数字で始まり" in caplog.text assert github.write_calls() == [] @@ -88,10 +88,10 @@ def test_name_outside_compose_rules_stops_before_writing( def test_project_is_added_and_reflected(github, root, app, run_cli): clone = _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", APP, "--yes") == 0 + assert run_cli("project", "create", APP, "--yes") == 0 pr = github.prs()[0] - assert pr["head"] == "devbase/new-project-app" + assert pr["head"] == "devbase/create-project-app" assert pr["state"] == "MERGED" base = "team-a/projects/app" full = "owner/plugins" @@ -109,7 +109,7 @@ def test_project_is_added_and_reflected(github, root, app, run_cli): def test_name_option(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", APP, "--name", "web", "--yes") == 0 + assert run_cli("project", "create", APP, "--name", "web", "--yes") == 0 assert (root / "projects" / "web").is_dir() assert not (root / "projects" / "app").exists() assert github.file("owner/plugins", "team-a/projects/web/project.yml") is not None @@ -117,7 +117,7 @@ def test_name_option(github, root, app, run_cli): def test_plan_shows_target_and_group(github, root, app, run_cli, capsys): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", APP) == 1, "TTY が無く --yes も無い" + assert run_cli("project", "create", APP) == 1, "TTY が無く --yes も無い" out = capsys.readouterr().out assert "team-a" in out and "acme" in out and "owner/plugins" in out and "main" in out assert github.write_calls() == [] @@ -129,34 +129,34 @@ def test_plan_shows_target_and_group(github, root, app, run_cli, capsys): def test_plugin_option_wins(github, root, app, run_cli): _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"]) _plugin_repo(github, root, "owner/two", plugin="two", groups=["acme"]) - assert run_cli("project", "new", APP, "--plugin", "two", "--yes") == 0 + assert run_cli("project", "create", APP, "--plugin", "two", "--yes") == 0 assert github.file("owner/two", "two/projects/app/env") is not None def test_plugin_option_requires_install(github, root, app, run_cli, caplog): _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"], install=False) - assert run_cli("project", "new", APP, "--plugin", "one", "--yes") == 1 + assert run_cli("project", "create", APP, "--plugin", "one", "--yes") == 1 assert "one" in caplog.text assert github.write_calls() == [] def test_plugin_option_requires_push(github, root, app, run_cli): _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"], permission="READ") - assert run_cli("project", "new", APP, "--plugin", "one", "--yes") == 1 + assert run_cli("project", "create", APP, "--plugin", "one", "--yes") == 1 assert github.write_calls() == [] def test_same_owner_narrows_the_candidates(github, root, app, run_cli): _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"]) _plugin_repo(github, root, "other/two", plugin="two", groups=["acme"]) - assert run_cli("project", "new", APP, "--yes") == 0 + assert run_cli("project", "create", APP, "--yes") == 0 assert github.file("owner/one", "one/projects/app/env") is not None def test_no_same_owner_keeps_all_candidates(github, root, app, run_cli, caplog): _plugin_repo(github, root, "other/one", plugin="one", groups=["acme"]) _plugin_repo(github, root, "other/two", plugin="two", groups=["acme"]) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert "one" in caplog.text and "two" in caplog.text assert github.write_calls() == [] @@ -164,26 +164,26 @@ def test_no_same_owner_keeps_all_candidates(github, root, app, run_cli, caplog): def test_unpushable_are_not_candidates(github, root, app, run_cli): _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"], permission="READ") _plugin_repo(github, root, "other/two", plugin="two", groups=["acme"]) - assert run_cli("project", "new", APP, "--yes") == 0 + assert run_cli("project", "create", APP, "--yes") == 0 assert github.file("other/two", "two/projects/app/env") is not None def test_multiple_with_tty_asks(github, root, app, run_cli): _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"]) _plugin_repo(github, root, "owner/two", plugin="two", groups=["acme"]) - assert run_cli("project", "new", APP, "--yes", tty=True, answers=["2"]) == 0 + assert run_cli("project", "create", APP, "--yes", tty=True, answers=["2"]) == 0 assert github.file("owner/two", "two/projects/app/env") is not None def test_multiple_with_tty_bad_answer_stops(github, root, app, run_cli): _plugin_repo(github, root, "owner/one", plugin="one", groups=["acme"]) _plugin_repo(github, root, "owner/two", plugin="two", groups=["acme"]) - assert run_cli("project", "new", APP, "--yes", tty=True, answers=["9"]) == 1 + assert run_cli("project", "create", APP, "--yes", tty=True, answers=["9"]) == 1 assert github.write_calls() == [] def test_zero_candidates_stops(github, root, app, run_cli): - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] @@ -239,14 +239,14 @@ def test_gh_is_called_once_per_repository(github, root, app): ]) def test_group_is_the_most_common(github, root, app, run_cli, groups, expected): _plugin_repo(github, root, "owner/plugins", groups=groups) - assert run_cli("project", "new", APP, "--yes") == 0 + assert run_cli("project", "create", APP, "--yes") == 0 assert github.file("owner/plugins", "team-a/projects/app/env") \ == f"DEVBASE_ACCOUNT_GROUP={expected}\n" def test_group_option_wins(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme", "acme"]) - assert run_cli("project", "new", APP, "--group", "mine", "--yes") == 0 + assert run_cli("project", "create", APP, "--group", "mine", "--yes") == 0 assert github.file("owner/plugins", "team-a/projects/app/env") \ == "DEVBASE_ACCOUNT_GROUP=mine\n" @@ -254,14 +254,14 @@ def test_group_option_wins(github, root, app, run_cli): @pytest.mark.parametrize("groups", [["a", "b"], []], ids=["tie", "none"]) def test_undecided_group_without_tty_stops(github, root, app, run_cli, groups): _plugin_repo(github, root, "owner/plugins", groups=groups) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] @pytest.mark.parametrize("groups", [["a", "b"], []], ids=["tie", "none"]) def test_undecided_group_with_tty_asks(github, root, app, run_cli, groups): _plugin_repo(github, root, "owner/plugins", groups=groups) - assert run_cli("project", "new", APP, "--yes", tty=True, answers=["typed"]) == 0 + assert run_cli("project", "create", APP, "--yes", tty=True, answers=["typed"]) == 0 assert github.file("owner/plugins", "team-a/projects/app/env") \ == "DEVBASE_ACCOUNT_GROUP=typed\n" @@ -269,19 +269,19 @@ def test_undecided_group_with_tty_asks(github, root, app, run_cli, groups): @pytest.mark.parametrize("bad", ["default", "ubuntu", "123", "a b"]) def test_bad_group_from_option_stops(github, root, app, run_cli, bad): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", APP, f"--group={bad}", "--yes") == 1 + assert run_cli("project", "create", APP, f"--group={bad}", "--yes") == 1 assert github.write_calls() == [] def test_bad_group_from_most_common_stops(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["default"]) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] def test_bad_group_from_tty_stops(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins") - assert run_cli("project", "new", APP, "--yes", tty=True, answers=["default"]) == 1 + assert run_cli("project", "create", APP, "--yes", tty=True, answers=["default"]) == 1 assert github.write_calls() == [] @@ -290,35 +290,35 @@ def test_bad_group_from_tty_stops(github, root, app, run_cli): def test_unreadable_target_stops(github, root, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] def test_existing_in_projects_stops(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) (root / "projects" / "app").mkdir() - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] def test_broken_symlink_in_projects_stops(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) (root / "projects" / "app").symlink_to("../gone") - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] def test_existing_in_the_plugin_stops(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) github.commit("owner/plugins", {"team-a/projects/app/project.yml": "version: 1\n"}) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] @pytest.mark.parametrize("name", ["../up", "a/b", "-x"]) def test_bad_name_stops(github, root, app, run_cli, name): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", APP, f"--name={name}", "--yes") == 1 + assert run_cli("project", "create", APP, f"--name={name}", "--yes") == 1 assert github.write_calls() == [] @@ -335,7 +335,7 @@ def test_registration_without_clone_stops(github, root, app, run_cli, caplog, st else: shutil.rmtree(clone) before = _plugins_yml(root) - assert run_cli("project", "new", APP, "--plugin", "team-a", "--yes") == 1 + assert run_cli("project", "create", APP, "--plugin", "team-a", "--yes") == 1 assert github.write_calls() == [] assert _plugins_yml(root) == before assert "plugin repo remove" in caplog.text @@ -346,7 +346,7 @@ def test_merge_failure_leaves_the_local_side(github, root, app, run_cli, caplog) _plugin_repo(github, root, "owner/plugins", groups=["acme"], merge_error="required reviews") before = _plugins_yml(root) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert _plugins_yml(root) == before assert not (root / "projects" / "app").exists() assert github.prs()[0]["url"] in caplog.text @@ -361,19 +361,19 @@ def test_stale_plugin_path_stops_before_writing(github, root, app, run_cli, capl _plugin_repo(github, root, "owner/plugins", groups=["acme"]) github.commit("owner/plugins", {"registry.yml": MOVED_REGISTRY, "moved/plugin.yml": "name: team-a\nversion: '1.0.0'\n"}) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] assert "devbase plugin repo refresh plugins" in caplog.text assert run_cli("plugin", "repo", "refresh", "plugins") == 0 - assert run_cli("project", "new", APP, "--group", "acme", "--yes") == 0 + assert run_cli("project", "create", APP, "--group", "acme", "--yes") == 0 assert github.file("owner/plugins", "moved/projects/app/project.yml") is not None def test_plugin_gone_from_the_registry_stops(github, root, app, run_cli, caplog): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) github.commit("owner/plugins", {"registry.yml": "name: plugins\nplugins: []\n"}) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] assert "項目なし" in caplog.text @@ -398,7 +398,7 @@ def _root_plugin_repo(github, root, full="owner/plugins"): def test_plugin_at_the_repository_root(github, root, app, run_cli): """path の無い項目は導入と同じく直下として扱い、projects/ へ現れる。""" clone = _root_plugin_repo(github, root) - assert run_cli("project", "new", APP, "--group", "acme", "--yes") == 0 + assert run_cli("project", "create", APP, "--group", "acme", "--yes") == 0 assert github.file("owner/plugins", "projects/app/project.yml") is not None assert github.file("owner/plugins", "team-a/projects/app/project.yml") is None assert (clone / "projects" / "app" / "project.yml").is_file() @@ -409,14 +409,14 @@ def test_group_comes_from_the_repository_root(github, root, app, run_cli): clone = _root_plugin_repo(github, root) (clone / "projects" / "p0").mkdir() (clone / "projects" / "p0" / "env").write_text("DEVBASE_ACCOUNT_GROUP=acme\n") - assert run_cli("project", "new", APP, "--yes") == 0 + assert run_cli("project", "create", APP, "--yes") == 0 assert github.file("owner/plugins", "projects/app/env") == "DEVBASE_ACCOUNT_GROUP=acme\n" def test_plugin_moved_from_the_root_stops(github, root, app, run_cli, caplog): _root_plugin_repo(github, root) github.commit("owner/plugins", {"registry.yml": MOVED_REGISTRY}) - assert run_cli("project", "new", APP, "--group", "acme", "--yes") == 1 + assert run_cli("project", "create", APP, "--group", "acme", "--yes") == 1 assert github.write_calls() == [] assert "リポジトリの直下" in caplog.text @@ -426,7 +426,7 @@ def test_moved_default_branch_stops_before_writing(github, root, app, run_cli, c _plugin_repo(github, root, "owner/plugins", groups=["acme"]) github.set_default_branch("owner/plugins", "develop") before = _plugins_yml(root) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert github.write_calls() == [] assert _plugins_yml(root) == before assert "既定ブランチ develop" in caplog.text @@ -439,28 +439,28 @@ def test_clone_on_the_new_default_branch_completes(github, root, app, run_cli): github.set_default_branch("owner/plugins", "develop") subprocess.run(["git", "fetch", "origin"], cwd=clone, check=True, capture_output=True) subprocess.run(["git", "switch", "develop"], cwd=clone, check=True, capture_output=True) - assert run_cli("project", "new", APP, "--yes") == 0 + assert run_cli("project", "create", APP, "--yes") == 0 assert (root / "projects" / "app" / "project.yml").is_file() def test_tty_decline_changes_nothing(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", APP, tty=True, answers=["n"]) == 1 + assert run_cli("project", "create", APP, tty=True, answers=["n"]) == 1 assert github.write_calls() == [] def test_unauthenticated(github, root, app, run_cli, caplog): github.update(authed=False) - assert run_cli("project", "new", APP, "--yes") == 1 + assert run_cli("project", "create", APP, "--yes") == 1 assert "gh auth login" in caplog.text def test_non_github_url_stops(github, root, run_cli): - assert run_cli("project", "new", "https://gitlab.com/owner/app", "--yes") == 1 + assert run_cli("project", "create", "https://gitlab.com/owner/app", "--yes") == 1 assert github.calls() == [] def test_never_touches_docker(github, root, app, run_cli): _plugin_repo(github, root, "owner/plugins", groups=["acme"]) - assert run_cli("project", "new", APP, "--yes") == 0 + assert run_cli("project", "create", APP, "--yes") == 0 assert github.docker_calls() == [] diff --git a/tests/plugin/test_create_repo.py b/tests/plugin/test_create_repo.py index 42474300..e1a4f1e8 100644 --- a/tests/plugin/test_create_repo.py +++ b/tests/plugin/test_create_repo.py @@ -1,4 +1,4 @@ -"""``devbase plugin repo new`` のテスト (#514 の受け入れ条件 1〜5・14・15・17)。""" +"""``devbase plugin repo create`` のテスト (#514 の受け入れ条件 1〜5・14・15・17)。""" from __future__ import annotations @@ -32,7 +32,7 @@ def _visibility(github): def test_absent_repo_is_created_private_and_registered(github, root, run_cli): github.add_org("owner", role="admin") - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 0 assert _visibility(github) == "private" assert yaml.safe_load(github.file(FULL, "registry.yml")) == { "name": "repo", "description": "", "plugins": []} @@ -46,13 +46,13 @@ def test_absent_repo_is_created_private_and_registered(github, root, run_cli): def test_public_flag_makes_it_public(github, root, run_cli): github.add_org("owner", role="admin") - assert run_cli("plugin", "repo", "new", FULL, "--public", "--yes") == 0 + assert run_cli("plugin", "repo", "create", FULL, "--public", "--yes") == 0 assert _visibility(github) == "public" def test_empty_repo_gets_first_commit_directly(github, root, run_cli): github.add_repo(FULL) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 0 assert github.pushed_refs(FULL) == ["refs/heads/main"] assert github.prs() == [] assert [c for c in github.write_calls() if c[:2] == ["repo", "create"]] == [] @@ -61,18 +61,18 @@ def test_empty_repo_gets_first_commit_directly(github, root, run_cli): def test_repo_without_registry_goes_through_a_pr(github, root, run_cli): github.add_repo(FULL, {"README.md": "x\n"}) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 0 pr = github.prs()[0] - assert pr["head"] == "devbase/new-repo-repo" + assert pr["head"] == "devbase/create-repo-repo" assert pr["state"] == "MERGED" - assert github.pushed_refs(FULL) == ["refs/heads/devbase/new-repo-repo"] + assert github.pushed_refs(FULL) == ["refs/heads/devbase/create-repo-repo"] assert github.file(FULL, "registry.yml") is not None assert len(_registered(root)) == 1 def test_repo_with_registry_is_only_registered(github, root, run_cli): github.add_repo(FULL, {"registry.yml": REGISTRY}) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 0 assert github.write_calls() == [] assert github.pushed_refs(FULL) == [] assert len(_registered(root)) == 1 @@ -87,7 +87,7 @@ def test_registered_is_left_alone(github, root, run_cli, caplog, registered_url) github.add_repo(FULL, {"registry.yml": REGISTRY}) PluginRegistry(root).add_repository(RegisteredRepository(name="r", url=registered_url)) before = _plugins_yml(root) - assert run_cli("plugin", "repo", "new", FULL) == 0, "確認も --yes も要らない" + assert run_cli("plugin", "repo", "create", FULL) == 0, "確認も --yes も要らない" assert _plugins_yml(root) == before assert github.write_calls() == [] assert "登録済み" in caplog.text @@ -97,7 +97,7 @@ def test_registered_without_push_stops_with_1(github, root, run_cli): github.add_repo(FULL, {"registry.yml": REGISTRY}, permission="READ") PluginRegistry(root).add_repository(RegisteredRepository(name="r", url=f"git@github.com:{FULL}.git")) before = _plugins_yml(root) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 1 assert _plugins_yml(root) == before assert github.write_calls() == [] @@ -106,12 +106,12 @@ def test_registered_with_empty_local_path_still_ends_0(github, root, run_cli): github.add_repo(FULL, {"registry.yml": REGISTRY}) PluginRegistry(root).add_repository(RegisteredRepository( name="r", url=f"https://github.com/{FULL}.git", local_path="")) - assert run_cli("plugin", "repo", "new", FULL) == 0 + assert run_cli("plugin", "repo", "create", FULL) == 0 def test_no_push_stops_without_writing(github, root, run_cli, caplog): github.add_repo(FULL, {"README.md": "x\n"}, permission="READ") - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 1 assert github.write_calls() == [] assert github.pushed_refs(FULL) == [] assert _plugins_yml(root) is None @@ -120,7 +120,7 @@ def test_no_push_stops_without_writing(github, root, run_cli, caplog): def test_absent_and_not_a_member_stops(github, root, run_cli): - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 1 assert github.write_calls() == [] assert not github.exists(FULL) assert _plugins_yml(root) is None @@ -129,26 +129,26 @@ def test_absent_and_not_a_member_stops(github, root, run_cli): def test_org_forbids_creation_stops_at_create_with_gh_output(github, root, run_cli, caplog): """非管理者には組織の設定が返らないので、gh repo create の失敗の出力で止まる。""" github.add_org("owner", role="member", can_create=False) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 1 assert "cannot create repositories" in caplog.text assert not github.exists(FULL) assert _plugins_yml(root) is None def test_absent_in_own_account_can_be_created(github, root, run_cli): - assert run_cli("plugin", "repo", "new", "me/repo", "--yes") == 0 + assert run_cli("plugin", "repo", "create", "me/repo", "--yes") == 0 assert github.exists("me/repo") def test_absent_in_org_where_members_can_create(github, root, run_cli): github.add_org("owner", role="member", can_create=True) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 0 def test_unreadable_private_stops_at_create_with_gh_output(github, root, run_cli, caplog): github.add_org("owner", role="admin") github.add_repo(FULL, {"README.md": "x\n"}, hidden=True) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 1 assert "Name already exists" in caplog.text assert _plugins_yml(root) is None @@ -156,7 +156,7 @@ def test_unreadable_private_stops_at_create_with_gh_output(github, root, run_cli def test_stale_clone_directory_stops_before_writing(github, root, run_cli, caplog): github.add_org("owner", role="admin") (root / "repos" / "github.com--owner--repo").mkdir(parents=True) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 1 assert github.write_calls() == [] assert "github.com--owner--repo" in caplog.text @@ -172,18 +172,18 @@ def test_stale_clone_directory_stops_before_writing(github, root, run_cli, caplo ]) def test_all_forms_reach_the_same_repo(github, root, run_cli, value, url): github.add_repo(FULL, {"registry.yml": REGISTRY}) - assert run_cli("plugin", "repo", "new", value, "--yes") == 0 + assert run_cli("plugin", "repo", "create", value, "--yes") == 0 assert _registered(root)[0].url == url def test_non_github_url_stops(github, root, run_cli): - assert run_cli("plugin", "repo", "new", "https://gitlab.com/owner/repo", "--yes") == 1 + assert run_cli("plugin", "repo", "create", "https://gitlab.com/owner/repo", "--yes") == 1 assert github.calls() == [], "gh を呼ぶ前に止まる" -def test_prefix_of_new_resolves(github, root, run_cli): +def test_prefix_of_create_resolves(github, root, run_cli): github.add_repo(FULL, {"registry.yml": REGISTRY}) - assert run_cli("pl", "repo", "n", FULL, "--yes") == 0 + assert run_cli("pl", "repo", "c", FULL, "--yes") == 0 # ── gh の前提 ──────────────────────────────────────────────────── @@ -195,7 +195,7 @@ def test_without_gh_nothing_changes(github, root, run_cli, monkeypatch, caplog): import shutil (git_only / "git").symlink_to(shutil.which("git")) monkeypatch.setenv("PATH", str(git_only)) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 1 assert "cli.github.com" in caplog.text assert github.calls() == [] assert _plugins_yml(root) is None @@ -203,7 +203,7 @@ def test_without_gh_nothing_changes(github, root, run_cli, monkeypatch, caplog): def test_unauthenticated_nothing_changes(github, root, run_cli, caplog): github.update(authed=False) - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 1 assert "gh auth login" in caplog.text assert github.write_calls() == [] assert _plugins_yml(root) is None @@ -214,7 +214,7 @@ def test_unauthenticated_nothing_changes(github, root, run_cli, caplog): def test_no_tty_without_yes_stops_after_showing_the_plan(github, root, run_cli, capsys, caplog): github.add_org("owner", role="admin") - assert run_cli("plugin", "repo", "new", FULL) == 1 + assert run_cli("plugin", "repo", "create", FULL) == 1 out = capsys.readouterr().out assert FULL in out and "private" in out assert "--yes" in caplog.text @@ -224,14 +224,14 @@ def test_no_tty_without_yes_stops_after_showing_the_plan(github, root, run_cli, def test_tty_decline_changes_nothing(github, root, run_cli): github.add_org("owner", role="admin") - assert run_cli("plugin", "repo", "new", FULL, tty=True, answers=["n"]) == 1 + assert run_cli("plugin", "repo", "create", FULL, tty=True, answers=["n"]) == 1 assert github.write_calls() == [] assert _plugins_yml(root) is None def test_tty_accept_goes_on(github, root, run_cli): github.add_org("owner", role="admin") - assert run_cli("plugin", "repo", "new", FULL, tty=True, answers=["y"]) == 0 + assert run_cli("plugin", "repo", "create", FULL, tty=True, answers=["y"]) == 0 assert github.exists(FULL) assert len(_registered(root)) == 1 @@ -248,7 +248,7 @@ def _record(): return False monkeypatch.setattr(commands, "_confirmed", _record) - assert run_cli("plugin", "repo", "new", FULL) == 1 + assert run_cli("plugin", "repo", "create", FULL) == 1 assert seen == {"writes": [], "registered": None} @@ -257,7 +257,7 @@ def _record(): def test_merge_failure_leaves_plugins_yml_and_shows_pr(github, root, run_cli, caplog): github.add_repo(FULL, {"README.md": "x\n"}, merge_error="required reviews") - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 1 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 1 pr = github.prs()[0] assert pr["url"] in caplog.text assert "devbase plugin repo add" in caplog.text @@ -270,6 +270,6 @@ def test_merge_failure_leaves_plugins_yml_and_shows_pr(github, root, run_cli, ca def test_never_touches_docker(github, root, run_cli): github.add_org("owner", role="admin") - assert run_cli("plugin", "repo", "new", FULL, "--yes") == 0 + assert run_cli("plugin", "repo", "create", FULL, "--yes") == 0 assert github.docker_calls() == [] assert os.environ["PATH"].startswith(str(github.bin)) diff --git a/tests/plugin/test_github.py b/tests/plugin/test_github.py index fb62a516..cf4092b4 100644 --- a/tests/plugin/test_github.py +++ b/tests/plugin/test_github.py @@ -208,7 +208,7 @@ def test_create_repo_failure_carries_gh_output(client): def test_create_pr_returns_url(client): gh, script = client([(["pr", "create"], (0, "https://github.com/owner/repo/pull/7\n"))]) - url = gh.create_pr(REF, base="main", head="devbase/new-plugin-x", title="t", body="b") + url = gh.create_pr(REF, base="main", head="devbase/create-plugin-x", title="t", body="b") assert url == "https://github.com/owner/repo/pull/7" assert script.calls[0][:4] == ["pr", "create", "--repo", "owner/repo"] @@ -285,9 +285,9 @@ def test_merge_pr_failure_is_tried_once(client): def test_find_open_pr(client): gh, _ = client([(["pr", "list"], (0, f'[{{"url": "{PR}"}}]'))]) - assert gh.find_open_pr(REF, "devbase/new-plugin-x") == PR + assert gh.find_open_pr(REF, "devbase/create-plugin-x") == PR def test_find_open_pr_none(client): gh, _ = client([(["pr", "list"], (0, "[]"))]) - assert gh.find_open_pr(REF, "devbase/new-plugin-x") is None + assert gh.find_open_pr(REF, "devbase/create-plugin-x") is None diff --git a/tests/plugin/test_publish.py b/tests/plugin/test_publish.py index ceda597d..1c112342 100644 --- a/tests/plugin/test_publish.py +++ b/tests/plugin/test_publish.py @@ -31,7 +31,7 @@ def test_branch_name_is_a_valid_git_branch(name): def test_branch_name_keeps_valid_names(): - assert publish.branch_name("plugin", "a.b") == "devbase/new-plugin-a.b" + assert publish.branch_name("plugin", "a.b") == "devbase/create-plugin-a.b" def test_branch_name_is_unique_and_stable_for_replaced_names(): @@ -64,11 +64,11 @@ def test_publish_change_opens_and_merges_a_pr(github, gh, tmp_path, monkeypatch) registry_entry="team-a") pr = github.prs()[0] assert pr["url"] == url - assert pr["head"] == "devbase/new-plugin-team-a" + assert pr["head"] == "devbase/create-plugin-team-a" assert pr["base"] == "main" assert pr["title"] == "devbase: plugin team-a を足す" assert pr["state"] == "MERGED" - assert github.pushed_refs(FULL) == ["refs/heads/devbase/new-plugin-team-a"], \ + assert github.pushed_refs(FULL) == ["refs/heads/devbase/create-plugin-team-a"], \ "既定ブランチへ直接 push しない (I7)" assert github.branches(FULL) == ["main"], "作業用のブランチが残らない" assert leftovers() == [], "作業場所が残らない" @@ -134,7 +134,7 @@ def test_publish_change_rejects_a_path_above_the_clone(github, gh): def test_publish_change_stops_at_an_existing_branch_with_pr(github, gh): github.add_repo(FULL, REGISTRY) - publish_branch = "devbase/new-plugin-team-a" + publish_branch = "devbase/create-plugin-team-a" github.update_repo(FULL, merge_error="blocked") with pytest.raises(publish.MergeFailed): publish.publish_change(gh, REF, kind="plugin", name="team-a",