diff --git a/CLAUDE.md b/CLAUDE.md index 14459c7..efd4789 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ ## 開発進捗 -最新: PLAN_02 のステップ 1-2(設定を `labremote.yaml` に移す)完了.次はステップ 1-3(送信の除外を,固定の部分と設定に分ける) +最新: PLAN_02 のステップ 1-3(送信の除外を,固定の部分と設定に分ける)完了.次はステップ 1-4(回収の一覧と結果の置き場を設定にする) ※ 本欄は**最新ステップ 1 行のみ上書き更新**.詳細な進捗履歴(動機・設計判断・失敗パターン)は [docs/PROGRESS.md](docs/PROGRESS.md) に追記する.運用ルールは `.claude/rules/progress-log.md` を参照(該当ファイル編集時に自動ロードされる). ## 必須ルール(コード実装時) diff --git "a/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" "b/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" index a4b5db5..3065a61 100644 --- "a/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" +++ "b/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" @@ -36,5 +36,5 @@ - `uv run ruff format .` は Markdown の中の Python のコードブロックも整形する.`.claude/` は対象から外してある(`pyproject.toml`) - `labremote` のサブコマンド(`push`・`run`・`pull` 等)は,`labremote.yaml` のあるフォルダ(またはその下)で実行するものである.LabRemote 自身のリポジトリには `labremote.yaml` を置かないので,ここで実行できるのは `--help` と単体テストだけである - 別のフォルダに置いた設定で試すときは,そのフォルダで `uv run --project labremote <サブコマンド>` を実行する.`push --dry-run` は,サーバに接続せずに,設定の読み込みと送るファイルの一覧までを確かめられる -- スキップされるテストが 35 件ある.17 件はシンボリックリンクを作れない環境(権限の無い Windows)のため,18 件は TongueSegModel の側にしか無いものに頼るため([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md)「1-1 で分かったこと」) +- 手元(権限の無い Windows)では,スキップされるテストが 37 件ある.20 件はシンボリックリンクを作れないため(CI では実行される),17 件は TongueSegModel の側にしか無いものに頼るため([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md)「1-1 で分かったこと」) - 実サーバを使う確認の手順は,仕様が決まった時点で別に書く.単体テストは実サーバに接続しない diff --git "a/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" "b/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" index ce26d8a..73857da 100644 --- "a/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" +++ "b/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" @@ -39,12 +39,11 @@ | 直すステップ | 内容 | | --- | --- | | 3-3 | 学習側のコードと git のハッシュの環境変数名を突き合わせるテスト(`test_whitelist.py`)は,名前を `LABREMOTE_GIT_COMMIT` に置き換えたため,TongueSegModel の今のコード(`TSM_GIT_COMMIT`)とは合わない.`project.git_commit_env` は 1-2 で入ったので,利用する側のテスト(3-3)で「設定の `git_commit_env` と,学習側のコードが読む名前が同じ」ことを確かめる形に移す | -| 1-3 | `files.py` で,固定の除外と TongueSegModel の事情(`data`・`legacy`・`external/TIASDataHub`)が混ざっている.`test_files.py` のサブモジュールのテストと `repo_and_outside` fixture も書き直す | | 1-4 | `test_cli.py` の回収のテストは,`split.json`・`predictions.csv` を「回収しない」前提で書かれている.一覧を設定にするときに,前提を設定から与える形に直す | | 1-6・3-3 | LabRemote の中では動かせないテストが 18 件あり,スキップにしてある(学習側の実験 ID の作り方と突き合わせる 15 件,実際の `configs/remote.yaml` を読む 2 件,サブモジュールの 1 件).利用する側のテストへ移す | | 1-7 | 表示・help の使用例・コメントに,TongueSegModel の言葉(「学習データのバンドル」,`tsm-train`・`tsm-export`,`TIAS_DATA_ROOT` の経緯)が残っている.テストの名前にも `tsm` が残っている(`test_markers_use_tsm_prefix`・`TestRunIdOfTsmTrain`) | | 1-7 | コメント・docstring の SPEC の参照(約 36 行)は,移す元の文書を指している.該当のコードを書き換えるステップで,LabRemote の SPEC を指す形に直す | -| 1-3 以降 | `cli.py` は約 1200 行あり,GPU の選択の流れ・git の状態の取得・tar の受け取りを抱えている.設定に出すときに,判定を各モジュールへ分ける(`.claude/rules/project-structure.md`) | +| 1-4 以降 | `cli.py` は約 1200 行あり,GPU の選択の流れ・git の状態の取得・tar の受け取りを抱えている.設定に出すときに,判定を各モジュールへ分ける(`.claude/rules/project-structure.md`) | | 1-7 | コンソールの文字コードが日本語を表せない環境(CI の Windows は cp1252)では,help や表示の書き出しで `UnicodeEncodeError` になり,コマンドが落ちる.手元(cp932)とサーバ(UTF-8)では起きない.入口で「表せない文字は置き換えて出す」設定にする.今は `test_imports.py` の `test_help_runs_without_torch` が,子プロセスに UTF-8 を指定して避けている | | M2 | `test_cli.py` の `test_subcommands_listed_in_help_are_from_spec` は,help の字下げの幅に頼って一覧を読んでいる.`ls`・`clean` を足すときに壊れやすい | @@ -56,11 +55,22 @@ | 直すステップ | 内容 | | --- | --- | -| 1-3 | `labremote.yaml` 自体が `push` で送られる.サーバでは使わないので,固定の除外に入れるかを決める(送る必要のないものは送らない方針) | | 1-7 | `project.name` は,まだどこにも表示していない.表示に使う場所を決める | | 1-7 | `--env` の help が,予約の名前を文字で並べている.定数から作る形にすると食い違わない.設定エラーの「どこが不正か」の文言の組み立ても,2 か所に分かれている | | 4-2 | 設定の環境変数の値は `~` を展開しない([SPEC_02](../04_SPEC/SPEC_02_設定ファイル仕様.md)「`run`」).TIASJudgeModel のデータの場所を `servers[].env` で渡すときに,絶対パスで書くか,展開する仕組みを足すかを決める | +### 1-3 で分かったこと (Findings from Step 1-3) + +1-3 は完了した(2026-11-20).前の 2 つの表のうち,1-3 に回してあった 2 件は済んだので消した. + +| 直すステップ | 内容 | +| --- | --- | +| 1-4 | `config.py` の固定の除外は,結果の置き場を定数の `runs` から作っている.結果の置き場を設定にするときに,送信の固定の除外と,`partial.path` の検証(結果の置き場の中を指す `path` の拒否)が,設定の値を見るように直す | +| 1-6 | 固定の除外を名前で判定する処理が,設定の検証(`config.py`)と選別(`files.py`)の 2 か所にある.「当たった部分の位置と種類」を返す関数 1 つにまとめられる.テスト用の関数は,`PushRules.from_push(設定の push).is_excluded(名前)` を包むだけで作れる | +| 3-1 | **`data`・`legacy`・重みの拡張子は,もう固定の除外ではない**.TongueSegModel の `labremote.yaml` に `push.exclude_root: [data, legacy]`・`push.exclude_suffixes`・`push.partial`(`external/TIASDataHub`)を必ず書き,3-3 のテストで確かめる.`push` の節が無い設定は,読む時点でエラーになる | +| 3-1 | LabRemote 自身のフォルダの場所は,「`labremote` パッケージの 2 つ上」で求めている(`src/` の形を前提にしている).サブモジュールとして編集可能インストールで入れる前提なら合う.別の入れ方にするなら見直す | +| 1-7 | テスト(`tests/test_files.py`)に,TongueSegModel の言葉(`original_tongue_seg_dataset.py`・`legacy`)が残っている.サブモジュールのテスト群と `TestPartial` は,確かめている内容が重なっている | + ## M2: 新しい機能 (New Features) | ステップ | 内容 | 確かめること | diff --git "a/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" "b/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" index 1872e6e..6a2a62f 100644 --- "a/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" +++ "b/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" @@ -62,12 +62,22 @@ ### 送信 (Push) -- `.git/`・`.venv/`・キャッシュ(`__pycache__/`・`.pytest_cache/`・`.ruff_cache/`)・`.claude/`・`.env`・`.env.*` は,設定に関わらず送らない -- LabRemote 自身のフォルダは,設定に関わらず送らない -- 結果の置き場は,設定に関わらず送らない(サーバ側の結果を上書きしないため) +- 次は,設定に関わらず送らない(固定の除外) + - どの階層にあっても送らないフォルダ: `.git/`・`.venv/`・`.claude/`・キャッシュ(`__pycache__/`・`.pytest_cache/`・`.ruff_cache/`) + - どの階層にあっても送らないファイル: `.env`・`.env.*` + - 結果の置き場(ルートの直下.サーバ側の結果を上書きしないため) + - 設定ファイル: 読み込んだ設定ファイルと,ルートの直下の `labremote.yaml`(サーバでは使わないため.2026-11-19 のユーザー判断) + - LabRemote 自身のフォルダ: 実行中の `labremote` パッケージが入っているリポジトリが,ルートの下にある場合 - シンボリックリンクとジャンクションは,ファイルもフォルダも送らず,中にも入らない(リンク先がデータや原本でも,名前からは分からないため) - tar を作る段階でも,通常のファイル以外が 1 つでもあれば,何も送らずに止まる - 設定で指定できるのは「送らないものを足す」ことだけで,上の除外を減らすことはできない +- 設定の `push` の節は省略できない(書き忘れたまま,データや原本を送ってしまうのを防ぐ.[SPEC_02](SPEC_02_設定ファイル仕様.md)「`push`」) +- 送るかどうかの判定は 1 か所で行い,次の順にかける.どれか 1 つに当たれば送らない + 1. 固定の除外 + 2. 設定の除外(`exclude_root`・`exclude_dirs`・`exclude_suffixes`) + 3. 一部だけ送るフォルダ(`partial`)の `include` に無いもの + 4. リンク(上の 3 つに当たらなかったものがリンクなら,送らずに「送らなかったリンク」として表示する) +- 名前の比べ方(小文字にして比べる)は,1 つの関数で決める.比べる箇所ごとに書かない(付け忘れた箇所で除外が効かなくなるのを防ぐ) ### 回収 (Pull) diff --git "a/docs/04_SPEC/SPEC_02_\350\250\255\345\256\232\343\203\225\343\202\241\343\202\244\343\203\253\344\273\225\346\247\230.md" "b/docs/04_SPEC/SPEC_02_\350\250\255\345\256\232\343\203\225\343\202\241\343\202\244\343\203\253\344\273\225\346\247\230.md" index 7d273ae..fec2c07 100644 --- "a/docs/04_SPEC/SPEC_02_\350\250\255\345\256\232\343\203\225\343\202\241\343\202\244\343\203\253\344\273\225\346\247\230.md" +++ "b/docs/04_SPEC/SPEC_02_\350\250\255\345\256\232\343\203\225\343\202\241\343\202\244\343\203\253\344\273\225\346\247\230.md" @@ -3,7 +3,7 @@ 各プロジェクトのルートに置く `labremote.yaml` の項目を定める.pydantic で検証し,未知のキーは拒否する. 設定で変えられない規則(安全の枠)は [SPEC_01](SPEC_01_アーキテクチャ設計.md) にある. -※ 実装の状況(2026-11-19): `project`・接続と GPU の基準・`servers`・`run.env` は実装済み.`push`・`results`・`run.exclude_groups` は未実装で,今は書くと未知のキーとして拒否される([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md) のステップ 1-3〜1-5). +※ 実装の状況(2026-11-20): `project`・接続と GPU の基準・`servers`・`run.env`・`push` は実装済み.`results`・`run.exclude_groups` は未実装で,今は書くと未知のキーとして拒否される([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md) のステップ 1-4・1-5).結果の置き場は,今は `runs` で固定である. ## 例 (Example) @@ -101,7 +101,9 @@ ### `push` -設定に関わらず送らないもの(`.git/`・`.venv/`・キャッシュ・`.claude/`・`.env`・リンク・結果の置き場・LabRemote 自身のフォルダ)に,**足す**ものを書く.減らすことはできない. +設定に関わらず送らないもの(`.git/`・`.venv/`・`.claude/`・キャッシュ・`.env`・リンク・結果の置き場・設定ファイル・LabRemote 自身のフォルダ.[SPEC_01](SPEC_01_アーキテクチャ設計.md)「安全の枠」)に,**足す**ものを書く.減らすことはできない. + +**`push` の節は省略できない**(2026-11-19 のユーザー判断).足すものが無いプロジェクトも,`push: {}` と書く.書き忘れたまま,データや原本を送ってしまうのを防ぐためである.節の中のキーは省略でき,既定は空である. | キー | 既定 | 内容 | | --- | --- | --- | @@ -110,7 +112,18 @@ | `exclude_suffixes` | `[]` | どの階層にあっても送らない拡張子(小文字で比べる) | | `partial` | `[]` | 一部だけ送るフォルダ.`path` の直下のうち,`include` に書いた名前だけを送る | -- `partial` の `path` は,ルートからの相対パスで書く.`..`・絶対パスは書けない +- `exclude_root`・`exclude_dirs`・`partial` の `include` に書くのは,1 つの名前である.`/`・`\`・ワイルドカード(`*`・`?`・`[`)・`.`・`..`・空の名前は書けない +- 名前の前後に空白は書けない(`data ` のような書き間違いで,除外が効かないまま送ってしまうのを防ぐ) +- 名前の比べ方: `exclude_root`・`exclude_dirs`・`exclude_suffixes`・`partial` の `path` と,固定の除外・場所の除外(設定ファイル・LabRemote 自身のフォルダ)は,小文字にして比べる(`data` と書けば `Data` も送らない).`partial` の `include` だけは,大文字と小文字を区別して完全一致で比べる(`src` と書いて実際が `Src` なら送らない).どちらも,迷ったら送らない側に倒すための決まりである +- `exclude_dirs` に書いた名前は,同じ名前のファイルも送らない +- フォルダの名前には,拡張子の除外(`exclude_suffixes`)と `.env` の除外を当てはめない(`models.onnx/` という名前のフォルダの中には入り,中のファイルを名前で判断する) +- `exclude_suffixes` は,`.` で始まる拡張子で書く(`.pt` 等).ファイル名の末尾と,小文字にして比べる +- `partial` は,`path` と `include` の両方を必ず書く(`include` は省略できない.空の一覧は書ける) +- `partial` の `path` は,ルートからの相対パスで,`/` 区切りで書く.`..`・絶対パス・ワイルドカードは書けない.`./a`・`a//b`・`a/` のように,`.` や空の部分を含む書き方もできない.同じ `path` を 2 回書くこと,一方が他方の中にある `path` を書くことはできない.固定の除外の中を指す `path`(`.venv/x`・`runs/x` 等)も書けない(そこは送られないので,書き間違いとして扱う) +- `partial` の `path` のフォルダが実際には無い場合は,エラーにせず,何も送らない.`path` がファイルを指す場合は,そのファイルを送らない.`include` が空の場合は,その下を何も送らない +- `exclude_root` と `partial` の `path` が重なる場合は,除外が優先される +- `partial` の `path` の下では,直下の名前が `include` に一致するものだけを送る.その中身には,固定の除外と,設定の他の除外(`exclude_dirs`・`exclude_suffixes`)がそのままかかる +- 節の中の既定はすべて空である.**データ・原本・重みのフォルダは,設定に書かなければ送られる**.各プロジェクトは,送ってはならないものを必ずここに書き,プロジェクトの側のテストで確かめる([SPEC_01](SPEC_01_アーキテクチャ設計.md)「プロジェクトの側のテスト」) - サブモジュールは,サーバでの導入に要るものだけを `partial` で指定する.指定しなかったサブモジュールは,通常のフォルダと同じく全体が送られる(LabRemote 自身は例外で,書かなくても送られない) ### `run` diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index dd578be..f1fc087 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -35,3 +35,8 @@ - 設計判断: 設定の環境変数の値は文字列だけを受け付け,`~` は展開しない(YAML が型を変えた値や,場所によって意味が変わる値を,気づかないまま渡さない) - 仕様と実装の食い違いを 3 件直した: `jump_host` の既定はコードを `null` に(TongueSegModel の値 `labpc` が残っていた),`data_ready` の既定と `uv` の欄は仕様をコードに合わせた(`false`・`~/.local/bin/uv`) - 後段: `push`・`results`・`run.exclude_groups` は未実装で,書くと未知のキーとして拒否される(1-3〜1-5) +- [x] **ステップ 1-3(送信の除外を分ける)**: 送らないものを,コードで固定する除外と,`labremote.yaml` の `push` で足す除外に分けた.`labremote.yaml`(読み込んだ設定ファイル)と LabRemote 自身のフォルダを送らないようにした. + - 設計判断: `push` の節は省略できないようにした(ユーザー判断).`data`・`legacy`・重みが固定の除外でなくなり,書かなければ送られるため,書き忘れに気づく機会を 1 つ足した.中身の正しさは,各プロジェクトの側のテストで確かめる + - 設計判断: 名前は小文字にして比べ(`data` と書けば `Data` も送らない),比べ方は 1 つの関数で決める.`partial.include` だけは大文字小文字を区別する.どちらも,迷ったら送らない側に倒すため + - 設計判断: `.claude` は「ルートの直下だけ」から「どの階層でも」送らない,に広げた(サブモジュールの中の `.claude` もサーバに要らない) + - 後段: TongueSegModel の切り替え(3-1)で,`push` に `data`・`legacy`・重み・`external/TIASDataHub` を必ず書く.結果の置き場はまだ `runs` で固定(1-4) diff --git a/src/labremote/cli.py b/src/labremote/cli.py index 84bda14..857efaf 100644 --- a/src/labremote/cli.py +++ b/src/labremote/cli.py @@ -45,6 +45,7 @@ from pydantic import ValidationError +import labremote from labremote.commands import ( EXIT_NO_SESSION, EXIT_NOT_FOUND, @@ -157,12 +158,16 @@ ssh: 手元の ssh 実行ファイル. jump_host: 踏み台(None なら直接接続). project_root: 手元のプロジェクトルート. + config_path: 読み込んだ設定ファイル(送信から除く). + labremote_dir: LabRemote 自身のフォルダ(ルートの下にあれば送信から除く). """ config: RemoteConfig ssh: str jump_host: str | None project_root: Path + config_path: Path + labremote_dir: Path @property def query_timeout_sec(self) -> int: @@ -560,7 +565,12 @@ def _collect_entries(ctx: _Context) -> PushSelection: """送信対象を集める(空ならエラー).""" - selection = select_push_files(ctx.project_root) + selection = select_push_files( + ctx.project_root, + ctx.config.push, + config_path=ctx.config_path, + labremote_dir=ctx.labremote_dir, + ) if not selection.entries: raise ValueError("送信するファイルが無い") return selection @@ -1030,9 +1040,10 @@ parents=[common, server_opt], help="コードをサーバへ送る(省略時は接続できる全サーバ)", description=( - "リポジトリを tar over ssh でサーバの remote_dir へ上書き展開する." - ".git / .venv / キャッシュ / data / runs / legacy / .claude・重み(.pt .pth .ckpt " - ".pb .onnx)・.env は送らない." + "プロジェクトのルートの下のファイルを tar over ssh でサーバの remote_dir へ" + "上書き展開する..git / .venv / .claude / キャッシュ・.env・リンク・" + f"{REMOTE_RUNS_DIR}/(ルートの直下)・設定ファイル・LabRemote 自身のフォルダは" + "常に送らない.ほかに送らないもの(データ・原本・重み等)は設定の push に書く." ), ) p_push.add_argument( @@ -1166,6 +1177,11 @@ } +def _labremote_repo_dir() -> Path: + """実行中の `labremote` パッケージが入っているリポジトリ(`src/labremote/` の 2 つ上).""" + return Path(labremote.__file__).resolve().parent.parent.parent + + def _build_context(args: argparse.Namespace) -> _Context: """設定を読み込み,実行環境を組み立てる.""" config_path = find_config_path(Path.cwd(), args.config) @@ -1176,6 +1192,8 @@ ssh=resolve_ssh_executable(os.environ), jump_host=resolve_jump_host(config, os.environ), project_root=project_root, + config_path=config_path, + labremote_dir=_labremote_repo_dir(), ) diff --git a/src/labremote/config.py b/src/labremote/config.py index 90992b1..526da1e 100644 --- a/src/labremote/config.py +++ b/src/labremote/config.py @@ -2,13 +2,17 @@ 設定の項目は SPEC_02,ルートの見つけ方は SPEC_01「プロジェクトのルートの見つけ方」, ジョブに渡す環境変数と予約の名前は SPEC_01「環境変数」・「名前と値の検証」に従う. +`push` の節(送らないものを足す設定)は SPEC_02「`push`」に従う.固定の除外(SPEC_01「安全の枠」の +「送信」)は設定のスキーマに入れない.固定の除外の名前は,`push.partial` の検証と +`labremote.files` の選別の両方で使うため,このモジュールの定数に置く +(`labremote.files` がこのモジュールを import する向きのため). """ from __future__ import annotations import os import re -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from pathlib import Path from typing import Any @@ -25,6 +29,7 @@ ) from labremote.commands import ( + REMOTE_RUNS_DIR, quote_remote_path, reserved_env_vars, validate_env_key, @@ -36,6 +41,48 @@ # 設定ファイルの名前.このファイルのあるフォルダをプロジェクトのルートとする CONFIG_FILE_NAME = "labremote.yaml" + +def fold_push_name(name: str) -> str: + """送信の除外で比べるために,名前を比べる形(小文字)にそろえる. + + 送信の除外の名前の比べ方は,この関数(と `fold_push_parts`)だけで決める.手元の Windows では + `.Git` も `.git` と同じ場所のため,大文字小文字の違いで除外をすり抜けないようにする. + `push.partial` の `include` には使わない(大文字小文字を区別して比べる.SPEC_02「`push`」). + + Args: + name: フォルダ・ファイルの名前,または拡張子. + + Returns: + 比べる形の名前. + """ + return name.lower() + + +def fold_push_parts(parts: Iterable[str]) -> tuple[str, ...]: + """相対パスの各部分を,`fold_push_name` で比べる形にそろえる. + + Args: + parts: 相対パスの各部分. + + Returns: + 比べる形の各部分. + """ + return tuple(fold_push_name(part) for part in parts) + + +# 固定の除外(SPEC_01「安全の枠」の「送信」)の名前.設定のスキーマに入れず,設定では減らせない. +# 選別(`labremote.files`)と `push.partial` の path の検証で使う. +# 比べる形(`fold_push_name`)で持つ. +# +# どの階層にあっても送らないフォルダ名..git は履歴,.venv は手元用(サーバでは使えない), +# .claude は手元の Claude Code の設定,残りはキャッシュで,サーバへ広げないため +FIXED_EXCLUDED_DIR_NAMES = frozenset( + fold_push_parts((".git", ".venv", ".claude", "__pycache__", ".pytest_cache", ".ruff_cache")) +) +# ルートの直下で送らない名前.結果の置き場はサーバ側の結果を上書きしないため, +# labremote.yaml はサーバでは使わないため(2026-11-19 のユーザー判断) +FIXED_EXCLUDED_ROOT_ENTRIES = frozenset(fold_push_parts((REMOTE_RUNS_DIR, CONFIG_FILE_NAME))) + # `jump_host` を上書きする.空文字なら直接接続(研究室 LAN 内にいるとき) JUMP_ENV_VAR = "LABREMOTE_JUMP" # 手元の ssh 実行ファイル @@ -48,6 +95,9 @@ _SERVER_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*") _PROJECT_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*") _TRUE_VALUES = frozenset({"1", "true", "yes"}) +# push の設定に書く名前に使えない文字.パスの区切り(1 つの名前に限るため)・ワイルドカード +# (名前は完全一致で比べるため,書いても効かないことに気づけるよう拒否する)・NUL +_PUSH_NAME_FORBIDDEN_CHARS = frozenset("/\\*?[\0") class _StrictModel(BaseModel): @@ -112,6 +162,139 @@ return value +def _check_push_name(value: str, *, where: str) -> str: + """push の設定に書く 1 つの名前(フォルダ・ファイルの名前)を検証して返す. + + Raises: + ValueError: 空・`.`・`..`,前後に空白がある,またはパスの区切り・ワイルドカード・NUL を + 含む場合. + """ + if value in {"", ".", ".."}: + raise ValueError(f"{where}: 空・.・.. は書けない(1 つの名前を書く): {value!r}") + if value != value.strip(): + # `data ` のような書き間違いは実際の `data` に一致せず,除外が効かないまま送るため拒否する + raise ValueError(f"{where}: 前後に空白のある名前は書けない: {value!r}") + if _PUSH_NAME_FORBIDDEN_CHARS.intersection(value): + raise ValueError( + f"{where}: / \\ とワイルドカード(* ? [)は書けない(1 つの名前を完全一致で比べる): " + f"{value!r}" + ) + return value + + +def _check_push_names(values: tuple[str, ...], *, where: str) -> tuple[str, ...]: + for value in values: + _check_push_name(value, where=where) + return values + + +class PartialPush(_StrictModel): + """一部だけ送るフォルダ 1 件. + + Attributes: + path: ルートからの相対パス(`/` 区切り). + include: `path` の直下で送る名前(大文字小文字を区別して完全一致で比べる). + その中身には,固定の除外と `exclude_dirs`・`exclude_suffixes` がそのままかかる. + """ + + path: StrictStr + include: tuple[StrictStr, ...] + + @field_validator("path") + @classmethod + def _check_path(cls, value: str) -> str: + # 絶対パス(/x・C:/x・\x)と .. を拒否し,ルートの下の場所だけを指せるようにする + if value.startswith("/") or (len(value) >= 2 and value[1] == ":"): + raise ValueError(f"push.partial の path に絶対パスは書けない: {value!r}") + parts = value.split("/") + for part in parts: + _check_push_name(part, where=f"push.partial の path {value!r}") + # 固定の除外の中は送られないため,書き間違いとして拒否する.選別と同じく小文字にして比べる + # (場所で決まる除外は,設定を読む時点では分からないため対象にしない) + folded = fold_push_parts(parts) + for part, folded_part in zip(parts, folded, strict=True): + if folded_part in FIXED_EXCLUDED_DIR_NAMES: + raise ValueError( + f"push.partial の path {value!r} は固定の除外の中を指す" + f"({part!r} はどの階層でも送らないフォルダ)" + ) + if folded[0] in FIXED_EXCLUDED_ROOT_ENTRIES: + raise ValueError( + f"push.partial の path {value!r} は固定の除外の中を指す" + f"(ルートの直下の {parts[0]!r} は送らない)" + ) + return value + + @field_validator("include") + @classmethod + def _check_include(cls, value: tuple[str, ...]) -> tuple[str, ...]: + return _check_push_names(value, where="push.partial の include") + + @property + def parts(self) -> tuple[str, ...]: + """`path` を `/` で分けたもの.""" + return tuple(self.path.split("/")) + + +class PushConfig(_StrictModel): + """送信の設定(固定の除外に足す除外.SPEC_02「`push`」). + + 固定の除外(SPEC_01「安全の枠」)はここに無く,設定で減らせない.既定はすべて空で, + データ・原本・重みは書かなければ送られる. + + Attributes: + exclude_root: ルートの直下でだけ送らない名前. + exclude_dirs: どの階層にあっても送らないフォルダの名前. + exclude_suffixes: どの階層にあっても送らない拡張子(`.` で始まる.小文字にして持つ). + partial: 一部だけ送るフォルダ. + """ + + exclude_root: tuple[StrictStr, ...] = () + exclude_dirs: tuple[StrictStr, ...] = () + exclude_suffixes: tuple[StrictStr, ...] = () + partial: tuple[PartialPush, ...] = () + + @field_validator("exclude_root") + @classmethod + def _check_exclude_root(cls, value: tuple[str, ...]) -> tuple[str, ...]: + return _check_push_names(value, where="push.exclude_root") + + @field_validator("exclude_dirs") + @classmethod + def _check_exclude_dirs(cls, value: tuple[str, ...]) -> tuple[str, ...]: + return _check_push_names(value, where="push.exclude_dirs") + + @field_validator("exclude_suffixes") + @classmethod + def _check_exclude_suffixes(cls, value: tuple[str, ...]) -> tuple[str, ...]: + for suffix in value: + # `.` だけ・`..` は全ファイル・何にも当たらない指定になり,意図と違うため拒否する + if not suffix.startswith(".") or suffix in {".", ".."}: + raise ValueError( + f"push.exclude_suffixes は . で始まる拡張子で書く(.pt 等): {suffix!r}" + ) + _check_push_name(suffix, where="push.exclude_suffixes") + # ファイル名と小文字にして比べるため,持つ側も小文字にそろえる + return fold_push_parts(value) + + @model_validator(mode="after") + def _check_partial_paths(self) -> PushConfig: + # 同じ場所・入れ子の path は,どちらの include が効くかが曖昧になるため拒否する. + # Windows では大文字小文字だけが違う名前が同じ場所を指すため,小文字にして比べる + folded = [(p.path, fold_push_parts(p.parts)) for p in self.partial] + for i, (path_a, parts_a) in enumerate(folded): + for path_b, parts_b in folded[i + 1 :]: + if parts_a == parts_b: + raise ValueError(f"push.partial の path が重複している: {path_a!r}") + shorter = min(len(parts_a), len(parts_b)) + if parts_a[:shorter] == parts_b[:shorter]: + raise ValueError( + "push.partial の path は,一方が他方の中にあってはならない: " + f"{path_a!r} と {path_b!r}" + ) + return self + + class GpuFreeThreshold(_StrictModel): """GPU を「空き」とみなす閾値と,判定前の観測の設定. @@ -195,15 +378,33 @@ connect_timeout_sec: ssh の接続タイムアウト(秒). gpu_free: 空き判定の閾値. servers: 計算サーバの一覧(1 件以上.名前は重複不可). + push: 送信の設定(固定の除外に足す除外). """ project: ProjectConfig run: RunConfig = Field(default_factory=RunConfig) + push: PushConfig jump_host: str | None = None connect_timeout_sec: StrictInt = Field(default=15, ge=1) gpu_free: GpuFreeThreshold = Field(default_factory=GpuFreeThreshold) servers: tuple[ServerConfig, ...] = Field(min_length=1) + @model_validator(mode="before") + @classmethod + def _require_push(cls, data: Any) -> Any: + # push の書き忘れで,データや原本を送ってしまうのを防ぐため,節の省略と null を拒否する + if not isinstance(data, Mapping): + return data + hint = ( + "送らないものを足さない場合も push: {} と書く" + "(データ・原本・重みのフォルダは,push に書かないと送られる)" + ) + if "push" not in data: + raise ValueError(f"push の節が無い.{hint}") + if data["push"] is None: + raise ValueError(f"push の値が空(null).{hint}") + return data + @field_validator("jump_host") @classmethod def _check_jump_host(cls, value: str | None) -> str | None: diff --git a/src/labremote/files.py b/src/labremote/files.py index d28ca5f..762500f 100644 --- a/src/labremote/files.py +++ b/src/labremote/files.py @@ -1,42 +1,52 @@ """push で送るファイルの選別. -リポジトリ内のコード一式を送り,キャッシュ・仮想環境・データ・実験結果・原本・重み・ -Claude の設定は送らない(SPEC_03「移植で変える点」).サブモジュール TIASDataHub は -サーバの `uv sync` が tiasdata を導入するのに要るものだけを送る. +ルートの下のファイルのうち,固定の除外(SPEC_01「安全の枠」の「送信」)と,設定で足した除外 +(SPEC_02「`push`」)に当たらないものを送る(SPEC_03「push」).固定の除外は名前の定数(このモジュール +と `labremote.config` の先頭)と,選別の関数が引数で受け取る場所(読み込んだ設定ファイル・LabRemote +自身のフォルダ)で決まり,設定では減らせない.設定で足せるのは,送らないものだけである. -シンボリックリンクとジャンクション(Windows の reparse point)は,ファイル・ディレクトリとも -送らず,リンクのディレクトリの中にも入らない(リンク先がリポジトリの外・`legacy/`・`data/` でも +シンボリックリンクとジャンクション(Windows の reparse point)は,ファイル・フォルダとも +送らず,リンクのフォルダの中にも入らない(リンク先がルートの外やデータ・原本の置き場でも, 名前だけでは分からないため.学習データ・原本をサーバへ送る経路を作らない). -TIASJudgeModel の `tias_judge_model.remote.files` の移植.`legacy/`・重みの拡張子・`.env`・ -リンクの除外を足した(移植元はリンク先の中身を送っていた). +選別の関数は,ファイルの一覧を読むほかは副作用を持たない.LabRemote 自身のフォルダと読み込んだ +設定ファイルの場所は,呼ぶ側(`cli`)が求めて渡す. + +「送らない」の判定は `PushRules.is_excluded` の 1 か所にまとめ,フォルダ・ファイルとも次の順で +当てはめる(どれか 1 つに当たれば送らない).`_walk_files` はこの判定に当たったフォルダに入らず, +当たらなかったものだけをリンクかどうか調べる(除外したフォルダの中のリンクは報告しない). + +1. 固定の除外(`_is_fixed_excluded`): どの階層でも送らないフォルダ名,ルートの直下で送らない名前, + 場所で決まるもの(設定ファイル・LabRemote 自身のフォルダ),`.env`・`.env.*` +2. 設定の除外(`_is_config_excluded`): `exclude_root`・`exclude_dirs`・`exclude_suffixes` +3. `partial`(`_is_outside_partial_include`): `path` の直下で `include` に無いもの +4. リンク(`_walk_files`): 1〜3 に当たらなかったシンボリックリンク・ジャンクション + +名前の比べ方は `labremote.config.fold_push_name` だけで決める(`partial` の `include` を除く). """ from __future__ import annotations import os -from collections.abc import Iterator +from collections.abc import Iterable, Iterator from dataclasses import dataclass from pathlib import Path, PurePosixPath -# どの階層にあっても送らないディレクトリ名(.venv は Windows 用でサーバでは使えない) -EXCLUDED_DIR_NAMES = frozenset({".git", ".venv", "__pycache__", ".pytest_cache", ".ruff_cache"}) -# プロジェクト直下でだけ除外するエントリ.data/ は学習データ・合成データの置き場,runs/ は -# サーバ側の実験結果を上書きしないため,.claude/ は手元の Claude Code 設定のため送らない. -# legacy/ は原本で,約 4 GB の重みと画像のファイル名を含む結果があるため送らない(SPEC_03). -# 直下に限るのは src/tongue_seg_model/data/(パッケージ)・tests/data/ を送るため -EXCLUDED_ROOT_ENTRIES = frozenset({"data", "runs", ".claude", "legacy"}) -# どの階層にあっても送らない拡張子(小文字で比べる).重みは data/・runs/・legacy/ の外に -# 置かれていても送らない(.gitignore の重みの拡張子と同じ) -EXCLUDED_SUFFIXES = frozenset({".pt", ".pth", ".ckpt", ".pb", ".onnx"}) -# どの階層にあっても送らないファイル名(環境変数ファイル.秘密を含みうる..gitignore と同じ) -_ENV_FILE_NAME = ".env" +from labremote.config import ( + FIXED_EXCLUDED_DIR_NAMES, + FIXED_EXCLUDED_ROOT_ENTRIES, + PushConfig, + fold_push_name, + fold_push_parts, +) -# サブモジュールのうち,サーバで `uv` が tiasdata を導入するのに要るものだけを送る -# (README.md は uv_build が要求する)..claude/・docs/・tests/・datasets/ 等は送らない -# (実行に要らず,手元の設定や別リポジトリの文書をサーバに広げないため). -_SUBMODULE_PARTS = ("external", "TIASDataHub") -_SUBMODULE_SENT_ENTRIES = frozenset({"pyproject.toml", "README.md", "src"}) +# 固定の除外(SPEC_01「安全の枠」の「送信」).設定のスキーマに入れず,設定では減らせない. +# 名前は比べる形(`fold_push_name`)で持つ.どの階層でも送らないフォルダ名 +# (FIXED_EXCLUDED_DIR_NAMES)とルートの直下で送らない名前(FIXED_EXCLUDED_ROOT_ENTRIES)は, +# push.partial の path の検証でも使うため `labremote.config` に置く +# +# どの階層にあっても送らない環境変数ファイル(`.env` と `.env.*`).秘密を含みうるため +FIXED_ENV_FILE_NAME = fold_push_name(".env") @dataclass(frozen=True) @@ -62,13 +72,168 @@ entries: 送信するファイル(arcname 順). skipped_links: 送らなかったリンク(シンボリックリンク・ジャンクション)の プロジェクトルート基準の相対パス(POSIX 区切り,順に並べたもの).除外対象の - ディレクトリ(`.venv/` 等)の中のリンクは含まない. + フォルダ(`.venv/` 等)の中のリンクは含まない. """ entries: tuple[PushEntry, ...] skipped_links: tuple[str, ...] +@dataclass(frozen=True) +class PushRules: + """送らないものの判定に使う規則(固定の除外は定数として常にかかる). + + 名前・パスは比べる形(`fold_push_name`)で持つ(`partial` の `include` だけは書いたまま持ち, + 大文字小文字を区別して比べる.送るものを増やす側に倒さないため). + + Attributes: + exclude_root: ルートの直下でだけ送らない名前(設定の `push.exclude_root`). + exclude_dirs: どの階層にあっても送らない名前(設定の `push.exclude_dirs`). + exclude_suffixes: どの階層にあっても送らないファイルの拡張子(設定の + `push.exclude_suffixes`). + partial: 一部だけ送るフォルダ(比べる形にした `path` の各部分と,`include` の組). + excluded_paths: 固定の除外のうち場所で決まるもの(読み込んだ設定ファイル・LabRemote + 自身のフォルダ)の,ルートからの相対パスを比べる形にして分けたもの. + """ + + exclude_root: frozenset[str] = frozenset() + exclude_dirs: frozenset[str] = frozenset() + exclude_suffixes: tuple[str, ...] = () + partial: tuple[tuple[tuple[str, ...], frozenset[str]], ...] = () + excluded_paths: frozenset[tuple[str, ...]] = frozenset() + + @classmethod + def from_push( + cls, + push: PushConfig | None = None, + *, + excluded_paths: Iterable[tuple[str, ...]] = (), + ) -> PushRules: + """設定の `push` から規則を作る. + + Args: + push: 設定の `push`.None なら設定の除外は無し(固定の除外だけ). + excluded_paths: 固定の除外のうち場所で決まるもの(ルートからの相対パスの各部分). + + Returns: + 規則. + """ + push = push or PushConfig() + return cls( + exclude_root=frozenset(fold_push_parts(push.exclude_root)), + exclude_dirs=frozenset(fold_push_parts(push.exclude_dirs)), + exclude_suffixes=fold_push_parts(push.exclude_suffixes), + partial=tuple( + (fold_push_parts(item.parts), frozenset(item.include)) for item in push.partial + ), + excluded_paths=frozenset(fold_push_parts(parts) for parts in excluded_paths), + ) + + def is_excluded(self, rel_path: str, *, is_dir: bool = False) -> bool: + """ルート基準の相対パスが送信から除外されるかを返す. + + 判定の順序はモジュールの docstring を参照する.名前は `fold_push_parts` で比べる形に + してから,固定の除外・設定の除外・`partial` の `path` と比べる. + + Args: + rel_path: POSIX 区切りの相対パス. + is_dir: フォルダなら True(拡張子・`.env` の除外を当てはめない.中のファイルは + 名前で判断する). + + Returns: + 除外対象なら True. + """ + parts = PurePosixPath(rel_path).parts + if not parts: + return False + folded = fold_push_parts(parts) + return ( + self._is_fixed_excluded(folded, is_dir=is_dir) + or self._is_config_excluded(folded, is_dir=is_dir) + or self._is_outside_partial_include(parts, folded, is_dir=is_dir) + ) + + def _is_fixed_excluded(self, folded: tuple[str, ...], *, is_dir: bool) -> bool: + # フォルダ名の除外はファイルにも当てはめる(サブモジュールの `.git` はファイルのため) + if any(part in FIXED_EXCLUDED_DIR_NAMES for part in folded): + return True + if folded[0] in FIXED_EXCLUDED_ROOT_ENTRIES: + return True + # 設定ファイル・LabRemote 自身のフォルダは,その場所とその中を送らない + if any(folded[: len(path)] == path for path in self.excluded_paths): + return True + name = folded[-1] + return not is_dir and ( + name == FIXED_ENV_FILE_NAME or name.startswith(FIXED_ENV_FILE_NAME + ".") + ) + + def _is_config_excluded(self, folded: tuple[str, ...], *, is_dir: bool) -> bool: + if folded[0] in self.exclude_root: + return True + # exclude_dirs はフォルダの名前だが,同じ名前のファイルも送らない側に倒す + if any(part in self.exclude_dirs for part in folded): + return True + return not is_dir and folded[-1].endswith(self.exclude_suffixes) + + def _is_outside_partial_include( + self, parts: tuple[str, ...], folded: tuple[str, ...], *, is_dir: bool + ) -> bool: + # partial の path の中は include に書いた名前だけを送り,書いていないもの(データ等)を + # 送らない.include は書いたままの parts と比べる(大文字小文字を区別する) + for path, include in self.partial: + depth = len(path) + if folded[:depth] != path: + continue + if len(parts) == depth: + # partial の path 自体がファイルなら,直下を選べないため送らない + return not is_dir + return parts[depth] not in include + return False + + +def _relative_parts_under(root: Path, path: Path | None) -> tuple[str, ...] | None: + """path がルートの下(ルートそのものを除く)にあれば,ルートからの相対パスの各部分を返す.""" + if path is None: + return None + try: + rel = path.resolve().relative_to(root) + except ValueError: + return None + return rel.parts or None + + +def build_push_rules( + root: Path, + push: PushConfig | None = None, + *, + config_path: Path | None = None, + labremote_dir: Path | None = None, +) -> PushRules: + """ルートと設定の `push` から,送らないものの規則を作る. + + Args: + root: プロジェクトのルート. + push: 設定の `push`.None なら設定の除外は無し(固定の除外だけ). + config_path: 読み込んだ設定ファイル.ルートの下にあれば送らない. + labremote_dir: LabRemote 自身のフォルダ(実行中の `labremote` パッケージが入っている + リポジトリ).ルートの下にあれば,フォルダ全体を送らない.ルートそのもの・ルートの外 + なら何もしない. + + Returns: + 規則. + """ + resolved_root = root.resolve() + excluded = [ + parts + for parts in ( + _relative_parts_under(resolved_root, config_path), + _relative_parts_under(resolved_root, labremote_dir), + ) + if parts is not None + ] + return PushRules.from_push(push, excluded_paths=excluded) + + def is_link(path: Path) -> bool: """path がシンボリックリンクかジャンクション(Windows の reparse point)かを返す. @@ -84,47 +249,26 @@ return path.is_symlink() or os.path.isjunction(path) -def _is_excluded_file_name(name: str) -> bool: - """ファイル名だけで除外が決まるもの(重みの拡張子・環境変数ファイル)か.""" - lowered = name.lower() - if lowered == _ENV_FILE_NAME or lowered.startswith(_ENV_FILE_NAME + "."): - return True - return PurePosixPath(lowered).suffix in EXCLUDED_SUFFIXES - - -def is_excluded(rel_path: str, *, is_dir: bool = False) -> bool: - """プロジェクトルート基準の相対パスが push から除外されるかを返す. +def is_excluded(rel_path: str, *, is_dir: bool = False, rules: PushRules | None = None) -> bool: + """ルート基準の相対パスが push から除外されるかを返す. Args: rel_path: POSIX 区切りの相対パス. - is_dir: ディレクトリなら True(拡張子・ファイル名による除外を当てはめない). + is_dir: フォルダなら True(拡張子・`.env` の除外を当てはめない). + rules: 規則.None なら固定の除外だけ(場所で決まるものを除く). Returns: 除外対象なら True. """ - parts = PurePosixPath(rel_path).parts - if not parts: - return False - # 大文字小文字を区別せずに比べる(手元の Windows では `Legacy/` も `legacy/` と同じ場所のため) - lowered = [part.lower() for part in parts] - if lowered[0] in EXCLUDED_ROOT_ENTRIES or any(part in EXCLUDED_DIR_NAMES for part in lowered): - return True - if not is_dir and _is_excluded_file_name(parts[-1]): - return True - depth = len(_SUBMODULE_PARTS) - return ( - len(parts) > depth - and parts[:depth] == _SUBMODULE_PARTS - and parts[depth] not in _SUBMODULE_SENT_ENTRIES - ) + return (rules or PushRules()).is_excluded(rel_path, is_dir=is_dir) -def _walk_files(root: Path, skipped_links: list[str]) -> Iterator[PushEntry]: +def _walk_files(root: Path, rules: PushRules, skipped_links: list[str]) -> Iterator[PushEntry]: """root 配下のファイルを,除外規則を適用しつつ決定的な順で列挙する. - リンク(ファイル・ディレクトリとも)は送らず,その相対パスを skipped_links に足す. - os.walk は既定でシンボリックリンクのディレクトリに入らないが,ジャンクションには入りうる - ため,dirnames から明示的に除いて入らないようにする. + リンク(ファイル・フォルダとも)は送らず,その相対パスを skipped_links に足す. + os.walk は既定でシンボリックリンクのフォルダに入らないが,ジャンクションには入りうる + ため,dirnames から明示的に除いて入らないようにする.除外したフォルダの中は列挙もしない. """ for dirpath, dirnames, filenames in os.walk(root): dir_rel = Path(dirpath).relative_to(root).as_posix() @@ -132,7 +276,7 @@ kept: list[str] = [] for dirname in sorted(dirnames): rel = prefix + dirname - if is_excluded(rel, is_dir=True): + if rules.is_excluded(rel, is_dir=True): continue if is_link(Path(dirpath) / dirname): skipped_links.append(rel) @@ -142,7 +286,7 @@ for filename in sorted(filenames): rel = prefix + filename path = Path(dirpath) / filename - if is_excluded(rel): + if rules.is_excluded(rel): continue if is_link(path): skipped_links.append(rel) @@ -152,27 +296,52 @@ yield PushEntry(path=path, arcname=rel, size=path.stat().st_size) -def select_push_files(root: Path) -> PushSelection: +def select_push_files( + root: Path, + push: PushConfig | None = None, + *, + config_path: Path | None = None, + labremote_dir: Path | None = None, +) -> PushSelection: """送信するファイルを選び,送らなかったリンクと合わせて返す. Args: - root: プロジェクトルート. + root: プロジェクトのルート. + push: 設定の `push`.None なら設定の除外は無し(固定の除外だけ). + config_path: 読み込んだ設定ファイル(`build_push_rules` を参照). + labremote_dir: LabRemote 自身のフォルダ(`build_push_rules` を参照). Returns: arcname 順に並べた送信対象と,送らなかったリンク. """ + resolved_root = root.resolve() + rules = build_push_rules( + resolved_root, push, config_path=config_path, labremote_dir=labremote_dir + ) skipped_links: list[str] = [] - entries = sorted(_walk_files(root.resolve(), skipped_links), key=lambda entry: entry.arcname) + entries = sorted( + _walk_files(resolved_root, rules, skipped_links), key=lambda entry: entry.arcname + ) return PushSelection(tuple(entries), tuple(sorted(skipped_links))) -def collect_push_entries(root: Path) -> list[PushEntry]: +def collect_push_entries( + root: Path, + push: PushConfig | None = None, + *, + config_path: Path | None = None, + labremote_dir: Path | None = None, +) -> list[PushEntry]: """送信するファイルの一覧を作る(リンクは含まない.`select_push_files` を参照). Args: - root: プロジェクトルート. + root: プロジェクトのルート. + push: 設定の `push`. + config_path: 読み込んだ設定ファイル. + labremote_dir: LabRemote 自身のフォルダ. Returns: arcname 順に並べた送信対象. """ - return list(select_push_files(root).entries) + selection = select_push_files(root, push, config_path=config_path, labremote_dir=labremote_dir) + return list(selection.entries) diff --git a/tests/test_cli.py b/tests/test_cli.py index f2228d1..4b686cb 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -54,6 +54,7 @@ CONFIG_YAML = """\ project: name: DemoProject +push: {} jump_host: labpc connect_timeout_sec: 15 gpu_free: @@ -522,6 +523,13 @@ def test_dry_run_lists_code_but_not_excluded( self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: + # data・legacy・重みは設定の push に書いたときに送られない(SPEC_02「`push`」) + _write_config_data( + project, + lambda data: data.update( + push={"exclude_root": ["data", "legacy"], "exclude_suffixes": [".pth", ".onnx"]} + ), + ) for rel in [ "data/synthetic/manifest.csv", "runs/x/metrics.json", @@ -540,7 +548,8 @@ assert cli.main(["push", "--dry-run"]) == 0 out = capsys.readouterr().out assert "pyproject.toml" in out - assert "labremote.yaml" in out + # 設定ファイルはサーバで使わないため送らない(SPEC_01「安全の枠」) + assert "labremote.yaml" not in out assert "data/synthetic" not in out assert "runs/x" not in out assert ".claude" not in out @@ -1777,3 +1786,175 @@ assert script_tokens[i - 1] == "export" assert script_tokens[i + 1] == ";" assert "touch" not in script_tokens + + +# --------------------------------------------------------------------------- +# push の設定と固定の除外を cli.main から(SPEC_01「送信」・SPEC_02「`push`」) +# --------------------------------------------------------------------------- + +PUSH_SUBCOMMANDS = [ + ["gpus"], + ["status"], + ["push"], + ["push", "--dry-run"], + ["run", "--name", "t", "--", "x"], + ["pull", RUN_ID], +] + + +class TestPushSectionFromCli: + @pytest.mark.parametrize("subcommand", PUSH_SUBCOMMANDS) + @pytest.mark.parametrize("case", ["missing", "null"]) + def test_config_without_push_stops_before_ssh( + self, + project: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + subcommand: list[str], + case: str, + ) -> None: + """SPEC_02「`push`」: push の節が無い・null なら,どのサブコマンドも ssh を呼ばない.""" + + def mutate(data: dict) -> None: + if case == "missing": + del data["push"] + else: + data["push"] = None + + _write_config_data(project, mutate) + fake = FakeSsh({}) + monkeypatch.setattr(cli, "_run_ssh", fake) + with caplog.at_level(logging.ERROR): + assert cli.main(subcommand) == 1 + assert fake.calls == [] + assert "push: {}" in caplog.text + assert not (project / "runs").exists() + + +def _fake_labremote_at(monkeypatch: pytest.MonkeyPatch, repo: Path) -> None: + """実行中の labremote パッケージが repo/src/labremote/ にあるように見せる.""" + monkeypatch.setattr(cli.labremote, "__file__", str(repo / "src" / "labremote" / "__init__.py")) + + +class TestLabRemoteDirFromCli: + LABREMOTE_FILES = ["pyproject.toml", "src/labremote/__init__.py", "README.md"] + + @pytest.mark.parametrize("where", ["external/LabRemote", "tools/deps/lr"]) + def test_labremote_under_root_is_not_sent( + self, + project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + where: str, + ) -> None: + """SPEC_01「送信」: 実行中の labremote のリポジトリがルートの下なら,その下を送らない.""" + for rel in self.LABREMOTE_FILES: + path = project / where / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"x") + _fake_labremote_at(monkeypatch, project / where) + fake = FakeSsh({}) + monkeypatch.setattr(cli, "_run_ssh", fake) + names = _push_dry_run_names([], capsys) + assert not [name for name in names if name.startswith(f"{where}/")] + assert "pyproject.toml" in names + assert "src/demo_project/__init__.py" in names + assert fake.calls == [] + + def test_same_name_elsewhere_is_sent( + self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_01「送信」: 名前ではなく場所で除く(LabRemote でない external/LabRemote は送る).""" + (project / "external" / "LabRemote").mkdir(parents=True) + (project / "external" / "LabRemote" / "a.py").write_bytes(b"x") + (project / "vendor" / "lr").mkdir(parents=True) + (project / "vendor" / "lr" / "b.py").write_bytes(b"x") + _fake_labremote_at(monkeypatch, project / "vendor" / "lr") + monkeypatch.setattr(cli, "_run_ssh", FakeSsh({})) + names = _push_dry_run_names([], capsys) + assert "external/LabRemote/a.py" in names + assert "vendor/lr/b.py" not in names + + def test_real_labremote_location_is_this_repository(self) -> None: + """SPEC_01「送信」: LabRemote 自身は,実行中の labremote パッケージのリポジトリ.""" + repo = Path(__file__).resolve().parents[1] + assert cli._labremote_repo_dir() == repo + assert (cli._labremote_repo_dir() / "src" / "labremote" / "cli.py").is_file() + + def test_real_labremote_outside_project_excludes_nothing( + self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_01「送信」: 実際の LabRemote はルート(tmp_path)の外なので,何も除かれない.""" + (project / "external" / "LabRemote").mkdir(parents=True) + (project / "external" / "LabRemote" / "a.py").write_bytes(b"x") + monkeypatch.setattr(cli, "_run_ssh", FakeSsh({})) + names = _push_dry_run_names([], capsys) + assert sorted(names) == [ + "external/LabRemote/a.py", + "pyproject.toml", + "src/demo_project/__init__.py", + ] + + +class TestPushConfigFromCli: + def test_config_option_file_is_not_sent( + self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_01「送信」: `--config` で読んだ別の名前の設定ファイルも,ルートの直下の + labremote.yaml も送らない.""" + (project / "custom.yaml").write_text(CONFIG_YAML, encoding="utf-8") + monkeypatch.setattr(cli, "_run_ssh", FakeSsh({})) + names = _push_dry_run_names(["--config", str(project / "custom.yaml")], capsys) + assert "custom.yaml" not in names + assert "labremote.yaml" not in names + assert "pyproject.toml" in names + + def test_partial_and_exclusions_are_applied( + self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_02「`push`」: 設定の exclude_dirs・partial が push の一覧に効く.""" + _write_config_data( + project, + lambda data: data.update( + push={ + "exclude_dirs": ["wandb"], + "partial": [{"path": "external/Sub", "include": ["src", "README.md"]}], + } + ), + ) + for rel in [ + "external/Sub/src/a.py", + "external/Sub/README.md", + "external/Sub/docs/x.md", + "src/demo_project/wandb/run.log", + ]: + path = project / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"x") + monkeypatch.setattr(cli, "_run_ssh", FakeSsh({})) + names = _push_dry_run_names([], capsys) + assert sorted(names) == [ + "external/Sub/README.md", + "external/Sub/src/a.py", + "pyproject.toml", + "src/demo_project/__init__.py", + ] + + @pytest.mark.parametrize( + "push", + [ + {"no_fixed_exclude": True}, + {"exclude_root": ["da*ta"]}, + {"partial": [{"path": ".git/x", "include": ["a"]}]}, + {"partial": [{"path": "../x", "include": ["a"]}]}, + ], + ) + def test_bad_push_stops_before_ssh( + self, project: Path, monkeypatch: pytest.MonkeyPatch, push: dict + ) -> None: + """SPEC_02「`push`」: 書けない push は設定を読む時点でエラー(ssh を呼ばない).""" + _write_config_data(project, lambda data: data.update(push=push)) + fake = FakeSsh({}) + monkeypatch.setattr(cli, "_run_ssh", fake) + assert cli.main(["push"]) == 1 + assert fake.calls == [] diff --git a/tests/test_config.py b/tests/test_config.py index 2de8f12..2e6e251 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -30,6 +30,7 @@ def _base() -> dict: return { "project": {"name": "DemoProject"}, + "push": {}, "jump_host": "labpc", "connect_timeout_sec": 15, "gpu_free": { @@ -804,9 +805,13 @@ class TestDefaultsOfNewFields: def test_minimal_config(self, tmp_path: Path) -> None: - """SPEC_02 の既定: `jump_host` は null,`data_ready` は false,`uv` は既定,`env` は空.""" + """SPEC_02 の既定: `jump_host` は null,`data_ready` は false,`uv` は既定,`env` は空. + + `push` の節は省略できないため,最小の設定にも `push: {}` を書く(節の中の既定は空). + """ data = { "project": {"name": "DemoProject"}, + "push": {}, "servers": [{"name": "Newton", "priority": 1, "remote_dir": "~/work/x"}], } config = load_remote_config(_write(tmp_path, data)) @@ -816,3 +821,229 @@ assert server.uv == "~/.local/bin/uv" assert dict(server.env) == {} assert dict(config.run.env) == {} + assert config.push.exclude_root == () + assert config.push.exclude_dirs == () + assert config.push.exclude_suffixes == () + assert config.push.partial == () + + +# --------------------------------------------------------------------------- +# push(SPEC_02「`push`」) +# --------------------------------------------------------------------------- + + +def _push_data(push: object) -> dict: + data = _base() + data["push"] = push + return data + + +# 1 つの名前として書けないもの(exclude_root・exclude_dirs・partial の include で共通) +BAD_PUSH_NAMES: list[object] = [ + "a/b", + "a\\b", + "data/", + "*", + "da*ta", + "dat?", + "[d]ata", + ".", + "..", + "", + " data", + "data ", + "data\t", + "data\n", + "da\x00ta", + 1, + True, + None, + ["data"], +] + +FIXED_DIR_NAMES = [".git", ".venv", ".claude", "__pycache__", ".pytest_cache", ".ruff_cache"] + + +def _fixed_paths() -> list[str]: + paths = [] + for name in FIXED_DIR_NAMES: + paths += [name, f"{name}/x", f"a/{name}/x", f"a/b/{name}", name.upper() + "/x"] + paths += ["runs", "runs/x", "Runs/x", "labremote.yaml", "labremote.yaml/x", "LabRemote.YAML/x"] + return paths + + +class TestPushSection: + def test_missing_push_is_rejected_with_hint(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: push の節は省略できない(push: {} と書けばよいことを示す).""" + data = _base() + del data["push"] + with pytest.raises(ValidationError) as excinfo: + load_remote_config(_write(tmp_path, data)) + assert "push: {}" in str(excinfo.value) + + def test_null_push_is_rejected_with_hint(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: push: null も省略と同じくエラー.""" + with pytest.raises(ValidationError) as excinfo: + load_remote_config(_write(tmp_path, _push_data(None))) + assert "push: {}" in str(excinfo.value) + + def test_empty_push_loads_with_empty_defaults(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: push: {} は通り,節の中の既定は空.""" + push = load_remote_config(_write(tmp_path, _push_data({}))).push + assert (push.exclude_root, push.exclude_dirs, push.exclude_suffixes, push.partial) == ( + (), + (), + (), + (), + ) + + def test_values_are_loaded(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: 4 つのキーを読む(拡張子は小文字にそろえる).""" + push = load_remote_config( + _write( + tmp_path, + _push_data( + { + "exclude_root": ["data", "legacy"], + "exclude_dirs": ["wandb"], + "exclude_suffixes": [".PT", ".tar.gz"], + "partial": [{"path": "external/Sub", "include": ["src", "README.md"]}], + } + ), + ) + ).push + assert push.exclude_root == ("data", "legacy") + assert push.exclude_dirs == ("wandb",) + assert push.exclude_suffixes == (".pt", ".tar.gz") + assert push.partial[0].path == "external/Sub" + assert push.partial[0].include == ("src", "README.md") + + @pytest.mark.parametrize("push", ["", "data", ["data"], 1, True]) + def test_push_must_be_mapping(self, tmp_path: Path, push: object) -> None: + """SPEC_02「`push`」: push は節(キーと値)で書く.""" + _invalid(tmp_path, _push_data(push)) + + @pytest.mark.parametrize( + "push", + [ + {"exclude": ["data"]}, + {"include": ["data"]}, + {"no_fixed_exclude": True}, + {"fixed_exclude": []}, + {"allow_git": True}, + {"exclude_rot": ["data"]}, + {"partial": [{"path": "a", "include": ["src"], "exclude": ["x"]}]}, + {"partial": [{"path": "a", "include": ["src"], "allow_fixed": True}]}, + ], + ) + def test_unknown_keys_are_rejected(self, tmp_path: Path, push: dict) -> None: + """SPEC_02「`push`」: push・partial の下の未知のキー(固定の除外を外すキーを含む)は拒否.""" + _invalid(tmp_path, _push_data(push)) + + @pytest.mark.parametrize("key", ["exclude_root", "exclude_dirs"]) + @pytest.mark.parametrize("name", BAD_PUSH_NAMES) + def test_bad_exclude_names_are_rejected(self, tmp_path: Path, key: str, name: object) -> None: + """SPEC_02「`push`」: / \\ ワイルドカード . .. 空・前後の空白・NUL・文字列以外は書けない.""" + _invalid(tmp_path, _push_data({key: [name]})) + + @pytest.mark.parametrize("name", BAD_PUSH_NAMES) + def test_bad_include_names_are_rejected(self, tmp_path: Path, name: object) -> None: + """SPEC_02「`push`」: partial の include も 1 つの名前だけ(同じ規則).""" + _invalid(tmp_path, _push_data({"partial": [{"path": "ext/Sub", "include": [name]}]})) + + @pytest.mark.parametrize("key", ["exclude_root", "exclude_dirs", "exclude_suffixes"]) + def test_list_must_not_be_a_bare_string(self, tmp_path: Path, key: str) -> None: + """SPEC_02「`push`」: 一覧のキーに文字列を 1 つだけ書く書き間違いは拒否.""" + _invalid(tmp_path, _push_data({key: "data" if key != "exclude_suffixes" else ".pt"})) + + @pytest.mark.parametrize( + "suffix", + ["pt", "", ".", "..", ".p*", ".p?", ".[p]", "*.pt", ".pt/x", ".p\\t", " .pt", ".pt ", 1], + ) + def test_bad_suffixes_are_rejected(self, tmp_path: Path, suffix: object) -> None: + """SPEC_02「`push`」: exclude_suffixes は . で始まる拡張子(.・..・ワイルドカード不可).""" + _invalid(tmp_path, _push_data({"exclude_suffixes": [suffix]})) + + @pytest.mark.parametrize("suffix", [".pt", ".tar.gz", ".ONNX", ".x-y"]) + def test_good_suffixes_are_accepted(self, tmp_path: Path, suffix: str) -> None: + """SPEC_02「`push`」: . で始まる拡張子は書ける(小文字にそろえて持つ).""" + push = load_remote_config(_write(tmp_path, _push_data({"exclude_suffixes": [suffix]}))).push + assert push.exclude_suffixes == (suffix.lower(),) + + @pytest.mark.parametrize( + "path", + [ + "..", + "../x", + "a/../b", + "a/..", + "/x", + "/", + "C:/x", + "C:\\x", + "c:x", + "a\\b", + "x/*", + "x/s?c", + "[x]", + "", + "a//b", + "a/", + "./a", + "a/./b", + " a", + "a /b", + "a\x00", + 1, + None, + ], + ) + def test_bad_partial_paths_are_rejected(self, tmp_path: Path, path: object) -> None: + """SPEC_02「`push`」: partial の path に .. 絶対パス・ワイルドカード・空の部分は書けない.""" + _invalid(tmp_path, _push_data({"partial": [{"path": path, "include": ["src"]}]})) + + @pytest.mark.parametrize("path", _fixed_paths()) + def test_partial_path_inside_fixed_exclusion_is_rejected( + self, tmp_path: Path, path: str + ) -> None: + """SPEC_02「`push`」: 固定の除外の中を指す partial の path は書けない(大小文字問わず).""" + _invalid(tmp_path, _push_data({"partial": [{"path": path, "include": ["src"]}]})) + + @pytest.mark.parametrize( + "path", ["src/runs", "a/labremote.yaml", "external/Sub", "runs_old", "a/.gitx"] + ) + def test_partial_path_outside_fixed_exclusion_is_accepted( + self, tmp_path: Path, path: str + ) -> None: + """SPEC_02「`push`」: runs・labremote.yaml はルートの直下だけ(下の階層の同名は書ける).""" + push = load_remote_config( + _write(tmp_path, _push_data({"partial": [{"path": path, "include": ["src"]}]})) + ).push + assert push.partial[0].path == path + + @pytest.mark.parametrize( + ("path_a", "path_b"), + [ + ("a/b", "a/b"), + ("a/B", "A/b"), + ("a", "a/b"), + ("a/b", "a"), + ("A", "a/b/c"), + ], + ) + def test_duplicate_or_nested_partial_paths_are_rejected( + self, tmp_path: Path, path_a: str, path_b: str + ) -> None: + """SPEC_02「`push`」: 同じ path・一方が他方の中にある path は書けない.""" + partial = [{"path": path_a, "include": ["src"]}, {"path": path_b, "include": ["lib"]}] + _invalid(tmp_path, _push_data({"partial": partial})) + + def test_disjoint_partial_paths_are_accepted(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: 重ならない複数の partial は書ける(前方一致の名前は別の場所).""" + partial = [ + {"path": "ext/a", "include": ["src"]}, + {"path": "ext/ab", "include": ["lib"]}, + {"path": "vendor", "include": []}, + ] + push = load_remote_config(_write(tmp_path, _push_data({"partial": partial}))).push + assert [p.path for p in push.partial] == ["ext/a", "ext/ab", "vendor"] diff --git a/tests/test_files.py b/tests/test_files.py index 4a45d86..d1e6445 100644 --- a/tests/test_files.py +++ b/tests/test_files.py @@ -1,13 +1,12 @@ """push で送るファイルの選別のテスト(SPEC_03「push」). -`.git/`・`.venv/`・`__pycache__/`・`.pytest_cache/`・`.ruff_cache/` はどこにあっても送らない. -`data/`・`runs/`・`.claude/`・`legacy/` はプロジェクト直下のみ除外する -(`src/tongue_seg_model/data/`・`tests/data/` は送る). -重み(`.pt`・`.pth`・`.ckpt`・`.pb`・`.onnx`.大文字小文字を問わず)と `.env`・`.env.*` は -どの階層でも送らない(SPEC_03「移植で変える点」). +固定の除外(SPEC_01「安全の枠」の「送信」): `.git/`・`.venv/`・`.claude/`・`__pycache__/`・ +`.pytest_cache/`・`.ruff_cache/` はどこにあっても,`.env`・`.env.*` はどの階層でも,`runs/` と +`labremote.yaml` はルートの直下で送らない. -TIASJudgeModel の tests/remote/test_files.py の移植に,`legacy/`・重み・`.env` の除外と,実際の -リポジトリに対する確認を足した(`legacy/` の中は一覧しない.送信対象の一覧の側から確かめる). +設定の除外(SPEC_02「`push`」): 下の `PUSH` に,データ・原本(`data/`・`legacy/`.直下のみ)・ +重みの拡張子(大文字小文字を問わず)・一部だけ送るサブモジュール(`external/DemoSub`)を書き, +それらが送られないことを確かめる(`src/demo_project/data/`・`tests/data/` は送る). """ from __future__ import annotations @@ -18,8 +17,10 @@ import pytest from link_helpers import LinkFactory +from labremote.config import PartialPush, PushConfig from labremote.files import ( PushEntry, + PushRules, PushSelection, collect_push_entries, is_excluded, @@ -27,23 +28,32 @@ select_push_files, ) +# データ・原本・重み・サブモジュールの扱いを書いたテスト用の設定(利用する側の labremote.yaml の +# push に当たる).サブモジュールは,サーバで導入に要るものだけを送る +PUSH = PushConfig( + exclude_root=("data", "legacy"), + exclude_suffixes=(".pt", ".pth", ".ckpt", ".pb", ".onnx"), + partial=(PartialPush(path="external/DemoSub", include=("pyproject.toml", "README.md", "src")),), +) +RULES = PushRules.from_push(PUSH) + SENT = [ "pyproject.toml", "uv.lock", ".python-version", - "src/tongue_seg_model/__init__.py", - "src/tongue_seg_model/data/manifest.py", - "src/tongue_seg_model/remote/gpu.py", + "src/demo_project/__init__.py", + "src/demo_project/data/manifest.py", + "src/demo_project/remote/gpu.py", "tests/data/test_split.py", "tests/remote/test_gpu.py", "scripts/make_synthetic_dataset.py", "configs/remote.yaml", "configs/synthetic-gpu.yaml", - "src/tongue_seg_model/data/bundle.py", + "src/demo_project/data/bundle.py", "tests/data/original_tongue_seg_dataset.py", # 重みの拡張子に似ているが違うもの・.env に似ているが違うもの "docs/onnx.md", - "src/tongue_seg_model/export/onnx_export.py", + "src/demo_project/export/onnx_export.py", "scripts/pth_tool.py", "src/a.pth.py", ".envrc", @@ -51,25 +61,45 @@ "my.env", # legacy・data・runs を名前に含むがプロジェクト直下の別名 "legacy.md", - "src/tongue_seg_model/legacy/x.py", + "src/demo_project/legacy/x.py", "docs/legacy/a.md", "tests/runs/a.py", - # サブモジュール TIASDataHub は導入に要るものだけ - "external/TIASDataHub/pyproject.toml", - "external/TIASDataHub/README.md", - "external/TIASDataHub/src/tiasdata/__init__.py", - "external/TIASDataHub/src/tiasdata/catalog/migrations/catalog/0001_x.sql", + # サブモジュール DemoSub は導入に要るものだけ + "external/DemoSub/pyproject.toml", + "external/DemoSub/README.md", + "external/DemoSub/src/demosub/__init__.py", + "external/DemoSub/src/demosub/catalog/migrations/catalog/0001_x.sql", ] -NOT_SENT = [ +# 設定に関わらず送らないもの(固定の除外) +NOT_SENT_FIXED = [ ".git/config", ".git/objects/ab/cdef", ".venv/Scripts/python.exe", "__pycache__/x.pyc", - "src/tongue_seg_model/__pycache__/a.cpython-312.pyc", + "src/demo_project/__pycache__/a.cpython-312.pyc", "tests/data/__pycache__/b.pyc", ".pytest_cache/v/cache/nodeids", ".ruff_cache/0.1/x", + # 環境変数ファイル(秘密を含みうる) + ".env", + ".env.local", + "configs/.env", + "src/.ENV", + ".Env.production", + "runs/20260927-120000_x/metrics.json", + "runs/_remote_logs/exp1.log", + "Runs/x/metrics.json", + ".claude/settings.json", + ".claude/rules/testing.md", + "labremote.yaml", + "external/DemoSub/.git", + "external/DemoSub/.claude/settings.json", + "external/DemoSub/src/demosub/__pycache__/bundle.cpython-312.pyc", +] + +# 設定の push(上の PUSH)に書いたときに送らないもの +NOT_SENT_BY_CONFIG = [ "data/synthetic/manifest.csv", "data/synthetic/synthetic/v1/files/ab.png", # 原本(重みと,画像のファイル名を含む結果がある) @@ -80,39 +110,28 @@ "Legacy/source/main.py", "LEGACY/a.txt", "DATA/x.png", - "Runs/x/metrics.json", # 重み(どの階層でも・大文字小文字を問わず) "model.pt", "best.pth", - "src/tongue_seg_model/models/best.pth", + "src/demo_project/models/best.pth", "tests/fixtures/ResUNet.onnx", "scripts/x.ckpt", "configs/frozen.pb", "BEST.PTH", "a/b/c/Model.Onnx", "x.tar.pt", - # 環境変数ファイル(秘密を含みうる) - ".env", - ".env.local", - "configs/.env", - "src/.ENV", - ".Env.production", - "runs/20260927-120000_x/metrics.json", - "runs/_remote_logs/exp1.log", - ".claude/settings.json", - ".claude/rules/testing.md", - "external/TIASDataHub/.git", - "external/TIASDataHub/.claude/settings.json", - "external/TIASDataHub/.github/dependabot.yml", - "external/TIASDataHub/CLAUDE.md", - "external/TIASDataHub/uv.lock", - "external/TIASDataHub/docs/PROGRESS.md", - "external/TIASDataHub/tests/test_bundle.py", - "external/TIASDataHub/datasets/tongue_color.toml", - "external/TIASDataHub/reviews/r1.md", - "external/TIASDataHub/src/tiasdata/__pycache__/bundle.cpython-312.pyc", + # サブモジュールは partial の include に書いたものだけを送る + "external/DemoSub/.github/dependabot.yml", + "external/DemoSub/CLAUDE.md", + "external/DemoSub/uv.lock", + "external/DemoSub/docs/PROGRESS.md", + "external/DemoSub/tests/test_bundle.py", + "external/DemoSub/datasets/tongue_color.toml", + "external/DemoSub/reviews/r1.md", ] +NOT_SENT = NOT_SENT_FIXED + NOT_SENT_BY_CONFIG + def _make_tree(root: Path, paths: list[str]) -> None: for rel in paths: @@ -123,72 +142,77 @@ def test_collect_push_entries_excludes_listed_directories(tmp_path: Path) -> None: _make_tree(tmp_path, SENT + NOT_SENT) - arcnames = [entry.arcname for entry in collect_push_entries(tmp_path)] + arcnames = [entry.arcname for entry in collect_push_entries(tmp_path, PUSH)] assert sorted(arcnames) == sorted(SENT) def test_arcnames_are_posix_relative(tmp_path: Path) -> None: - _make_tree(tmp_path, ["src/tongue_seg_model/data/manifest.py"]) + _make_tree(tmp_path, ["src/demo_project/data/manifest.py"]) entries = collect_push_entries(tmp_path) - assert [e.arcname for e in entries] == ["src/tongue_seg_model/data/manifest.py"] + assert [e.arcname for e in entries] == ["src/demo_project/data/manifest.py"] assert entries[0].size == 1 +@pytest.mark.parametrize("rel", NOT_SENT_FIXED) +def test_fixed_exclusions_apply_without_config(rel: str) -> None: + assert is_excluded(rel) + + @pytest.mark.parametrize("rel", NOT_SENT) def test_is_excluded_for_not_sent(rel: str) -> None: - assert is_excluded(rel) + assert is_excluded(rel, rules=RULES) @pytest.mark.parametrize("rel", SENT) def test_is_not_excluded_for_sent(rel: str) -> None: - assert not is_excluded(rel) + assert not is_excluded(rel, rules=RULES) @pytest.mark.parametrize( "rel", ["data", "runs", ".claude", ".git", ".venv", "legacy", "Legacy", "src/__pycache__"] ) def test_root_directories_themselves_are_excluded(rel: str) -> None: - assert is_excluded(rel) + assert is_excluded(rel, rules=RULES) @pytest.mark.parametrize( - "rel", ["src/tongue_seg_model/data", "tests/data", "src/tongue_seg_model/runs_util.py"] + "rel", ["src/demo_project/data", "tests/data", "src/demo_project/runs_util.py"] ) def test_nested_data_is_not_excluded(rel: str) -> None: - assert not is_excluded(rel) + assert not is_excluded(rel, rules=RULES) -# --- サブモジュール external/TIASDataHub/ --- +# --- サブモジュール external/DemoSub/ --- -@pytest.mark.parametrize("rel", ["external", "external/TIASDataHub"]) +@pytest.mark.parametrize("rel", ["external", "external/DemoSub"]) def test_submodule_parent_directories_are_walked(rel: str) -> None: - assert not is_excluded(rel) + assert not is_excluded(rel, is_dir=True, rules=RULES) @pytest.mark.parametrize( "rel", [ - "external/TIASDataHub/src", - "external/TIASDataHub/pyproject.toml", - "external/TIASDataHub/README.md", + "external/DemoSub/src", + "external/DemoSub/pyproject.toml", + "external/DemoSub/README.md", ], ) def test_submodule_sent_entries_are_not_excluded(rel: str) -> None: - assert not is_excluded(rel) + assert not is_excluded(rel, rules=RULES) @pytest.mark.parametrize( "rel", [ - "external/TIASDataHub/docs", - "external/TIASDataHub/tests", - "external/TIASDataHub/.claude", - "external/TIASDataHub/datasets", + "external/DemoSub/docs", + "external/DemoSub/tests", + "external/DemoSub/.claude", + "external/DemoSub/datasets", ], ) def test_submodule_other_directories_are_excluded(rel: str) -> None: - assert is_excluded(rel) + assert is_excluded(rel, is_dir=True, rules=RULES) @pytest.mark.parametrize( @@ -196,26 +220,40 @@ [ # 同じ名前でも submodule の直下でなければ規則の対象外 "external/Other/docs/a.md", - "external/TIASDataHub2/docs/a.md", - "src/external/TIASDataHub/docs/a.md", + "external/DemoSub2/docs/a.md", + "src/external/DemoSub/docs/a.md", # submodule の src の下は名前によらず送る - "external/TIASDataHub/src/tiasdata/docs/a.md", - "external/TIASDataHub/src/tiasdata/tests/a.py", + "external/DemoSub/src/demosub/docs/a.md", + "external/DemoSub/src/demosub/tests/a.py", ], ) def test_submodule_rule_is_limited_to_its_top_level(rel: str) -> None: - assert not is_excluded(rel) + assert not is_excluded(rel, rules=RULES) -def test_repository_submodule_sends_only_install_files() -> None: - root = Path(__file__).resolve().parents[1] - if not (root / "external" / "TIASDataHub" / "pyproject.toml").is_file(): - pytest.skip("サブモジュールが展開されていない") - prefix = "external/TIASDataHub/" - sent = [e.arcname for e in collect_push_entries(root) if e.arcname.startswith(prefix)] +def test_submodule_sends_only_install_files(tmp_path: Path) -> None: + """サブモジュールに見立てたフォルダから,partial の include に書いたものだけを送る.""" + prefix = "external/DemoSub/" + _make_tree( + tmp_path, + [ + "pyproject.toml", + f"{prefix}pyproject.toml", + f"{prefix}README.md", + f"{prefix}src/demosub/bundle.py", + f"{prefix}.git", + f"{prefix}.claude/settings.json", + f"{prefix}CLAUDE.md", + f"{prefix}uv.lock", + f"{prefix}docs/PROGRESS.md", + f"{prefix}tests/test_bundle.py", + f"{prefix}datasets/x.toml", + ], + ) + sent = [e.arcname for e in collect_push_entries(tmp_path, PUSH) if e.arcname.startswith(prefix)] assert f"{prefix}pyproject.toml" in sent assert f"{prefix}README.md" in sent - assert f"{prefix}src/tiasdata/bundle.py" in sent + assert f"{prefix}src/demosub/bundle.py" in sent assert {name.removeprefix(prefix).split("/")[0] for name in sent} == { "pyproject.toml", "README.md", @@ -229,16 +267,17 @@ @pytest.mark.parametrize("rel", ["models.onnx", "src/weights.pth", ".env.d"]) def test_directory_names_are_not_matched_by_file_rules(rel: str) -> None: # 拡張子・.env の除外はファイルだけに当てはめる(中のファイルは名前で判断する) - assert not is_excluded(rel, is_dir=True) + assert not is_excluded(rel, is_dir=True, rules=RULES) def test_files_inside_weight_like_directory(tmp_path: Path) -> None: _make_tree(tmp_path, ["models.onnx/readme.md", "models.onnx/w.ONNX"]) - assert [e.arcname for e in collect_push_entries(tmp_path)] == ["models.onnx/readme.md"] + entries = collect_push_entries(tmp_path, PUSH) + assert [e.arcname for e in entries] == ["models.onnx/readme.md"] def test_legacy_directory_is_not_walked(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """`legacy/`・`data/`・`runs/` の中は列挙もしない(ファイル名を読まない).""" + """設定で除いた `legacy/`・`data/` と,`runs/` の中は列挙もしない(ファイル名を読まない).""" import os _make_tree(tmp_path, ["legacy/result/x.csv", "data/a.png", "runs/r/log.txt", "src/a.py"]) @@ -251,7 +290,7 @@ yield dirpath, dirnames, filenames monkeypatch.setattr("labremote.files.os.walk", spy_walk) - assert [e.arcname for e in collect_push_entries(tmp_path)] == ["src/a.py"] + assert [e.arcname for e in collect_push_entries(tmp_path, PUSH)] == ["src/a.py"] assert not any(v.split("/")[0] in {"legacy", "data", "runs"} for v in visited) @@ -270,7 +309,7 @@ def _repository_entries() -> list[str]: - return [e.arcname for e in collect_push_entries(REPO_ROOT)] + return [e.arcname for e in collect_push_entries(REPO_ROOT, PUSH)] def test_repository_push_has_no_legacy_data_runs_or_weights() -> None: @@ -314,12 +353,12 @@ """tmp_path の中に「リポジトリ役」と「外役」の 2 つのフォルダを作る.""" repo = tmp_path / "repo" outside = tmp_path / "outside" - _make_tree(repo, ["pyproject.toml", "src/tongue_seg_model/__init__.py"]) + _make_tree(repo, ["pyproject.toml", "src/demo_project/__init__.py"]) _make_tree(outside, ["secret.py", "patients/P0001.png", "sub/code.py"]) return repo, outside -REPO_CODE = ["pyproject.toml", "src/tongue_seg_model/__init__.py"] +REPO_CODE = ["pyproject.toml", "src/demo_project/__init__.py"] def _arcnames(root: Path) -> list[str]: @@ -367,9 +406,9 @@ def test_collect_push_entries_is_selection_entries(self, tmp_path: Path) -> None: _make_tree(tmp_path, SENT + NOT_SENT) - entries = collect_push_entries(tmp_path) + entries = collect_push_entries(tmp_path, PUSH) assert isinstance(entries, list) - assert entries == list(select_push_files(tmp_path).entries) + assert entries == list(select_push_files(tmp_path, PUSH).entries) class TestFileLinks: @@ -434,7 +473,7 @@ _make_tree(repo, ["legacy/result/r.csv", "data/a.png", "src/a.py"]) getattr(links, kind)(repo / "src" / "old", repo / "legacy") getattr(links, kind)(repo / "src" / "d", repo / "data") - selection = select_push_files(repo) + selection = select_push_files(repo, PUSH) assert [e.arcname for e in selection.entries] == ["src/a.py"] assert selection.skipped_links == ("src/d", "src/old") @@ -496,3 +535,380 @@ links.symlink(repo / "a" / "dir", outside / "sub") selection = select_push_files(repo) assert selection.skipped_links == ("a/dir", "src/b/a.py", "z.py") + + +# --------------------------------------------------------------------------- +# 固定の除外は設定に関わらず効き,設定で減らせない(SPEC_01「安全の枠」の「送信」) +# --------------------------------------------------------------------------- + +FIXED_DIR_NAMES = [".git", ".venv", ".claude", "__pycache__", ".pytest_cache", ".ruff_cache"] +# 固定の除外のフォルダを置く場所(ルートの直下・2 段下・partial の include の下) +FIXED_DIR_PREFIXES = ["", "a/b/", "vendor/Sub/src/"] +# 一部だけ送るフォルダの include に,固定の除外の名前を書いた設定(書いても送られない) +PARTIAL_WITH_FIXED_NAMES = PushConfig( + partial=( + PartialPush( + path="vendor/Sub", + include=("src", *FIXED_DIR_NAMES, ".env", ".env.local", "runs", "labremote.yaml"), + ), + ) +) +# 送るべきもの(空の一覧で通ってしまわないための対照) +FIXED_CONTROL_SENT = [ + "pyproject.toml", + "a/b/code.py", + "vendor/Sub/src/pkg.py", + # ルートの直下でない runs・labremote.yaml は送る + "src/runs/x.py", + "sub/labremote.yaml", + "vendor/Sub/src/runs/y.py", +] + + +def _fixed_not_sent() -> list[str]: + names = [f"{prefix}{name}/f.txt" for prefix in FIXED_DIR_PREFIXES for name in FIXED_DIR_NAMES] + names += [f"{prefix}{env}" for prefix in FIXED_DIR_PREFIXES for env in [".env", ".env.prod"]] + names += ["runs/r1/metrics.json", "runs/_remote_logs/a.log", "labremote.yaml"] + # partial の include に書いた固定の除外の名前(vendor/Sub の直下) + names += [ + "vendor/Sub/.git", + "vendor/Sub/.venv/x.py", + "vendor/Sub/.claude/settings.json", + "vendor/Sub/__pycache__/a.pyc", + "vendor/Sub/.env", + "vendor/Sub/.env.local", + ] + return names + + +class TestFixedExclusionsInTree: + @pytest.mark.parametrize( + "push", + [None, PushConfig(), PUSH, PARTIAL_WITH_FIXED_NAMES], + ids=["none", "empty", "PUSH", "partial-fixed"], + ) + def test_fixed_exclusions_are_never_sent(self, tmp_path: Path, push: PushConfig | None) -> None: + """SPEC_01「送信」: 固定の除外は,push に何を書いても(`{}` を含む)送られない.""" + not_sent = _fixed_not_sent() + _make_tree(tmp_path, FIXED_CONTROL_SENT + not_sent) + sent = {e.arcname for e in collect_push_entries(tmp_path, push)} + assert not sent & set(not_sent) + for name in sent: + parts = name.lower().split("/") + assert not set(parts) & set(FIXED_DIR_NAMES), name + assert parts[-1] != ".env" and not parts[-1].startswith(".env."), name + assert parts[0] not in {"runs", "labremote.yaml"}, name + assert {"pyproject.toml", "a/b/code.py", "vendor/Sub/src/pkg.py"} <= sent + + def test_empty_push_sends_everything_else(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: `push: {}` では固定の除外だけが効く(他は全部送る).""" + not_sent = _fixed_not_sent() + _make_tree(tmp_path, FIXED_CONTROL_SENT + not_sent) + sent = [e.arcname for e in collect_push_entries(tmp_path, PushConfig())] + assert sorted(sent) == sorted(FIXED_CONTROL_SENT) + + @pytest.mark.parametrize( + "rel", ["src/runs/x.py", "sub/labremote.yaml", "a/runs", "docs/labremote.yaml"] + ) + def test_runs_and_config_name_below_root_are_sent(self, rel: str) -> None: + """SPEC_01「送信」: 結果の置き場と labremote.yaml の除外はルートの直下だけ.""" + assert not is_excluded(rel, rules=PushRules.from_push(PushConfig())) + + @pytest.mark.parametrize("rel", ["Labremote.yaml", "LABREMOTE.YAML", "RUNS/a.txt", ".GIT/x"]) + def test_fixed_names_are_compared_in_lower_case(self, rel: str) -> None: + """SPEC_01「送信」: 固定の除外は大文字小文字の違いでは外れない.""" + assert is_excluded(rel) + + +class TestConfigFileIsNotSent: + @pytest.mark.parametrize("rel", ["custom.yaml", "cfg/my-remote.yaml", "labremote.yaml"]) + def test_loaded_config_file_is_not_sent(self, tmp_path: Path, rel: str) -> None: + """SPEC_01「送信」: 読み込んだ設定ファイルは,名前・場所によらず送らない.""" + _make_tree(tmp_path, ["pyproject.toml", "cfg/other.yaml", rel]) + sent = [ + e.arcname + for e in collect_push_entries(tmp_path, PushConfig(), config_path=tmp_path / rel) + ] + assert rel not in sent + assert "pyproject.toml" in sent + assert "cfg/other.yaml" in sent + + def test_config_outside_root_excludes_nothing(self, tmp_path: Path) -> None: + """SPEC_01「送信」: ルートの外の設定ファイルを指定しても,ルートの下は何も除かれない.""" + root = tmp_path / "proj" + _make_tree(root, ["pyproject.toml", "custom.yaml"]) + _make_tree(tmp_path, ["custom.yaml"]) + sent = [ + e.arcname + for e in collect_push_entries(root, PushConfig(), config_path=tmp_path / "custom.yaml") + ] + assert sorted(sent) == ["custom.yaml", "pyproject.toml"] + + +# --------------------------------------------------------------------------- +# LabRemote 自身のフォルダを送らない(SPEC_01「送信」「プロジェクトからの使い方」) +# --------------------------------------------------------------------------- + +LABREMOTE_FILES = ["pyproject.toml", "src/labremote/cli.py", "README.md", "docs/a.md"] + + +class TestLabRemoteDirIsNotSent: + @pytest.mark.parametrize("where", ["external/LabRemote", "LabRemote", "deps/x/y/tools-lr"]) + def test_labremote_under_root_is_not_sent(self, tmp_path: Path, where: str) -> None: + """SPEC_01「送信」: LabRemote のフォルダがルートの下にあれば,その下を 1 件も送らない.""" + _make_tree(tmp_path, ["pyproject.toml", "src/app.py"]) + _make_tree(tmp_path / where, LABREMOTE_FILES) + sent = [ + e.arcname + for e in collect_push_entries(tmp_path, PushConfig(), labremote_dir=tmp_path / where) + ] + assert not [name for name in sent if name.startswith(f"{where}/")] + assert sorted(sent) == ["pyproject.toml", "src/app.py"] + + def test_exclusion_is_by_location_not_by_name(self, tmp_path: Path) -> None: + """SPEC_01「送信」: 名前ではなく場所で除く(同じ名前でも LabRemote でなければ送る).""" + _make_tree(tmp_path, ["pyproject.toml"]) + _make_tree(tmp_path / "external/LabRemote", ["a.py"]) + _make_tree(tmp_path / "vendor/lr", LABREMOTE_FILES) + sent = [ + e.arcname + for e in collect_push_entries( + tmp_path, PushConfig(), labremote_dir=tmp_path / "vendor/lr" + ) + ] + assert "external/LabRemote/a.py" in sent + assert not [name for name in sent if name.startswith("vendor/lr/")] + + def test_sibling_with_common_prefix_is_sent(self, tmp_path: Path) -> None: + """SPEC_01「送信」: 除くのは LabRemote のフォルダの下だけ(名前の前方一致で広げない).""" + _make_tree(tmp_path, ["external/LabRemote2/a.py", "external/LabRemote.md"]) + _make_tree(tmp_path / "external/LabRemote", LABREMOTE_FILES) + sent = [ + e.arcname + for e in collect_push_entries( + tmp_path, PushConfig(), labremote_dir=tmp_path / "external/LabRemote" + ) + ] + assert sorted(sent) == ["external/LabRemote.md", "external/LabRemote2/a.py"] + + @pytest.mark.parametrize("case", ["root", "outside", "none"]) + def test_labremote_at_root_or_outside_excludes_nothing(self, tmp_path: Path, case: str) -> None: + """SPEC_01「送信」: ルートそのもの・ルートの外・指定が無いときは,何も除かない.""" + root = tmp_path / "proj" + files = ["pyproject.toml", "src/labremote/cli.py", "external/LabRemote/a.py"] + _make_tree(root, files) + labremote_dir = {"root": root, "outside": tmp_path / "LabRemote", "none": None}[case] + if case == "outside": + _make_tree(tmp_path / "LabRemote", LABREMOTE_FILES) + sent = [ + e.arcname for e in collect_push_entries(root, PushConfig(), labremote_dir=labremote_dir) + ] + assert sorted(sent) == sorted(files) + + def test_labremote_dir_is_excluded_even_inside_partial_include(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: LabRemote 自身は partial の include に書いても送られない.""" + push = PushConfig(partial=(PartialPush(path="external", include=("LabRemote", "Other")),)) + _make_tree(tmp_path, ["pyproject.toml", "external/Other/a.py"]) + _make_tree(tmp_path / "external/LabRemote", LABREMOTE_FILES) + sent = [ + e.arcname + for e in collect_push_entries( + tmp_path, push, labremote_dir=tmp_path / "external/LabRemote" + ) + ] + assert sorted(sent) == ["external/Other/a.py", "pyproject.toml"] + + +# --------------------------------------------------------------------------- +# 設定で足す除外(SPEC_02「`push`」) +# --------------------------------------------------------------------------- + + +def _sent(root: Path, push: PushConfig) -> list[str]: + return sorted(e.arcname for e in collect_push_entries(root, push)) + + +class TestConfigExclusions: + def test_exclude_root_applies_only_at_root(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: exclude_root はルートの直下だけ.フォルダにもファイルにも効く.""" + _make_tree( + tmp_path, + ["data/a.png", "Data2/a.png", "notes.txt", "src/pkg/data/x.py", "src/notes.txt"], + ) + push = PushConfig(exclude_root=("data", "notes.txt")) + assert _sent(tmp_path, push) == ["Data2/a.png", "src/notes.txt", "src/pkg/data/x.py"] + + def test_exclude_root_is_compared_in_lower_case(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: data と書けば Data/ も送らない.""" + _make_tree(tmp_path, ["Data/a.png", "keep.py"]) + assert _sent(tmp_path, PushConfig(exclude_root=("data",))) == ["keep.py"] + + def test_exclude_root_written_in_upper_case(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: exclude_root は小文字にして比べる(設定を大文字で書いても効く).""" + _make_tree(tmp_path, ["data/a.png", "keep.py"]) + assert _sent(tmp_path, PushConfig(exclude_root=("DATA",))) == ["keep.py"] + + def test_exclude_dirs_applies_at_any_depth_and_to_files(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: exclude_dirs はどの階層でも効き,同じ名前のファイルも送らない.""" + _make_tree( + tmp_path, + ["wandb/a.log", "src/x/wandb/b.log", "src/Wandb/c.log", "a/wandb", "keep/wandb2.py"], + ) + assert _sent(tmp_path, PushConfig(exclude_dirs=("wandb",))) == ["keep/wandb2.py"] + + def test_exclude_suffixes(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: 拡張子はどの階層でも小文字で比べ,.tar.gz も効く.""" + _make_tree( + tmp_path, + ["A.PT", "src/m/b.pt", "x.tar.gz", "y.gz", "z.tar", "p.pt.py", "deep/a/b/c.Tar.Gz"], + ) + push = PushConfig(exclude_suffixes=(".pt", ".tar.gz")) + assert _sent(tmp_path, push) == ["p.pt.py", "y.gz", "z.tar"] + + def test_exclude_suffixes_written_in_upper_case(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: 拡張子は小文字にして比べる(設定の側を大文字で書いても効く).""" + _make_tree(tmp_path, ["a.pt", "b.PT", "keep.py"]) + assert _sent(tmp_path, PushConfig(exclude_suffixes=(".PT",))) == ["keep.py"] + + def test_suffix_is_not_applied_to_directory_names(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: フォルダの名前には拡張子の除外を当てはめない(中は名前で判断).""" + _make_tree(tmp_path, ["models.onnx/readme.md", "models.onnx/w.onnx", "x.tar.gz/a.txt"]) + push = PushConfig(exclude_suffixes=(".onnx", ".tar.gz")) + assert _sent(tmp_path, push) == ["models.onnx/readme.md", "x.tar.gz/a.txt"] + + +# --------------------------------------------------------------------------- +# partial(SPEC_02「`push`」) +# --------------------------------------------------------------------------- + + +class TestPartial: + def test_only_include_names_are_sent(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: path の直下のうち,include に書いた名前だけを送る.""" + _make_tree(tmp_path, ["ext/Sub/src/a.py", "ext/Sub/README.md", "ext/Sub/docs/x.md"]) + push = PushConfig(partial=(PartialPush(path="ext/Sub", include=("src", "README.md")),)) + assert _sent(tmp_path, push) == ["ext/Sub/README.md", "ext/Sub/src/a.py"] + + def test_include_is_case_sensitive(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: include は大文字小文字を区別する(src と書いて Src なら送らない).""" + _make_tree(tmp_path, ["ext/Sub/Src/a.py", "ext/Sub/readme.md", "keep.py"]) + push = PushConfig(partial=(PartialPush(path="ext/Sub", include=("src", "README.md")),)) + assert _sent(tmp_path, push) == ["keep.py"] + + def test_path_is_compared_in_lower_case(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: partial の path は小文字にして比べる.""" + _make_tree(tmp_path, ["Ext/SUB/src/a.py", "Ext/SUB/docs/x.md"]) + push = PushConfig(partial=(PartialPush(path="ext/sub", include=("src",)),)) + assert _sent(tmp_path, push) == ["Ext/SUB/src/a.py"] + + def test_other_exclusions_apply_inside_include(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: include の中身にも固定の除外・exclude_dirs・exclude_suffixes.""" + _make_tree( + tmp_path, + [ + "ext/Sub/src/a.py", + "ext/Sub/src/w.pt", + "ext/Sub/src/cache/x.py", + "ext/Sub/src/__pycache__/a.pyc", + "ext/Sub/src/.env", + "ext/Sub/src/.git/HEAD", + ], + ) + push = PushConfig( + exclude_dirs=("cache",), + exclude_suffixes=(".pt",), + partial=(PartialPush(path="ext/Sub", include=("src",)),), + ) + assert _sent(tmp_path, push) == ["ext/Sub/src/a.py"] + + @pytest.mark.parametrize("case", ["missing", "file", "empty-include"]) + def test_nothing_is_sent_without_error(self, tmp_path: Path, case: str) -> None: + """SPEC_02「`push`」: path が無い・path がファイル・include が空なら何も送らない.""" + _make_tree(tmp_path, ["keep.py"]) + if case == "file": + _make_tree(tmp_path, ["ext/Sub"]) + if case == "empty-include": + _make_tree(tmp_path, ["ext/Sub/src/a.py", "ext/Sub/README.md"]) + include = () if case == "empty-include" else ("src",) + push = PushConfig(partial=(PartialPush(path="ext/Sub", include=include),)) + assert _sent(tmp_path, push) == ["keep.py"] + + @pytest.mark.parametrize( + ("exclude_root", "path", "files"), + [ + ("ext", "ext/Sub", ["ext/Sub/src/a.py"]), + ("data", "data", ["data/src/a.py"]), + ("DATA", "data", ["data/src/a.py"]), + ], + ) + def test_exclude_root_wins_over_partial( + self, tmp_path: Path, exclude_root: str, path: str, files: list[str] + ) -> None: + """SPEC_02「`push`」: exclude_root と partial の path が重なる場合は,除外が優先.""" + _make_tree(tmp_path, [*files, "keep.py"]) + push = PushConfig( + exclude_root=(exclude_root,), partial=(PartialPush(path=path, include=("src",)),) + ) + assert _sent(tmp_path, push) == ["keep.py"] + + def test_multiple_partials_each_apply(self, tmp_path: Path) -> None: + """SPEC_02「`push`」: 重ならない複数の partial が,それぞれ効く.""" + _make_tree( + tmp_path, + ["ext/A/src/a.py", "ext/A/docs/x.md", "ext/B/lib/b.py", "ext/B/src/c.py", "ext/C/x.py"], + ) + push = PushConfig( + partial=( + PartialPush(path="ext/A", include=("src",)), + PartialPush(path="ext/B", include=("lib",)), + ) + ) + assert _sent(tmp_path, push) == ["ext/A/src/a.py", "ext/B/lib/b.py", "ext/C/x.py"] + + +# --------------------------------------------------------------------------- +# 設定を入れてもリンクは送らない(SPEC_01「送信」) +# --------------------------------------------------------------------------- + + +class TestLinksWithPushConfig: + @pytest.mark.parametrize("kind", ["symlink", "junction"]) + def test_link_named_in_partial_include_is_not_walked( + self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str + ) -> None: + """SPEC_01「送信」: include に書いた名前がリンクでも,送らず中にも入らない.""" + repo, outside = repo_and_outside + getattr(links, kind)(repo / "ext" / "Sub" / "src", outside) + push = PushConfig(partial=(PartialPush(path="ext/Sub", include=("src",)),)) + selection = select_push_files(repo, push) + assert [e.arcname for e in selection.entries] == REPO_CODE + assert selection.skipped_links == ("ext/Sub/src",) + assert _nothing_from(outside, selection.entries) + + @pytest.mark.parametrize("kind", ["symlink", "junction"]) + def test_link_is_not_sent_with_permissive_config( + self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str + ) -> None: + """SPEC_01「送信」: push に何を書いても,リンクのフォルダは送らず中にも入らない.""" + repo, outside = repo_and_outside + getattr(links, kind)(repo / "src" / "ext", outside) + push = PushConfig( + exclude_dirs=("unrelated",), + exclude_suffixes=(".pt",), + partial=(PartialPush(path="src", include=("ext", "demo_project")),), + ) + selection = select_push_files(repo, push) + assert [e.arcname for e in selection.entries] == REPO_CODE + assert selection.skipped_links == ("src/ext",) + assert _nothing_from(outside, selection.entries) + + def test_file_symlink_in_partial_include_is_not_sent( + self, repo_and_outside: tuple[Path, Path], links: LinkFactory + ) -> None: + """SPEC_01「送信」: include に書いた名前のファイルがリンクでも送らない.""" + repo, outside = repo_and_outside + links.symlink(repo / "ext" / "Sub" / "README.md", outside / "secret.py") + push = PushConfig(partial=(PartialPush(path="ext/Sub", include=("README.md",)),)) + selection = select_push_files(repo, push) + assert [e.arcname for e in selection.entries] == REPO_CODE + assert selection.skipped_links == ("ext/Sub/README.md",)