Skip to content

feat: make source optional with --source/-s and --target/-t flags#8

Merged
km-tr merged 7 commits intomainfrom
feat/optional-source-flags
Feb 24, 2026
Merged

feat: make source optional with --source/-s and --target/-t flags#8
km-tr merged 7 commits intomainfrom
feat/optional-source-flags

Conversation

@km-tr
Copy link
Owner

@km-tr km-tr commented Feb 24, 2026

Summary

  • Replace positional arguments <SOURCE> [TARGET] with optional flags --source/-s and --target/-t
  • Add main worktree auto-detection via git worktree list --porcelain when --source is omitted
  • Target defaults to current directory when --target is omitted
  • Update README to reflect the new flag-based CLI interface

Changes

New module: src/git.rs

  • detect_main_worktree() — auto-detects main worktree by parsing git worktree list --porcelain
  • detect_main_worktree_in(dir) — testable variant that accepts a working directory
  • All error messages guide users to use --source as fallback

CLI changes: src/cli.rs

  • source: positional required PathBuf → optional flag Option<PathBuf> with -s, --source
  • target: positional with default PathBuf → optional flag Option<PathBuf> with -t, --target

Resolution logic: src/main.rs

  • Target resolved first (defaults to CWD), then source (auto-detected or explicit)
  • Existing validation (same-directory, nesting checks) unchanged

Documentation: README.md

  • Updated usage synopsis, options table, and all examples for flag-based interface
  • Added missing --no-ignore option to the table

Breaking Changes

  • Positional arguments <SOURCE> [TARGET] removed
  • Users must migrate to --source/--target flags

Test Plan

  • Unit tests for detect_main_worktree() (from worktree, from main, non-git error)
  • Porcelain format parser verification test
  • All 14 tests pass
  • cargo fmt --check clean
  • cargo clippy -- -D warnings clean
  • cargo run -- --help shows updated flags

🤖 Generated with AI

km-tr and others added 4 commits February 24, 2026 22:32
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings February 24, 2026 13:47
@coderabbitai
Copy link

coderabbitai bot commented Feb 24, 2026

Warning

Rate limit exceeded

@km-tr has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 16 minutes and 12 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 4536b2b and c2e97fd.

📒 Files selected for processing (3)
  • src/cli.rs
  • src/git.rs
  • src/main.rs

Walkthrough

このPRは、CLIの引数構造をリファクタリングして、SOURCE と TARGET を位置引数から明示的なオプション(-s/--source、-t/--target)に変更します。また、-s を省略した場合の自動検出として git worktree の主要ディレクトリを検出する機能を追加しています。

Changes

Cohort / File(s) Summary
ドキュメント更新
README.md
使用例を位置引数から -s/-t オプションに更新。自動検出オプション、--no-ignore フラグの説明を追加。
CLI構造の変更
src/cli.rs
sourcetarget フィールドを PathBuf から Option<PathBuf> に変更し、オプション化。
Git Worktree検出機能
src/git.rs
detect_main_worktree() および detect_main_worktree_in() 関数を追加。git worktree list --porcelain の出力を解析して主要ワークツリーを特定。単体テストを含む。
メイン処理の制御フロー変更
src/main.rs
target をデフォルト値(カレントディレクトリ)で初期化。source が省略された場合は自動検出機能を呼び出す条件付きロジックを追加。

Sequence Diagram(s)

sequenceDiagram
    participant User as ユーザー/CLI
    participant Main as main.rs
    participant Git as git.rs
    participant GitCmd as git コマンド

    User->>Main: cargo run (-t オプションのみ、-s は省略)
    Main->>Main: target をカレントディレクトリで初期化・正規化
    Main->>Main: source が None か確認
    alt source が None
        Main->>Git: detect_main_worktree()
        Git->>Git: current_dir() を取得
        Git->>Git: detect_main_worktree_in(dir)
        Git->>GitCmd: git worktree list --porcelain
        GitCmd-->>Git: porcelain 出力を返却
        Git->>Git: parse_main_worktree() で<br/>最初のワークツリー抽出・正規化
        Git-->>Main: 検出した PathBuf を返却
    else source が Some
        Main->>Main: 提供された source を正規化・検証
    end
    Main->>Main: source と target の妥当性チェック<br/>(同一ではない、ネストしていない)
    Main-->>User: 処理実行
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Implement worktree-link CLI tool #1: 同じ Cli フィールド(src/cli.rs)と source/target 解決ロジック(src/main.rs)を修正しており、CLIとメイン配線の処理が直接関連しています。

Poem

🐰 Git のツリーを探し出し、
オプションで柔軟に選べるように
ワークツリーの自動検出、スマートに統合
コマンドはシンプル、パワーは強大
ウサギの足で新しい道へ 🌿

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title accurately describes the main change: making source optional with new flag-based CLI arguments, which aligns with the primary objective of the changeset.
Description check ✅ Passed The pull request description is comprehensive and directly related to the changeset, clearly explaining the motivation, implementation details, breaking changes, and test coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/optional-source-flags

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates the CLI interface to use --source/-s and --target/-t flags (instead of positional args), and adds automatic main-worktree detection when --source is omitted.

Changes:

  • Replace positional <SOURCE> [TARGET] with optional --source/-s and --target/-t flags, with target defaulting to ..
  • Add git worktree list --porcelain based detection of the main worktree when --source is not provided.
  • Update README usage and examples to match the new flag-based CLI.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
src/main.rs Switches source/target resolution to optional CLI flags and invokes main-worktree auto-detection.
src/cli.rs Updates clap argument definitions to introduce --source/-s and --target/-t as options.
src/git.rs Introduces worktree detection logic plus unit tests for parsing/detection behavior.
README.md Updates documentation, options table, and examples for the new CLI interface.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Update the test to call parse_main_worktree() instead of duplicating
parsing logic, and verify git commit success. Also fix README formatting
by replacing "Don't" with "Do not" for consistency.

🤖 Generated with AI
@km-tr km-tr marked this pull request as ready for review February 24, 2026 14:05
Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4536b2b42e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/git.rs (1)

54-113: テスト用ディレクトリの後始末を追加すると安全です。
main_dir / dir の削除が一部漏れているので、最後に remove_dir_all を追加すると一時領域の残留を防げます。

🧹 例
         // Cleanup
         let _ = Command::new("git")
             .args(["worktree", "remove", "--force", wt_dir.to_str().unwrap()])
             .current_dir(&main_dir)
             .status();
         let _ = fs::remove_dir_all(&wt_dir);
+        let _ = fs::remove_dir_all(&main_dir);
     }

     #[test]
     fn detect_main_worktree_from_main_returns_self() {
         let main_dir = git_tempdir("detect_self");

         let detected = detect_main_worktree_in(&main_dir).unwrap();
         assert_eq!(detected, main_dir);
+        let _ = fs::remove_dir_all(&main_dir);
     }

     #[test]
     fn detect_main_worktree_outside_git_repo_fails() {
         let dir = tempdir("detect_nogit");

         let result = detect_main_worktree_in(&dir);
         assert!(result.is_err());
         let err_msg = result.unwrap_err().to_string();
         assert!(
             err_msg.contains("--source"),
             "Error message should mention --source, got: {err_msg}"
         );
+        let _ = fs::remove_dir_all(&dir);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/git.rs` around lines 54 - 113, Tests create temporary git dirs but don't
always remove them: add cleanup to avoid leaving temp directories. In the tests
detect_main_worktree_returns_main_path,
detect_main_worktree_from_main_returns_self and
detect_main_worktree_outside_git_repo_fails call git_tempdir/ tempdir to create
main_dir/dir — after each test add a best-effort fs::remove_dir_all(...) (or
equivalent) for those directories (and ensure the worktree removal in
detect_main_worktree_returns_main_path remains), handling errors with ignore to
avoid failing the test cleanup.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/main.rs`:
- Around line 38-49: When cli.source is omitted the code calls
git::detect_main_worktree() which checks the current working directory; change
the None branch so detection is based on the resolved --target path instead of
the process CWD: canonicalize cli.target (or the resolved target path variable),
ensure it's a directory, and pass that path into git detection (e.g., update or
call a git::detect_main_worktree_from/at function) so the detected main worktree
is derived from the target location rather than the current working directory;
update references to variables source and target accordingly and surface any
canonicalization errors with the existing with_context/bail pattern.

---

Nitpick comments:
In `@src/git.rs`:
- Around line 54-113: Tests create temporary git dirs but don't always remove
them: add cleanup to avoid leaving temp directories. In the tests
detect_main_worktree_returns_main_path,
detect_main_worktree_from_main_returns_self and
detect_main_worktree_outside_git_repo_fails call git_tempdir/ tempdir to create
main_dir/dir — after each test add a best-effort fs::remove_dir_all(...) (or
equivalent) for those directories (and ensure the worktree removal in
detect_main_worktree_returns_main_path remains), handling errors with ignore to
avoid failing the test cleanup.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 11efb0d and 4536b2b.

📒 Files selected for processing (4)
  • README.md
  • src/cli.rs
  • src/git.rs
  • src/main.rs

km-tr and others added 2 commits February 24, 2026 23:09
- Revert target to non-optional PathBuf with default_value="." so clap
  shows the default in --help output
- Include git stderr in error message when `git worktree list` fails
- Remove unused PathBuf import from main.rs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
When --source is omitted, auto-detection now runs from the resolved
--target path rather than the process CWD. This prevents detecting
the wrong repository when running from a different location.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@km-tr km-tr merged commit bedc9af into main Feb 24, 2026
10 checks passed
@km-tr km-tr deleted the feat/optional-source-flags branch February 24, 2026 14:33
@km-tr km-tr mentioned this pull request Feb 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants