From b57e57f001cdc69c6657a688721b8265be6b9295 Mon Sep 17 00:00:00 2001 From: Petr Michalec Date: Thu, 5 Nov 2026 08:46:48 +0100 Subject: [PATCH 01/22] simplify and focus use-case --- .agents/README.md | 4 +- .github/workflows/release.yml | 46 -- AGENTS.md | 110 ++--- CHANGELOG.md | 7 + Justfile | 7 +- Justfile.cross | 402 ++++++------------ README.md | 75 ++-- TODO.md | 8 + docs/overview.md | 42 +- docs/tutorials/local-overlays-and-upstream.md | 27 +- .../migrating-private-fork-to-git-cross.md | 20 +- .../split-repo-into-upstream-and-private.md | 6 +- .../whole-upstream-into-local-dir.md | 23 +- sbx-kits/README.md | 2 +- specs/001-cross-test-strategy/spec.md | 5 + src-go/main.go | 387 ++++++++++++++++- test/004_sync.sh | 164 ------- test/006_push.sh | 137 ------ test/007_status.sh | 21 +- test/009_go_cli.sh | 85 ++-- test/010_worktree.sh | 8 +- test/012_sparse_checkout.sh | 21 - test/014_remove.sh | 35 -- test/017_cd_wt_fix.sh | 19 - test/018_sbx_sandbox.sh | 180 ++------ test/run-all.sh | 11 + test/test-all-implementations.sh | 5 +- 27 files changed, 747 insertions(+), 1110 deletions(-) delete mode 100755 test/004_sync.sh delete mode 100755 test/006_push.sh diff --git a/.agents/README.md b/.agents/README.md index 93d5853c4..6326641bb 100644 --- a/.agents/README.md +++ b/.agents/README.md @@ -4,9 +4,9 @@ These files are shared repo-specific agent skills. Current shared roles: -- `git-cross-maintainer.md` for safe code changes across Just, Go, and Rust +- `git-cross-maintainer.md` for safe code changes across supported Just/Fish and Go implementations - `feature-spec-writer.md` for specs and behavior design work -- `safety-reviewer.md` for risky sync, push, patch, remove, and prune changes +- `safety-reviewer.md` for risky update, patch, remove, and prune changes - `regression-tester.md` for focused and full regression planning User-facing docs that mention these roles live in: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 36490d097..ab27b363b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,49 +30,3 @@ jobs: args: release --clean env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - rust-build: - name: Build Rust Binaries - runs-on: ${{ matrix.os }} - strategy: - matrix: - include: - - os: ubuntu-latest - target: x86_64-unknown-linux-gnu - artifact_name: git-cross-rust-linux-amd64 - - os: macos-latest - target: x86_64-apple-darwin - artifact_name: git-cross-rust-darwin-amd64 - - os: macos-latest - target: aarch64-apple-darwin - artifact_name: git-cross-rust-darwin-arm64 - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - with: - targets: ${{ matrix.target }} - - name: Build - run: cargo build --manifest-path src-rust/Cargo.toml --release --target ${{ matrix.target }} - - name: Upload Artifact - uses: actions/upload-artifact@v4 - with: - name: ${{ matrix.artifact_name }} - path: src-rust/target/${{ matrix.target }}/release/git-cross-rust - - upload-rust-to-release: - name: Upload Rust to GitHub Release - needs: [goreleaser, rust-build] - runs-on: ubuntu-latest - steps: - - name: Download Artifacts - uses: actions/download-artifact@v4 - with: - pattern: git-cross-rust-* - path: artifacts - - name: Upload to Release - uses: softprops/action-gh-release@v2 - if: startsWith(github.ref, 'refs/tags/') - with: - files: artifacts/**/* diff --git a/AGENTS.md b/AGENTS.md index b6e94b1be..01d65765a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,27 +4,27 @@ Instructions for AI agents working on this codebase. ## Architecture -**Core mechanism**: `git worktree` (vendoring) + `rsync` (syncing). Three parallel implementations exist with command parity. +**Core mechanism**: sparse `git worktree` + `rsync`. Supported implementations are Go (primary) and Just/Fish (reference). Rust remains in the repository but is unsupported and unmaintained. | Layer | Location | Language | CLI Framework | Git Interface | Status | |-------|----------|----------|---------------|---------------|--------| | **Go** (primary) | `src-go/main.go` | Go | Cobra | `gogs/git-module` + `os/exec` | Production | | **Just + Fish** | `Justfile.cross` | Fish/Bash | Just | `git` CLI + `jq` | Reference | -| **Rust** (experimental) | `src-rust/src/main.rs` | Rust | Clap | `git2` (minimal) + `duct` | WIP | +| **Rust** (unsupported) | `src-rust/src/main.rs` | Rust | Clap | `git2` + `duct` | Unmaintained | -Both Go and Rust are single-file implementations (~1500 lines each). Justfile.cross is ~960 lines. +Go is a single-file implementation. Justfile.cross is the readable reference. ## File Map ``` Justfile # Root wrapper: delegates `just cross ` to Justfile.cross Justfile.cross # Shell/Fish reference implementation (all commands) -Crossfile # User-facing state: records use/patch commands for replay +Crossfile # User-facing declarations: records use/patch setup src-go/main.go # Go CLI (single file, Cobra-based) src-go/go.mod # Go module (go 1.24) src-rust/src/main.rs # Rust CLI (single file, Clap-based) src-rust/Cargo.toml # Rust dependencies -.git/cross/ # Internal state directory +.cross/ # Internal state directory metadata.json # Patch registry: {patches: [{remote, remote_path, local_path, worktree, branch}]} worktrees/ # Hidden git worktrees for each patch test/common.sh # Shared test helpers (setup_sandbox, create_upstream, assertions) @@ -38,15 +38,13 @@ test/001-018_*.sh # Individual test files (see coverage matrix below) |---------|------|---------| | `use` | ` ` | Register remote, detect default branch | | `patch` | ` [local_path]` | Sparse-checkout worktree, rsync to local | -| `sync` | `[path]` | Pull upstream, rebase, rsync back to local | +| `update` | `[path]` | Read Crossfile and update upstream patches; preserve local edits | | `diff` | `[path]` | `git diff --no-index` between worktree and local (context-aware: auto-detects patch from CWD) | | `list` | | Table of remotes and patches | | `status` | | Health: local diffs, upstream divergence, conflicts | -| `push` | `[path]` | Rsync local to worktree, commit, push upstream | -| `replay` | | Re-execute Crossfile to reconstruct environment | +| `compare` | `[path]` | Open configured directory diff tool between local copy and worktree | | `remove` | `` | Delete patch, clean Crossfile and metadata | | `prune` | `[remote]` | Remove remote and all its patches, prune stale worktrees | -| `exec` | `` | Run arbitrary command (for Crossfile hooks) | | `init` | | Create empty Crossfile | | `cd` | `[path]` | Open shell in local_path (or fzf select + clipboard) | | `wt` | `[path]` | Open shell in worktree (or fzf select + clipboard) | @@ -55,7 +53,7 @@ test/001-018_*.sh # Individual test files (see coverage matrix below) ### Quality Assessment -| Aspect | Just/Fish | Go | Rust | +| Aspect | Just/Fish | Go | Rust (unsupported) | |--------|-----------|-----|------| | **Readability** | Best. Concise, intent-clear | Good. Cobra structure helps | Good. Match arms are clean | | **Error handling** | Weak. Fish has no `set -e`; many unchecked returns | Weak. 14 `loadMetadata` errors silently discarded | Mixed. `anyhow`/`?` is good, but 12 `let _ =` suppressions | @@ -63,16 +61,15 @@ test/001-018_*.sh # Individual test files (see coverage matrix below) | **Distribution** | Requires `just` + `fish` + `jq` + `rsync` | Single static binary + `rsync` | Single binary + `rsync` | | **Maintainability** | Simple to modify, fast iteration | Single 1509-line file, needs decomposition | Single 1520-line file, needs decomposition | -### Key Discrepancies +### Historical implementation discrepancies -| Topic | Just/Fish | Go | Rust | +| Topic | Just/Fish | Go | Rust (unsupported) | |-------|-----------|-----|------| -| **Worktree hash** | `SHA256(remote\0remote_path\0branch)[:8]` — matches Go | `SHA256(remote+path+branch)[:8]` — no field separator | `DefaultHasher(canonical+branch)[:8]` — **non-deterministic across Rust versions** | +| **Worktree hash** | `SHA256(remote\0remote_path\0branch)[:8]` — Just reference | `SHA256(remote+path+branch)[:8]` — Go legacy mismatch | Rust used `DefaultHasher`; unsupported | | **Git interface** | Direct `git` CLI everywhere | Mixed: `gogs/git-module` + `os/exec` + `git.Open()` — 3 styles interleaved | `git2` for 2 commands only, `duct`/`run_cmd` for rest — git2 is dead weight | | **Metadata `id` field** | Written via jq | **Not in struct** — silently dropped on save | Present with `#[serde(default)]` | | **Crossfile removal** | `grep -v "patch"` — removes ALL lines with "patch" | `strings.Contains(line, "patch") && strings.Contains(line, localPath)` — fragile | Same as Go — fragile substring match | | **`init` path** | CWD (no `pushd REPO_DIR`) | CWD (hardcodes `"Crossfile"`) | CWD (hardcodes `"Crossfile"`) | -| **`push` no-arg** | Requires explicit path or CWD in patch | Silently selects first patch | Silently selects first patch | ### What Each Implementation Does Best @@ -80,11 +77,11 @@ test/001-018_*.sh # Individual test files (see coverage matrix below) - **Go**: `updateCrossfile()` has the best deduplication (3-way prefix matching). `resolvePathToRepoRelative()` handles macOS `/tmp` -> `/private/tmp` symlinks. `detectDefaultBranch()` has the most robust fallback chain. - **Rust**: `parse_patch_spec()` handles the most edge cases. `anyhow` error context is better than Go's raw `fmt.Errorf`. `select_patch_interactive()` has the cleanest fzf integration. -### Known Systemic Issues (all implementations share) +### Known historical issues 1. **`cd`/`wt` code duplication**: Near-identical blocks in Go (80 lines) and Rust (56 lines). Should be a single parameterized function. 2. **`remove`/`prune` code duplication**: Prune copy-pastes remove logic. Should call a shared `removePatch()` helper. -3. **`sync` is a god-method**: 159 lines (Go), 192 lines (Rust), 166 lines (Just). Needs decomposition into: stash, sync-to-worktree, pull-rebase, detect-deletions, sync-from-worktree, unstash. +3. The retired `sync` flow rebased local changes. The supported `update` flow fetches upstream, fast-forwards a clean worktree, and preserves local files for manual review if they differ. 4. **Crossfile removal is fragile**: All three use substring matching that can corrupt unrelated lines. 5. **`loadMetadata` errors universally ignored**: Corrupted metadata.json silently treated as empty. @@ -92,41 +89,34 @@ test/001-018_*.sh # Individual test files (see coverage matrix below) ### Test Structure -Tests 001-007 form a chain for Shell/Just (001 is sourced by 002, etc.). Tests 008 (Rust) and 009 (Go) are self-contained monolithic tests. Tests 010-018 are focused feature tests. +Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 exercises Go. Rust, push, and replay legacy tests are excluded from the default runner. Tests 010-018 are focused feature tests. ### Coverage Matrix -| Command | Shell (tests) | Go (tests) | Rust (tests) | -|---------|:---:|:---:|:---:| -| `use` | 001 | 009 | 008 | -| `patch` | 002 | 009 | 008 | -| `sync` (basic) | 004 | 009 | 008 | -| `sync` (edge cases: conflicts, stash, deletion) | 004 | -- | -- | -| `diff` (basic) | 003 | 009 | 008 | -| `diff` (context-aware CWD) | 003, 016 | 016 | -- | -| `diff` (relative paths) | 003 | -- | -- | -| `list` | (017) | 009, 014 | 008, 014 | -| `status` (all states) | 007 | 009* | 008* | -| `push` (basic) | 006 | 009 | 008, 011 | -| `push` (custom msg/branch/force) | 006 | -- | 011 | -| `replay` | 005 | 009 | 008 | -| `remove` | 014 | 014 | 014 | -| `prune` | 015 | 009 | 008 | -| `cd`/`wt` | 017 | 017 | 017 | -| `exec` | 005* | -- | -- | -| `init` | -- | 009 | 008 | -| `sparse checkout` | 012 | 012 | 012 | -| `sbx/sandbox workflow` | -- | 018 | -- | +| Command | Just/Fish | Go | +|---------|:---:|:---:| +| `use` | 001 | 009 | +| `patch` | 002 | 009 | +| `update` (upstream/local edit behavior) | 004 | 009, 018 | +| `diff` (basic) | 003 | 009 | +| `diff` (context-aware CWD) | 003, 016 | 016 | +| `diff` (relative paths) | 003 | -- | +| `list` | (017) | 009, 014 | +| `status` (all states) | 007 | 009* | +| `compare` | -- | 009 | +| `remove` | 014 | 014 | +| `prune` | 015 | 009 | +| `cd`/`wt` | 017 | 017 | +| `init` | -- | 009 | +| `sparse checkout` | 012 | 012 | +| `sbx/update workflow` | -- | 018 | `*` = partial/basic assertions only. `--` = not tested. ### Gaps Worth Addressing -- **Go/Rust sync edge cases**: conflicts, uncommitted changes, file deletion — only tested in Shell. -- **Go push with custom message/branch/force**: only Shell and Rust test these. -- **Rust context-aware diff**: not tested (Go and Shell are). -- **`exec` command**: only tested indirectly through replay. -- **`list` for Shell**: no dedicated test. +- **Just update behavior**: requires Fish to be installed; run `test/004_update.sh` in an environment with Fish. +- **`list` for Just/Fish**: no dedicated test. ## Agent Workflow @@ -134,7 +124,7 @@ Tests 001-007 form a chain for Shell/Just (001 is sourced by 002, etc.). Tests 0 1. **Read this file** and `TODO.md` to understand priorities and constraints. 2. **Run existing tests** to establish a baseline: `just cross-test` or `bash test/run-all.sh`. -3. **Understand the three implementations** — changes must land in all three unless the scope is explicitly limited (e.g., "fix Go only"). +3. **Understand supported implementations** — implement shared behavior in Just/Fish first and Go second. Do not update Rust. 4. **Check the coverage matrix** above to know what's tested where. ### Implementing Features @@ -142,31 +132,29 @@ Tests 001-007 form a chain for Shell/Just (001 is sourced by 002, etc.). Tests 0 **Order of implementation:** 1. **Justfile.cross first** — it's the simplest to iterate on, and serves as the reference for behavior. 2. **Go second** — primary production implementation. Ensure it matches the Just behavior. -3. **Rust third** — experimental. Port from Go since the structure is closer. -4. **Write/update tests** — at minimum, add assertions to 008 (Rust) and 009 (Go). For Shell, add to the relevant 00X test or create a new one. +3. **Write/update tests** — cover Just/Fish and Go; Rust tests are excluded from supported verification. 5. **Update documentation** — `TODO.md`, `CHANGELOG.md`, this file if the change affects architecture. **Order of verification:** 1. `bash test/NNN_specific.sh` — run the specific test for the feature. -2. `bash test/003_diff.sh` and `bash test/004_sync.sh` — most likely to regress. +2. `bash test/003_diff.sh` and `bash test/004_update.sh` — most likely to regress. 3. `bash test/run-all.sh` — full regression. ### Implementing Bug Fixes -- Fix in all three implementations unless the bug is implementation-specific. -- If fixing a shared pattern (e.g., Crossfile removal), fix the pattern once and port to all three. +- Fix in supported implementations (Just/Fish and Go). +- If fixing a shared pattern (e.g., Crossfile removal), fix the pattern in Just/Fish and Go. - Add a regression test. ### Code Quality Rules **Do:** -- Propagate errors explicitly. Use `return err` (Go), `?` (Rust), `or exit 1` (Fish). +- Propagate errors explicitly. Use `return err` (Go), `or exit 1` (Fish). - Use the established helpers: `getRepoRoot()`/`get_repo_root()`, `loadMetadata()`/`load_metadata()`, `updateCrossfile()`/`update_crossfile()`. -- Use constants for paths: `.git/cross/worktrees/`, `Crossfile`, `.git/cross/metadata.json`. -- Match the existing code style of each implementation (Cobra commands in Go, Clap derive in Rust, Fish recipes in Just). +- Use constants for paths: `.cross/worktrees/`, `Crossfile`, `.cross/metadata.json`. +- Match the existing code style of each supported implementation (Cobra commands in Go, Fish recipes in Just). **Don't:** -- Add new dependencies to Rust (git2 is already dead weight — prefer `duct` CLI calls). - Use `gogs/git-module` for new Go code (prefer `os/exec` for consistency — the mixed approach is a known problem). - Make Justfile.cross more complex to accommodate programmatic concerns — keep it readable and concise. - Silently discard errors with `_ =` / `let _ =` / ignoring return values. Log them at minimum. @@ -176,16 +164,15 @@ Tests 001-007 form a chain for Shell/Just (001 is sourced by 002, etc.). Tests 0 - Tests use `setup_sandbox` and `create_upstream` from `test/common.sh`. - Shell tests may chain-source earlier tests (e.g., 003 sources 002 which sources 001). -- Tests 008/009 are self-contained and build their own binaries. +- Test 009 is self-contained and builds/reuses the Go binary. - To run a specific test: `bash test/NNN_name.sh`. - To run all: `bash test/run-all.sh` or `just cross-test`. -- CI runs on `ubuntu-latest` and does NOT install Go/Rust toolchains — tests 008/009/011 must handle this gracefully (skip with message if build fails). +- CI runs on `ubuntu-latest`; optional Go tests must handle missing Go toolchains gracefully. - Go binary builds must remove stale `src-go/vendor/` before building and pass `-mod=mod` directly as a flag (not via `GOFLAGS`). The vendor directory is gitignored but may exist locally. -- Rust tests must handle `cargo build` failures gracefully — skip instead of failing the test. ### Commit Conventions -- No partial implementations — all three must be updated in the same commit series. +- No partial implementations — supported Just/Fish and Go behavior should stay aligned. - Test coverage required for new features. - Update `CHANGELOG.md` for user-facing changes. - Update `TODO.md` when completing or adding items. @@ -195,7 +182,7 @@ Tests 001-007 form a chain for Shell/Just (001 is sourced by 002, etc.). Tests 0 - **Hidden worktrees**: `.git/cross/worktrees/_`. - **Sparse checkout**: `git sparse-checkout init --no-cone` + `git sparse-checkout set /` + `git read-tree -mu HEAD`. The trailing `/` on the pattern is required for reliable directory matching in `--no-cone` mode on newer Git versions (2.43+). `read-tree -mu HEAD` explicitly materializes the worktree (bare `git checkout` can no-op after `--no-checkout`). - **Rsync**: `rsync -av --delete --exclude .git` for worktree-to-local sync. `--delete` removes files locally that were deleted upstream. -- **Crossfile format**: Lines like `cross use ` or `cross patch :: `. Parsed as bash during `replay`. +- **Crossfile format**: Lines like `cross use ` or `cross patch :: `. `update` interprets only these declarative commands; arbitrary shell commands are not executed. - **.crossignore**: Located in the root of each local_path, uses gitignore-style patterns to exclude files from status and diff comparisons. Implemented by filtering directory trees using git add and git clean to remove ignored files before comparison. ## Refactoring Priorities @@ -204,8 +191,5 @@ When time allows, these structural improvements would most benefit the codebase: 1. **Extract `removePatch()` helper** in Go and Rust — eliminates duplication between `remove` and `prune`. 2. **Unify `cd`/`wt`** into a single parameterized function in Go and Rust. -3. **Decompose `sync`** into sub-functions (stash, sync-to-wt, pull, detect-deletions, sync-from-wt, unstash). -4. **Fix Crossfile removal** — use structured parsing (split line, match local_path field) instead of substring matching. -5. **Stabilize Rust worktree hash** — replace `DefaultHasher` with SHA256 to match Go's deterministic behavior. -6. **Remove `git2` dependency** from Rust — it's used for 2 trivial operations that already have CLI fallbacks. -7. **Consolidate Go's git interface** — pick either `gogs/git-module` or `os/exec` and use it consistently. +3. **Fix Crossfile removal** — use structured parsing (split line, match local_path field) instead of substring matching. +4. **Consolidate Go's git interface** — pick either `gogs/git-module` or `os/exec` and use it consistently. diff --git a/CHANGELOG.md b/CHANGELOG.md index 888cd5b29..05e60b74a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed +- **Simplified upstream workflow** - Added `git cross update [path]` to read declarative `use`/`patch` entries from `Crossfile`, fetch upstream, fast-forward sparse worktrees, and install only when the local copy has no edits. Local edits are preserved while the worktree advances for manual comparison. +- **Manual contribution workflow** - Retired `push`; use `wt`, `compare`, and ordinary Git commands to manually copy and commit desired changes in the sparse worktree. Configure the directory diff command with `git config --global cross.diffTool 'vim "+DirDiff"'`. +- **Retired replay and arbitrary Crossfile commands** - `update` interprets only `use` and `patch`; hooks and shell commands are no longer run from Crossfile. +- **Supported implementations** - Go remains primary and Just/Fish the reference. Rust source is retained but no longer maintained; release artifacts are Go-only. +- **Retired sync workflow** - The prior stash/copy/rebase logic is removed from the supported CLI and Just recipes. + ### Added - **User documentation refresh** - Added a clearer top-level README, a user-facing architecture overview, and a tutorial for local overlays, publishing to your own origin, and sending changes back upstream. - **Repo-local `sbx` starter kit** - Added `sbx-kits/opencode` plus `sbx-kits/README.md` so users can try `git-cross` in a versioned sandbox setup instead of relying on a home-directory kit path. diff --git a/Justfile b/Justfile index 3ad1f233f..f02154f59 100644 --- a/Justfile +++ b/Justfile @@ -13,17 +13,12 @@ import? "git.just" REPO_DIR=$(git rev-parse --show-toplevel) \ just --justfile "{{source_dir()}}/Justfile.cross" test "{{ARGS}}" -# Run the Rust implementation -[no-cd] -@cross-rust *ARGS: - cargo run --manifest-path "{{source_dir()}}/src-rust/Cargo.toml" -- {{ARGS}} - # Run the Go implementation [no-cd] @cross-go *ARGS: go run -C "{{source_dir()}}/src-go" main.go {{ARGS}} -# Install git alias for git-cross (default: go) +# Install git alias for git-cross (Go or Just) [no-cd] @install impl="go": just --justfile "{{source_dir()}}/Justfile.cross" install {{impl}} diff --git a/Justfile.cross b/Justfile.cross index 9cb2b9e23..663883578 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -220,10 +220,6 @@ _log level +message: echo "==> {{message}}" end -# Execute arbitrary shell command -exec +CMD: - {{CMD}} - # Initialize a new project with Crossfile [no-cd] init: @@ -398,7 +394,7 @@ prune remote_name="": check-deps end popd -# AICONTEXT: "patch" will do sparse checkout of specified branch of remote repository into local path. "remote_spec" is in format "remote_name:branch", where "branch" is optional. local_path is the same are remote_path if not provided. Command shall firs use `git ls-remote --heads ` to identify whether remote is having main or master as default branch if not provided - no more evaluation needed, simply grep "refs/heads" with regexp. Tool shall configure sparse checkout and use `git worktree add` and use `".git/cross/worktrees/$remote"_"$hash"` as working directory. Hash shall be short, but shall be created from path and branch name and humans shall ideally read it. checkout either only need maximum of 1 git history (last commmit version). When the checkout is done, "sync" target is called, to sync just this specific "patch" git worktree into main repository to local_path. Then a placeholder is required for post_sync_hook function to run. Finally call `git add` on local_path in top level repo. +# Sparse-checkout an upstream path into a local directory and record it in Crossfile. # AICONTEXT: for implementation, use "fish" keep it simple, shell comamnds shall be readable. Ideally keep bellow 30 lines. User interaction shall be kept minimal. Debug statements are not needed. Document in comments major logical blocks. # Patch a directory from a remote into a local path patch remote_spec local_path="": check-deps @@ -508,183 +504,137 @@ patch remote_spec local_path="": check-deps [no-cd] @check-initialized: cd {{REPO_DIR}} && test -d {{CROSSDIR}}/worktrees && test -f {{METADATA}} \ - || { just cross _log warn "No patches to sync"; exit 0; } + || { just cross _log warn "No patches to update"; exit 0; } -# AICONTEXT: "sync" will sync all or the provided local_path with upstream. Workflow: 1. Stash uncommitted changes in local_path. 2. Rsync git-tracked files from local_path to worktree. 3. Commit changes in worktree. 4. Pull rebase from upstream. 5. If conflicts, exit and ask user to resolve. 6. Rsync worktree back to local_path. 7. Restore stashed changes. 8. Check for conflicts in restored changes. -# Sync all patches from upstream +# Update Crossfile-managed patches from upstream. Local edits are preserved and +# left for manual review against the refreshed sparse worktree. [no-cd] -sync *path="": check-initialized +_update_patch spec local_path: #!/usr/bin/env fish - # Query metadata.json - just cross _resolve_context2 {{path}} | source \ - || { just cross _log error "Error: Could not resolve metadata for $path."; exit 1; } - - pushd "{{REPO_DIR}}" - just cross _log info "Syncing $local_path with $worktree..." - - # 0. Ensure local_path exists - mkdir -p $local_path - - # 0.5. Check for uncommitted changes in local_path (detect but don't stash yet) - set stashed false - set has_changes (git status --porcelain $local_path 2>/dev/null | wc -l | tr -d ' ') - if test "$has_changes" -gt 0 - just cross _log info "Detected uncommitted changes in $local_path..." - set stashed true - end - - # 1. Rsync current state (including uncommitted) from local_path to worktree - # AICONTEXT: the rsync need to sync only git tracked files in $local_path to $worktree/$remote_path - just cross _log info "Syncing local changes to worktree..." - if test -d $local_path - pushd $local_path - # Get tracked files (includes files with uncommitted changes) - set tracked (git ls-files .) - if test -n "$tracked" - # Rsync tracked files (with their current content, including uncommitted changes) - git ls-files . -z | rsync -0 --files-from=- -av --relative --exclude .git {{REPO_DIR}}/$local_path {{REPO_DIR}}/$worktree/$remote_path - end - popd + if test "{{local_path}}" = "." + just cross _log error "Updating a repository-root patch is not supported safely yet." + exit 1 + end + pushd "{{REPO_DIR}}" >/dev/null + set fields (string split ':' -- "{{spec}}") + set remote $fields[1] + set remote_path (string trim -c '/' -- $fields[-1]) + test -n "$remote_path"; or set remote_path "." + set entry (jq -c --arg lp "{{local_path}}" '.patches[]? | select(.local_path == $lp)' {{METADATA}} 2>/dev/null) + if test -z "$entry" + if test -e "{{REPO_DIR}}/{{local_path}}" + just cross _log error "Local path already exists but is not registered; refusing to overwrite it: {{local_path}}" + exit 1 end - - # 1.5. NOW stash uncommitted changes (after copying them to worktree) - if test "$stashed" = "true" - just cross _log info "Stashing uncommitted changes in $local_path..." - # Stash including untracked files, only in local_path - git stash push --include-untracked -m "cross-sync-auto-stash: $local_path" -- $local_path + just cross patch "{{spec}}" "{{local_path}}" + exit $status + end + set wt (echo "$entry" | jq -r '.worktree') + set branch (echo "$entry" | jq -r '.branch') + set entry_remote (echo "$entry" | jq -r '.remote') + set entry_remote_path (echo "$entry" | jq -r '.remote_path') + if test "$remote" != "$entry_remote" -o "$remote_path" != "$entry_remote_path" + just cross _log error "Crossfile source changed for {{local_path}}; remove and patch it explicitly before updating." + exit 1 + end + set spec_parts (string split ':' -- "{{spec}}") + if test (count $spec_parts) -eq 3 -a "$spec_parts[2]" != "$branch" + just cross _log error "Crossfile branch changed for {{local_path}}; remove and patch it explicitly before updating." + exit 1 + end + set local_abs "{{REPO_DIR}}/{{local_path}}" + set wt_abs "{{REPO_DIR}}/$wt/$remote_path" + set local_changed false + if test -d "$local_abs" + git diff --no-index --quiet -- "$wt_abs" "$local_abs" + set diff_status $status + if test $diff_status -eq 1 + set local_changed true + else if test $diff_status -gt 1 + just cross _log error "Could not compare local path and worktree." + exit 1 end - + end + git fetch $remote $branch; or exit 1 + set fetched_commit (git rev-parse FETCH_HEAD); or exit 1 + set worktree_dirty (git -C "$wt" status --porcelain) + if test -n "$worktree_dirty" + just cross _log error "Worktree has manual changes; leaving it untouched: $wt" + exit 1 + end + git -C "$wt" merge --ff-only "$fetched_commit"; or begin + just cross _log error "Upstream cannot fast-forward the worktree. Review it manually: $wt" + exit 1 + end + if test "$local_changed" = "true" + just cross _log warn "Local edits detected; preserving $local_abs. Compare manually:" + set tool (git config --get cross.diffTool 2>/dev/null) + test -n "$tool"; or set tool 'vim "+DirDiff"' + printf ' git cross compare "%s"\n' "{{local_path}}" + printf ' %s "%s" "%s"\n' "$tool" "$wt_abs" "$local_abs" + exit 0 + end + mkdir -p "$local_abs" + rsync -av --delete --exclude .git "$wt_abs/" "$local_abs/" - # 2. Commit local changes in worktree - set dirty (git -C $worktree status --porcelain) - if test -n "$dirty" - just cross _log info "Committing local changes in $worktree..." - git -C $worktree add . - git -C $worktree commit -m "Sync local changes" +# Update declarations in Crossfile. Only use and patch lines are interpreted. +[no-cd] +update path="": check-deps + #!/usr/bin/env fish + if not test -f "{{REPO_DIR}}/Crossfile" + just cross _log error "Crossfile not found." + exit 1 + end + pushd "{{REPO_DIR}}" >/dev/null + set updates 0 + while read -l line + set fields (string split -n ' ' -- (string trim -- "$line")) + if test (count $fields) -eq 0; or string match -q '#*' -- $fields[1] + continue end - - # 2.5. Check if worktree is in a good state (not detached HEAD, not mid-rebase) - pushd $worktree - # Check for ongoing rebase/merge FIRST (before anything else) - # For worktrees, rebase-merge can be in multiple locations - set worktree_name (basename $worktree) - set rebase_dirs .git/rebase-merge .git/rebase-apply {{REPO_DIR}}/.git/worktrees/$worktree_name/rebase-merge {{REPO_DIR}}/.git/worktrees/$worktree_name/rebase-apply - - set needs_cleanup false - for dir in $rebase_dirs - if test -d $dir - set needs_cleanup true - break - end - end - - if test "$needs_cleanup" = "true" - just cross _log warn "Worktree has an in-progress operation. Cleaning up..." - git rebase --abort 2>/dev/null || true - git merge --abort 2>/dev/null || true - # Force remove all possible rebase dirs - for dir in $rebase_dirs - rm -rf $dir 2>/dev/null || true - end + if test "$fields[1]" = "git" -o "$fields[1]" = "just" + if test (count $fields) -lt 3 -o "$fields[2]" != "cross" + just cross _log error "Unsupported Crossfile command: $line" + exit 1 end - - # Check for detached HEAD - if not git symbolic-ref -q HEAD >/dev/null 2>&1 - just cross _log warn "Worktree is in detached HEAD state. Attempting to recover..." - # Find the worktree's branch name - set branch_name (git for-each-ref --format='%(refname:short)' refs/heads/ | grep -E 'cross/' | head -1) - if test -n "$branch_name" - just cross _log info "Checking out branch: $branch_name" - git checkout -B $branch_name 2>/dev/null || true - # Reset to clean state - git fetch $remote 2>/dev/null || true - git reset --hard $remote/$remote_branch 2>/dev/null || true - end + set fields $fields[3..-1] + else if test "$fields[1]" = "cross" + set fields $fields[2..-1] + end + if test "$fields[1]" = "use" + if test (count $fields) -ne 3 + just cross _log error "Invalid use declaration in Crossfile: $line" + exit 1 end - popd - - # 3. Pull rebase from upstream - # Refresh index to avoid false conflicts from rsync mtime changes - git -C $worktree update-index --refresh -q 2>/dev/null; or true - just cross _log info "Pulling from upstream..." - if not git -C $worktree pull --rebase - just cross _log error "Conflict detected in $worktree. Please resolve manually." - just cross _log info "cd $worktree" - if test "$stashed" = "true" - just cross _log warn "Note: Local changes are stashed. Run 'git stash pop' in $local_path after resolving." + just cross use $fields[2] $fields[3]; or exit 1 + git fetch $fields[2]; or exit 1 + else if test "$fields[1]" = "patch" + if test (count $fields) -lt 2 -o (count $fields) -gt 3 + just cross _log error "Invalid patch declaration in Crossfile: $line" + exit 1 end - exit 1 - end - - # 4. Sync back to local - ensure directory exists - just cross _log info "Syncing back to $local_path..." - mkdir -p $local_path - - # 4.1. Remove files from local_path that were deleted upstream - # Only delete files that are: - # - Tracked in the main repo (in local_path) - # - No longer exist in the worktree - pushd $worktree/$remote_path - # Get list of tracked files in worktree - set worktree_files (git ls-files .) - - # Create temp file with worktree files list - set temp_list (mktemp) - echo "$worktree_files" > $temp_list - - # Get list of tracked files in local_path (from main repo) - pushd {{REPO_DIR}} - set local_tracked (git ls-files $local_path 2>/dev/null || echo "") - popd - - # Only check tracked files for deletion - if test -n "$local_tracked" - for tracked_file in $local_tracked - # Get just the filename relative to local_path - set rel_file (string replace -r "^$local_path/" "" $tracked_file) - # Check if this tracked file no longer exists in worktree - if not grep -qF "$rel_file" $temp_list 2>/dev/null - just cross _log info "Removing deleted file: $rel_file" - rm -f {{REPO_DIR}}/$tracked_file - end + set remote_path (string split ':' -- "$fields[2]")[-1] + set local_path $remote_path + if test (count $fields) -ge 3 + set local_path $fields[3] end - end - - rm -f $temp_list - - # 4.2. Rsync tracked files from worktree to local - git ls-files . -z | rsync -0 --files-from=- -av --relative --exclude .git {{REPO_DIR}}/$worktree/$remote_path {{REPO_DIR}}/$local_path - popd - - # 5. Restore stashed changes if they exist - if test "$stashed" = "true" - just cross _log info "Restoring stashed local changes..." - # First, add any new files that came from worktree sync - git add $local_path 2>/dev/null || true - # Now try to pop the stash (might have conflicts if same files were modified upstream) - if git stash pop - # Success - check for conflicts - set conflicts (git diff --name-only --diff-filter=U -- $local_path 2>/dev/null | wc -l | tr -d ' ') - if test "$conflicts" -gt 0 - just cross _log error "Conflicts detected after restoring local changes in $local_path:" - git diff --name-only --diff-filter=U -- $local_path - just cross _log info "Resolve conflicts, then run 'git add' and continue." - end - else - # Stash pop failed - likely due to conflicts - just cross _log warn "Could not automatically restore stashed changes." - just cross _log info "Your changes are preserved in the stash." - just cross _log info "Run 'git stash list' to see them, 'git stash show' to view, 'git stash pop' to retry." - just cross _log info "Or run 'git stash drop' if you want to discard them." + test -n "$local_path"; or set local_path "." + if test -n "{{path}}" -a "$local_path" != "{{path}}" + continue end + just cross _update_patch $fields[2] $local_path; or exit 1 + set updates (math $updates + 1) + else + just cross _log error "Unsupported Crossfile command: $line (update supports use and patch only)" + exit 1 end + end < "{{REPO_DIR}}/Crossfile" + if test -n "{{path}}" -a $updates -eq 0 + just cross _log error "No Crossfile patch found for {{path}}" + exit 1 + end + popd >/dev/null - just cross _log success "Sync completed for $local_path" - popd - - - -# AICONTEXT: "diff" will diff local vs .git/cross/worktrees/$remote"_"$hash. It will take all "git tracked" files from local_path and rsync them to .git/cross/worktrees/$remote"_"$hash/$remote_path. This function shall be used by "sync" target to manipulate with files between local_path and WT. When on WT, regular `git diff` can be run. (though then CWD shal return to where user was before the execution, which probably just ensure anyway) # Diff local vs upstream [no-cd] diff path="": check-initialized @@ -732,101 +682,17 @@ diff path="": check-initialized end popd -# AICONTEXT: "push" works on .git/cross/worktrees/$remote"_"$hash/$remote_path. Input argument is local_path (or understand user stand in the under git-cross'ed local_path and call this comand). The "sync" shall be run first, then regular git push to remote (as pull request, merge request shall happen to remote), the branch to push MR shall be autocalculated ie: "gituser_$hash" used in WT. User shall be give the optino to force-push, as he can repeate. (feature on git-cross) -# Push changes back to upstream +# Open the configured directory comparison tool (git config cross.diffTool). [no-cd] -push path="" branch="" force="false" yes="false" message="": check-initialized +compare path="": check-initialized #!/usr/bin/env fish - - # Query metadata.json just cross _resolve_context2 "{{path}}" | source \ - || { just cross _log error "Error: Could not resolve metadata for '$path'."; exit 1; } - - pushd "{{REPO_DIR}}" - just cross _log warn "The 'push' command is experimental. Verify upstream changes after use." - if not test -d $worktree - just cross _log error "Error: Worktree not found. Run 'just patch' first." - exit 1 - end - - just cross _log info "Syncing changes from $local_path back to $worktree..." - rsync -av --delete --exclude .git $local_path/ $worktree/$remote_path/ - - just cross _log info "---------------------------------------------------" - just cross _log info "Worktree updated. Status:" - git -C $worktree status - just cross _log info "---------------------------------------------------" - - while true - if test "{{yes}}" = "true" - set choice "r" - else - read -P "Run (r), Manual (m), Cancel (c)? " choice - end - - switch $choice - case r R - just cross _log info "Preparing commit..." - pushd $worktree - git add . - - # Determine commit message - set msg "{{message}}" - - if test -z "$msg"; and test "{{yes}}" = "false" - read -P "Commit message (empty to auto-generate from local log): " user_msg - if test -n "$user_msg" - set msg "$user_msg" - end - end - - if test -z "$msg" - # Auto-generate from local git log of the path - # We need to find the last commit that touched the local_path in the main repo - # Note: REPO_DIR is the main repo root - set msg (git -C "{{REPO_DIR}}" log -n 1 --pretty=format:%s -- "$local_path") - if test -z "$msg" - set msg "Sync updates from $local_path" - end - just cross _log info "Auto-generated message: $msg" - end - - git commit -m "$msg" - - # Determine push target - if test -z "{{branch}}" - set upstream (git rev-parse --abbrev-ref --symbolic-full-name '@{upstream}') - set remote (string split -m1 / $upstream)[1] - set target_branch (string split -m1 / $upstream)[2] - else - set remote "$remote" - set target_branch "{{branch}}" - end - - set push_args "$remote" "HEAD:$target_branch" - if test "{{force}}" = "true" - set push_args $push_args "--force" - end - - just cross _log info "Pushing to $push_args..." - git push $push_args - popd >/dev/null - break - case m M - just cross _log info "Spawning subshell in $worktree..." - just cross _log info "Type 'exit' to return." - pushd $worktree - fish - popd >/dev/null - just cross _log info "Returned from manual mode." - case c C - just cross _log warn "Cancelled." - exit 0 - case '*' - just cross _log error "Invalid choice." - end - end - popd + || { just cross _log error "Provide a patch path or run inside a patch directory."; exit 1; } + set tool (git config --get cross.diffTool 2>/dev/null) + test -n "$tool"; or set tool 'vim "+DirDiff"' + set worktree_path "{{REPO_DIR}}/$worktree/$remote_path" + set local_path_abs "{{REPO_DIR}}/$local_path" + bash -c "$tool \"\$1\" \"\$2\"" cross-compare "$worktree_path" "$local_path_abs" # AICONTEXT: "list" lists all patches in local repo, by reading Crossfile and `git worktree list` under .git/cross/worktrees. The listing shall be combined with status of each WT and git status of local_path. The logic can be take from "status" implementation. # List all patches @@ -1014,11 +880,7 @@ status: check-deps just cross _log info "No patches found." end -# Replay commands from Crossfile -replay: check-deps - /usr/bin/env bash -c "cross() { just --justfile '{{JUST_DIR}}/Justfile' cross \"\$@\"; }; git() { if [ \"\${1-}\" = \"cross\" ]; then shift; cross \"\$@\"; else command git \"\$@\"; fi; }; source '{{REPO_DIR}}/Crossfile'" - -# Install git alias for git-cross (impl: go, shell, rust) +# Install git alias for git-cross (impl: go or shell) install impl="go": #!/usr/bin/env bash set -e @@ -1038,16 +900,8 @@ install impl="go": git config --global alias.cross "!just --justfile $CROSS_PATH cross" echo "Success: Git alias 'cross' installed." ;; - rust) - echo "==> Building Rust implementation..." - (cd "{{JUST_DIR}}/src-rust" && cargo build) - EXE="{{JUST_DIR}}/src-rust/target/debug/git-cross-rust" - echo "==> Setting up git alias 'cross' -> $EXE" - git config --global alias.cross-rust "!$EXE" - echo "Success: Git alias 'cross' installed." - ;; *) - echo "ERROR: Unknown implementation '{{impl}}'. Use: go, shell, or rust." + echo "ERROR: Unknown implementation '{{impl}}'. Use: go or shell." exit 1 ;; esac diff --git a/README.md b/README.md index 341580fd9..2463501d6 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ `git-cross` is a small tool for pulling part of one Git repository into another with `git worktree` plus `rsync`. -It is for the cases where you want real files in your tree, not a gitlink, and still want a clean path back upstream. +It is for the cases where you want real files in your tree, not a gitlink, and want a simple way to refresh them from upstream. ## Why Use It @@ -15,7 +15,7 @@ It is for the cases where you want real files in your tree, not a gitlink, and s - vendor only one subdirectory from another repository - keep vendored code as normal files in your own repository - pull upstream updates without converting your repo into a submodule setup -- push changes back to a fork or upstream project without manual worktree plumbing +- manually compare local edits with the sparse upstream worktree when both have changed - let AI tools work on a mounted subfolder instead of your full repository Compared with submodules or subrepo-style flows, the tradeoff is simple: `git-cross` keeps files physical and visible in your repo, and tracks the upstream relationship separately through hidden worktrees and `Crossfile`. @@ -26,15 +26,14 @@ Compared with submodules or subrepo-style flows, the tradeoff is simple: `git-cr - Keep a shared app template in `vendor/template` and customize it locally - Work on an upstream library inside `vendor/lib` with normal editor tooling - Let an AI sandbox mount only `vendor/lib` instead of the whole repo -- Publish your local combined result to your own `origin`, while still being able to send a clean PR or MR upstream later +- Publish your local combined result to your own `origin` ## Status -The repository ships three implementations: +The repository supports two implementations: 1. Go: primary production implementation 2. Just/Fish: readable reference implementation -3. Rust: experimental parity implementation For normal usage, prefer the Go binary. @@ -54,18 +53,12 @@ go build -o git-cross-go main.go git config --global alias.cross "!$(pwd)/git-cross-go" ``` -### Shell Reference +### Just/Fish Reference ```bash just install shell ``` -### Rust CLI - -```bash -just install rust -``` - ## Quick Start ```bash @@ -80,12 +73,12 @@ git cross status git cross diff vendor/docs # 4. Pull new upstream changes later -git cross sync vendor/docs +git cross update vendor/docs ``` ## How It Works -`git-cross` keeps four things in sync: +`git-cross` connects four things: 1. Your main repository 2. A hidden worktree for each upstream patch under `.cross/worktrees/` @@ -97,7 +90,7 @@ In practice: - your editor sees normal files - AI tools can work on normal files - upstream history stays in the hidden worktree -- `git cross replay` can reconstruct the setup later +- `Crossfile` records the `use` and `patch` declarations; `git cross update` reads them to refresh patches ## Local Custom Files On Top Of Upstream @@ -128,9 +121,9 @@ What this does today: - `git cross diff vendor/app` prints manual `git diff --no-index ...` commands for the override paths - your local files stay in place for normal local work -This is intentionally conservative. `.crossignore` entries are review signals, not a substitute for review before `sync` or `push`. +This is intentionally conservative. `.crossignore` entries are review signals, not a substitute for review before updating. -If you keep secrets or machine-local files in a patched directory, review them explicitly before sending changes upstream. +If you keep secrets or machine-local files in a patched directory, review them explicitly before updating. ## Publish To Your Own Repo And Upstream @@ -148,22 +141,21 @@ git push origin main Your own repository stores the final combined result, including local overlay files if you choose to commit them there. -### 2. Send changes back to the upstream project +### 2. Manually contribute changes upstream When you want to contribute upstream-managed changes back: ```bash -git cross diff vendor/app -git cross push vendor/app --message "Fix upstream bug" +git cross wt vendor/app +git config --global cross.diffTool 'vim "+DirDiff"' +git cross compare vendor/app ``` Recommended pattern: -1. Track a writable fork with `git cross use`. -2. Patch from that fork into your local tree. -3. Keep local-only overlay files out of the upstream contribution. -4. Run `git cross push` for the vendored path. -5. Open a PR or MR from your fork branch to the original upstream project. +1. Open the sparse worktree with `git cross wt vendor/app`. +2. Compare it with the local patch using `git cross compare vendor/app` or your own directory diff tool. +3. Manually copy desired changes into the worktree, then commit and push with Git. This lets your main repo keep its local opinionated result while the upstream contribution stays focused. @@ -194,13 +186,21 @@ git cross patch : [local_dest] Create or reuse a hidden worktree, sparse-check out the upstream path, and sync it into your local directory. -### `sync` +### `update` + +```bash +git cross update [path] +``` + +Read `Crossfile`, fetch upstream updates, and update each patch. If the local copy differs from the previously installed upstream content, `update` preserves local files, advances the sparse worktree, and prints a comparison command for manual review. Configure a directory diff tool with `git config --global cross.diffTool 'vim "+DirDiff"'`. + +### `compare` ```bash -git cross sync [path] +git cross compare [path] ``` -Pull upstream changes into the local patched directory. +Open the configured directory comparison tool for a local patch and its sparse worktree. ### `diff` @@ -218,22 +218,6 @@ git cross status Show local diff state, upstream divergence, and conflicts. -### `push` - -```bash -git cross push [path] [--force] [--message "msg"] -``` - -Sync local changes back into the worktree, commit them there, and push to the upstream remote. - -### `replay` - -```bash -git cross replay -``` - -Rebuild the full setup from `Crossfile`. - ### `remove` ```bash @@ -254,6 +238,7 @@ Remove unused remotes, stale worktrees, or all patches for one remote. - `remove` and `prune` now guard against deleting repo root contents when a patch targets `.` - whole-upstream patching with `remote:.` and `remote:/` works for vendoring into local directories +- repository-root local targets are not supported by `update` yet - override markers in `.crossignore` currently affect review surfaces: `status` and `diff` - if you are experimenting with root-target overlay workflows, treat them as advanced usage and verify results carefully @@ -299,7 +284,7 @@ High level: - Just/Fish is the readable behavior reference - Go is the main production CLI -- Rust is parity-oriented and still experimental +- Rust source remains in the repository but is not maintained or supported Detailed architecture notes live in [docs/overview.md](docs/overview.md). diff --git a/TODO.md b/TODO.md index 2c93cd34c..dd5f15cb5 100644 --- a/TODO.md +++ b/TODO.md @@ -1,5 +1,13 @@ # TODO - git-cross +## Current Direction + +- Supported implementations: Go (primary) and Just/Fish (reference). Rust source is retained but unsupported and unmaintained. +- Core workflow: `Crossfile` declares `use`/`patch`; `patch` installs an initial sparse upstream path; `update` fetches and refreshes declared patches. +- If the local patch differs from the previously installed upstream tree, `update` preserves local files, advances the sparse worktree, and provides a manual comparison command. No automatic conflict resolution or back-propagation is provided. +- `push`, `sync`, and `replay` are retired. Manual upstream contributions use `wt`, a directory comparison tool, and ordinary Git commands. +- Legacy notes below describe historical work and are not the current product direction. + ## Summary **Status:** v0.3.1-dev — sparse-checkout fix, vendor build fix, AI sandbox workflow diff --git a/docs/overview.md b/docs/overview.md index 0c78290fd..2284c5d66 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -10,7 +10,7 @@ It does that by keeping: - a local copied directory with normal files in your repo - a `Crossfile` that records how the setup was created -The local directory is what you edit. The worktree is what `git-cross` uses to sync, diff, and push. +The local directory is what you edit. The sparse worktree holds the upstream version for updates and manual comparison. ## Mental Model @@ -31,7 +31,7 @@ upstream repo:path <-> hidden worktree:path <-> local directory ### `Crossfile` -Human-readable replay log. +Declarative list of upstream remotes and patches used by `update`. Example: @@ -44,7 +44,7 @@ cross patch demo:main:src/lib vendor/lib Hidden worktrees keyed by remote plus hash. -They hold upstream Git state and make `sync`, `diff`, and `push` possible without turning your vendored directory into another Git repository. +They hold upstream Git state and make `update` and manual comparison possible without turning your vendored directory into another Git repository. ### `.cross/metadata.json` @@ -62,9 +62,13 @@ Adds a named remote and detects the default branch. Creates or reuses a hidden worktree, sparse-checks out the requested upstream path, and syncs it into the local directory. -### `sync` +### `update` -Updates from upstream into the local directory. +Reads `Crossfile`, fetches each upstream, and fast-forwards its sparse worktree. It installs files locally only when the local copy still matches the previously installed version. If local edits exist, it preserves the local directory, leaves the refreshed upstream in the worktree, and prints a manual comparison command. + +### `compare` + +Opens the configured directory diff tool for the local path and its sparse worktree. Configure it with `git config --global cross.diffTool 'vim "+DirDiff"'`. ### `diff` @@ -74,19 +78,11 @@ Compares local files with the hidden worktree copy. Summarizes local modifications, upstream ahead/behind state, and conflict markers. -### `push` - -Copies local changes back into the hidden worktree, commits there, and pushes to the configured upstream remote. - -### `replay` - -Reconstructs the environment from `Crossfile`. - ### `remove` and `prune` Remove patch metadata, clean worktrees, and avoid unsafe deletion of repo-root content. -## Three Implementations +## Supported Implementations ### Go @@ -100,12 +96,6 @@ Reference implementation. Use this when you want the clearest behavior or fastest iteration inside the repo. -### Rust - -Experimental parity implementation. - -Useful for contributors and parity testing, but not the default recommendation for general users yet. - ## Local Overlay Files One practical pattern is to keep local-only files next to upstream-managed files. @@ -133,7 +123,7 @@ Current shipped behavior: - `status` shows `Override` - `diff` prints manual compare commands for those override paths -This gives you a visible review surface without pretending that local-only files are safe to push blindly. +This gives you a visible review surface without pretending that local-only files are upstream content. ## Safety Model @@ -147,16 +137,15 @@ This gives you a visible review surface without pretending that local-only files Important current boundary: - override markers are currently a review aid in `status` and `diff` -- if a file must never be sent upstream, review it explicitly before `push` +- if local changes exist, `update` preserves them and asks you to review the local copy against the refreshed worktree ## Typical Collaboration Pattern 1. Patch an upstream directory into `vendor/...` 2. Edit files locally as normal 3. Commit the combined result to your own repo -4. Pull upstream changes later with `sync` -5. Push upstream-safe changes back with `git cross push` -6. Open a PR or MR from the pushed branch if needed +4. Refresh upstream changes later with `update` +5. Manually compare and copy any desired contribution into the worktree, then use Git there ## AI And Sandbox Fit @@ -166,8 +155,7 @@ That means you can: - mount only `vendor/lib` into a sandbox - keep `.git` and hidden worktrees on the host -- review AI changes with `git cross diff` -- publish upstream-safe changes with `git cross push` +- review AI changes with `git cross diff` and `git cross compare` See: diff --git a/docs/tutorials/local-overlays-and-upstream.md b/docs/tutorials/local-overlays-and-upstream.md index 632c7263b..8db116869 100644 --- a/docs/tutorials/local-overlays-and-upstream.md +++ b/docs/tutorials/local-overlays-and-upstream.md @@ -94,10 +94,10 @@ This publishes the combined result to your own team repository. That is separate from contributing changes back to the upstream project. -## Step 6: Pull New Upstream Changes Later +## Step 6: Update From Upstream Later ```bash -git cross sync vendor/app +git cross update vendor/app ``` Then review again: @@ -115,28 +115,19 @@ When you want to send a fix upstream, first separate the changes that belong ups The cleanest setup is to track a writable fork from the start, then open a PR or MR from that fork to the original project. -If your current patch points at a read-only upstream remote, switch the tracked remote to your fork before using `git cross push`. +To manually prepare upstream-bound changes: -Before pushing upstream-bound changes: - -1. review `git cross diff vendor/app` -2. make sure local-only overlay files are not part of what you intend to send upstream -3. keep the upstream contribution limited to upstream-managed files - -Then push: - -```bash -git cross push vendor/app --message "Fix parser bug" -``` - -After that, open a PR or MR from your fork branch to the original upstream project. +1. open the sparse worktree with `git cross wt vendor/app` +2. compare it with local files using `git cross compare vendor/app` +3. manually copy intended changes into the worktree +4. commit and push from there with normal Git commands ## Practical Advice - Use your main repo `origin` for your final combined product state. -- Use a fork remote for upstream contribution. +- Use a fork remote if you plan to contribute upstream. - Keep local secrets and machine config clearly marked in `.crossignore`. -- Treat `.crossignore` entries as review helpers, not as permission to stop thinking about what gets pushed. +- Treat `.crossignore` entries as review helpers, not as a replacement for manual comparison. ## When To Use A Sandbox diff --git a/docs/tutorials/migrating-private-fork-to-git-cross.md b/docs/tutorials/migrating-private-fork-to-git-cross.md index e1074ea00..36ea5e11f 100644 --- a/docs/tutorials/migrating-private-fork-to-git-cross.md +++ b/docs/tutorials/migrating-private-fork-to-git-cross.md @@ -256,27 +256,21 @@ git push origin main After the migration: -- pull upstream updates with `git cross sync .` +- repository-root updates are currently blocked until root-overlay safety is implemented - review root changes with `git cross diff .` - inspect state with `git cross status` - publish the combined result to your private `origin` with normal Git -## Step 11: Contribute Changes Back Upstream +## Step 11: Manually Contribute Changes Back Upstream If you want to send some changes back upstream later: -1. review `git cross diff .` -2. make sure private files are not part of the upstream contribution -3. prefer using a writable fork as the tracked remote -4. push carefully and verify the resulting branch +1. open the sparse worktree with `git cross wt .` +2. compare it with the local repo using `git cross compare .` +3. manually copy intended upstream changes into the worktree +4. commit and push from that worktree with normal Git commands -Example: - -```bash -git cross push . --message "Fix upstream behavior" -``` - -Then open a PR or MR from the pushed branch. +Then open a PR or MR from the resulting branch. ## Practical Recommendation diff --git a/docs/tutorials/split-repo-into-upstream-and-private.md b/docs/tutorials/split-repo-into-upstream-and-private.md index 783d9023f..6ed8ca166 100644 --- a/docs/tutorials/split-repo-into-upstream-and-private.md +++ b/docs/tutorials/split-repo-into-upstream-and-private.md @@ -175,10 +175,10 @@ git add Crossfile .crossignore . && git commit -m "Track upstream via git-cross" git push origin main ``` -- pull upstream: `git cross sync .` +- repository-root updates are currently blocked until root-overlay safety is implemented; use a local subdirectory patch for update workflows - review: `git cross diff .` / `git cross status` -- contribute upstream: `git cross push . --message "..."` after confirming no - private files are included +- contribute manually: compare with `git cross compare .`, copy intended files + into the sparse worktree, then commit/push with Git from that worktree ## Related diff --git a/docs/tutorials/whole-upstream-into-local-dir.md b/docs/tutorials/whole-upstream-into-local-dir.md index dff21d5a3..b39f36ef9 100644 --- a/docs/tutorials/whole-upstream-into-local-dir.md +++ b/docs/tutorials/whole-upstream-into-local-dir.md @@ -8,7 +8,7 @@ Use this when: - you want the whole upstream tree, not just one subdirectory - you still want normal files in your repository -- you want to pull updates later or send changes back upstream +- you want to pull updates later This tutorial vendors the whole upstream into a local directory, not into repo root. @@ -88,12 +88,12 @@ Current behavior: - `git cross status` reports `Override` - `git cross diff vendor/upstream-app` prints a manual compare command for `.env` -Treat this as a review aid. Local-only files still need human review before any upstream push. +Treat this as a review aid. Local-only files remain local and are not copied into the sparse worktree. ## Step 6: Pull New Upstream Changes Later ```bash -git cross sync vendor/upstream-app +git cross update vendor/upstream-app ``` Then review again: @@ -113,21 +113,16 @@ git commit -m "Update vendored upstream app" git push origin main ``` -## Step 8: Contribute Back Upstream +## Step 8: Manually Contribute Back Upstream If some of your changes belong upstream: -1. review `git cross diff vendor/upstream-app` -2. make sure local-only files are not part of the upstream contribution -3. prefer tracking a writable fork for the patch remote +1. open the worktree with `git cross wt vendor/upstream-app` +2. compare the local directory and worktree with `git cross compare vendor/upstream-app` +3. manually copy intended changes into the worktree +4. commit and push from the worktree with normal Git commands -Then push: - -```bash -git cross push vendor/upstream-app --message "Fix upstream issue" -``` - -After that, open a PR or MR from your fork branch to the original project. +Open a PR or MR from your fork branch to the original project when ready. ## When This Pattern Is Better Than A Subdirectory Patch diff --git a/sbx-kits/README.md b/sbx-kits/README.md index 628264a1b..8505e47b5 100644 --- a/sbx-kits/README.md +++ b/sbx-kits/README.md @@ -67,7 +67,7 @@ They are meant to be a safe base for: 3. Start a sandbox with the repo-local kit. 4. Mount only the vendored path you want the agent to edit. 5. Review the result on the host with `git cross diff` and `git cross status`. -6. Publish to your own repo or push upstream separately. +6. Commit the result to your own repo; compare with the sparse worktree for any manual upstream contribution. ## Notes diff --git a/specs/001-cross-test-strategy/spec.md b/specs/001-cross-test-strategy/spec.md index fb75d19e2..a909510a1 100644 --- a/specs/001-cross-test-strategy/spec.md +++ b/specs/001-cross-test-strategy/spec.md @@ -1,5 +1,10 @@ # Feature Specification: cross command test strategy +> Historical specification retained for design reference. Its Rust parity, +> executable Crossfile hooks, `replay`, and legacy `sync` requirements are not +> part of the supported workflow. Current supported implementations are Go and +> Just/Fish; `update` interprets declarative `use` and `patch` entries only. + **Feature Branch**: `001-cross-test-strategy` **Created**: 2025-11-28 **Implementation**: Rust, Go, Justfile + Fish (Parity complete) diff --git a/src-go/main.go b/src-go/main.go index 51ac7a3c5..09e6bc224 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "crypto/sha256" "encoding/hex" "encoding/json" @@ -9,6 +10,7 @@ import ( "os/exec" "path/filepath" "sort" + "strconv" "strings" "github.com/fatih/color" @@ -172,7 +174,6 @@ func getCrossOverrides(localPath string) ([]string, error) { return overrides, nil } - func hasCrossOverrides(localPath string) (bool, error) { overrides, err := getCrossOverrides(localPath) if err != nil { @@ -225,6 +226,11 @@ func parsePatchSpec(spec string) (patchSpec, error) { remotePath = strings.TrimPrefix(remotePath, "/") remotePath = strings.TrimSuffix(remotePath, "/") + for _, component := range strings.Split(remotePath, "/") { + if component == ".." { + return patchSpec{}, fmt.Errorf("remote path must not traverse outside the repository") + } + } // Treat empty path (from "/") as "." meaning whole repo root if remotePath == "" { remotePath = "." @@ -263,6 +269,44 @@ func logSuccess(msg string) { fmt.Println(msg) } +func logWarn(msg string) { + color.New(color.Bold, color.FgYellow).Print("==> WARNING: ") + fmt.Println(msg) +} + +func diffTool() string { + if out, err := exec.Command("git", "config", "--get", "cross.diffTool").Output(); err == nil { + if tool := strings.TrimSpace(string(out)); tool != "" { + return tool + } + } + return `vim "+DirDiff"` +} + +func printDiffCommand(left, right string) { + tool := diffTool() + fmt.Printf(" git config --global cross.diffTool %s\n", strconv.Quote(tool)) + fmt.Printf(" %s %q %q\n", tool, left, right) +} + +func runDiffTool(left, right string) error { + tool := diffTool() + cmd := exec.Command("bash", "-c", tool+` "$@"`, "cross-diff", left, right) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + return cmd.Run() +} + +func localDiffersFromWorktree(localPath, worktreePath string) (bool, error) { + if _, err := os.Stat(localPath); os.IsNotExist(err) { + return false, nil + } else if err != nil { + return false, err + } + return directoriesDiffer(worktreePath, localPath) +} + func logError(msg string) { color.New(color.Bold, color.FgRed).Print("==> ERROR: ") fmt.Println(msg) @@ -379,6 +423,51 @@ func runSync(src, dst string) error { return nil } +func directoriesDiffer(left, right string) (bool, error) { + cmd := exec.Command("git", "diff", "--no-index", "--quiet", "--", left, right) + err := cmd.Run() + if err == nil { + return false, nil + } + if exitErr, ok := err.(*exec.ExitError); ok { + if exitErr.ExitCode() == 1 { + return true, nil + } + } + return false, fmt.Errorf("compare %s and %s: %w", left, right, err) +} + +func crossfileCommands(path string) ([][]string, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + var commands [][]string + scanner := bufio.NewScanner(file) + for lineNumber := 1; scanner.Scan(); lineNumber++ { + line := strings.TrimSpace(scanner.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + fields := strings.Fields(line) + if len(fields) >= 2 && (fields[0] == "git" || fields[0] == "just") && fields[1] == "cross" { + fields = fields[2:] + } else if len(fields) > 0 && fields[0] == "cross" { + fields = fields[1:] + } + if len(fields) == 0 || (fields[0] != "use" && fields[0] != "patch") { + return nil, fmt.Errorf("unsupported Crossfile command on line %d (update accepts only use and patch declarations)", lineNumber) + } + commands = append(commands, fields) + } + if err := scanner.Err(); err != nil { + return nil, err + } + return commands, nil +} + func detectDefaultBranch(url string) (string, error) { cmd := exec.Command("git", "ls-remote", "--symref", url, "HEAD") if out, err := cmd.CombinedOutput(); err == nil { @@ -547,6 +636,22 @@ func findPatchForPath(meta Metadata, rel string) *Patch { return selected } +func findPatchForPathFromCWD(meta Metadata) (*Patch, error) { + root, err := getRepoRoot() + if err != nil { + return nil, err + } + cwd, err := os.Getwd() + if err != nil { + return nil, err + } + rel, err := filepath.Rel(root, cwd) + if err != nil { + return nil, err + } + return findPatchForPath(meta, filepath.ToSlash(rel)), nil +} + // resolvePathToRepoRelative converts any path (relative, absolute, or repo-relative) // to a repo-relative path for matching against metadata func resolvePathToRepoRelative(inputPath string) (string, error) { @@ -863,8 +968,9 @@ func main() { } syncCmd := &cobra.Command{ - Use: "sync [path]", - Short: "Update patches from upstream", + Use: "sync [path]", + Short: "Update patches from upstream", + Hidden: true, RunE: func(cmd *cobra.Command, args []string) error { path := "" if len(args) > 0 { @@ -1024,6 +1130,244 @@ func main() { }, } + updateCmd := &cobra.Command{ + Use: "update [path]", + Short: "Update Crossfile patches from upstream", + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + root, err := getRepoRoot() + if err != nil { + return err + } + cwd, err := os.Getwd() + if err != nil { + return err + } + if err := os.Chdir(root); err != nil { + return err + } + defer os.Chdir(cwd) + crossfile, err := getCrossfilePath() + if err != nil { + return err + } + commands, err := crossfileCommands(crossfile) + if err != nil { + return err + } + selectedPath := "" + if len(args) > 0 { + selectedPath, err = resolvePathToRepoRelative(args[0]) + if err != nil { + return err + } + if selectedPath == "" && (args[0] == "." || args[0] == root) { + selectedPath = "." + } + } + meta, err := loadMetadata() + if err != nil { + return err + } + localChanges := make(map[string]bool) + for _, fields := range commands { + if len(fields) == 0 || fields[0] != "patch" || len(fields) < 2 || len(fields) > 3 { + continue + } + spec, err := parsePatchSpec(fields[1]) + if err != nil { + return err + } + localPath := filepath.Base(spec.RemotePath) + if len(fields) == 3 { + localPath = fields[2] + } + localPath = filepath.Clean(localPath) + if selectedPath != "" && selectedPath != localPath { + continue + } + for i := range meta.Patches { + p := &meta.Patches[i] + if filepath.Clean(p.LocalPath) == localPath && p.Remote == spec.Remote && filepath.Clean(p.RemotePath) == filepath.Clean(spec.RemotePath) { + localPathAbs := filepath.Join(root, localPath) + worktreePath := filepath.Join(root, p.Worktree, p.RemotePath) + different, err := localDiffersFromWorktree(localPathAbs, worktreePath) + if err != nil { + return err + } + localChanges[localPath] = different + break + } + } + } + updated := 0 + matched := 0 + for _, fields := range commands { + if fields[0] == "use" { + if len(fields) != 3 { + return fmt.Errorf("invalid use declaration in Crossfile: %s", strings.Join(fields, " ")) + } + name, url := fields[1], fields[2] + if _, err := exec.Command("git", "-C", root, "remote", "get-url", name).Output(); err != nil { + if output, addErr := exec.Command("git", "-C", root, "remote", "add", name, url).CombinedOutput(); addErr != nil { + return fmt.Errorf("add remote %s: %s: %w", name, strings.TrimSpace(string(output)), addErr) + } + } else if output, setErr := exec.Command("git", "-C", root, "remote", "set-url", name, url).CombinedOutput(); setErr != nil { + return fmt.Errorf("update remote %s: %s: %w", name, strings.TrimSpace(string(output)), setErr) + } + branch, err := detectDefaultBranch(url) + if err != nil { + return fmt.Errorf("detect default branch for %s: %w", name, err) + } + if output, fetchErr := exec.Command("git", "-C", root, "fetch", name, branch).CombinedOutput(); fetchErr != nil { + return fmt.Errorf("fetch %s: %s: %w", name, strings.TrimSpace(string(output)), fetchErr) + } + continue + } + if len(fields) < 2 || len(fields) > 3 { + return fmt.Errorf("invalid patch declaration in Crossfile: %s", strings.Join(fields, " ")) + } + spec, err := parsePatchSpec(fields[1]) + if err != nil { + return err + } + localPath := "" + if len(fields) == 3 { + localPath = fields[2] + } else { + localPath = filepath.Base(spec.RemotePath) + } + localPath = filepath.Clean(localPath) + if filepath.IsAbs(localPath) || localPath == ".." || strings.HasPrefix(localPath, ".."+string(os.PathSeparator)) { + return fmt.Errorf("local path must stay inside the repository: %s", localPath) + } + if localPath == "." { + return fmt.Errorf("updating a repository-root patch is disabled until root overlay safety is implemented") + } + if selectedPath != "" && selectedPath != localPath { + continue + } + matched++ + var patch *Patch + for i := range meta.Patches { + if filepath.Clean(meta.Patches[i].LocalPath) == localPath { + patch = &meta.Patches[i] + break + } + } + if patch == nil { + if _, err := os.Stat(filepath.Join(root, localPath)); err == nil { + return fmt.Errorf("local path %s exists but is not registered in metadata; refusing to overwrite it", localPath) + } + if err := patchCmd.RunE(cmd, []string{fields[1], localPath}); err != nil { + return err + } + meta, err = loadMetadata() + if err != nil { + return err + } + updated++ + continue + } + if patch.Remote != spec.Remote || filepath.Clean(patch.RemotePath) != filepath.Clean(spec.RemotePath) || (spec.Branch != "" && patch.Branch != spec.Branch) { + return fmt.Errorf("Crossfile source for %s changed; remove and re-patch it explicitly before updating", localPath) + } + if _, err := os.Stat(filepath.Join(root, patch.Worktree)); os.IsNotExist(err) { + if _, localErr := os.Stat(filepath.Join(root, localPath)); localErr == nil { + return fmt.Errorf("worktree %s is missing while local path %s exists; refusing to overwrite it. Review/remove the patch explicitly, then run update again", patch.Worktree, localPath) + } + if err := patchCmd.RunE(cmd, []string{fields[1], localPath}); err != nil { + return err + } + meta, err = loadMetadata() + if err != nil { + return err + } + updated++ + continue + } + if spec.Branch == "" { + spec.Branch = patch.Branch + } + localAbs := filepath.Join(root, localPath) + upstreamAbs := filepath.Join(root, patch.Worktree, patch.RemotePath) + localChanged := localChanges[localPath] + if err := exec.Command("git", "-C", root, "fetch", spec.Remote, spec.Branch).Run(); err != nil { + return fmt.Errorf("fetch %s %s: %w", spec.Remote, spec.Branch, err) + } + fetchHead, err := exec.Command("git", "-C", root, "rev-parse", "FETCH_HEAD").Output() + if err != nil { + return fmt.Errorf("resolve fetched revision: %w", err) + } + status, err := exec.Command("git", "-C", patch.Worktree, "status", "--porcelain").Output() + if err != nil { + return fmt.Errorf("inspect worktree %s: %w", patch.Worktree, err) + } + if len(status) != 0 { + logError(fmt.Sprintf("Worktree has manual changes; leaving it untouched: %s", patch.Worktree)) + continue + } + merge := exec.Command("git", "-C", patch.Worktree, "merge", "--ff-only", strings.TrimSpace(string(fetchHead))) + if output, err := merge.CombinedOutput(); err != nil { + return fmt.Errorf("upstream update for %s requires manual worktree review (%s): %s", localPath, patch.Worktree, strings.TrimSpace(string(output))) + } + updated++ + if localChanged { + logWarn(fmt.Sprintf("Local edits detected; preserving %s. Compare the worktree and local copy manually:", localPath)) + printDiffCommand(upstreamAbs, localAbs) + continue + } + if err := os.MkdirAll(localAbs, 0o755); err != nil { + return err + } + if err := runSync(upstreamAbs+string(os.PathSeparator), localAbs+string(os.PathSeparator)); err != nil { + return err + } + logSuccess(fmt.Sprintf("Updated %s", localPath)) + } + if selectedPath != "" && matched == 0 { + return fmt.Errorf("no Crossfile patch found for path: %s", selectedPath) + } + if updated == 0 { + logInfo("No patches updated.") + } + return nil + }, + } + + compareCmd := &cobra.Command{ + Use: "compare [path]", + Short: "Open the configured directory comparison tool for a patch", + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + meta, err := loadMetadata() + if err != nil { + return err + } + var patch *Patch + if len(args) > 0 { + relPath, err := resolvePathToRepoRelative(args[0]) + if err != nil { + return err + } + patch = findPatchForPath(meta, relPath) + } else { + patch, err = findPatchForPathFromCWD(meta) + if err != nil { + return err + } + } + if patch == nil { + return fmt.Errorf("patch not found; provide a path or run from inside a patched directory") + } + root, err := getRepoRoot() + if err != nil { + return err + } + return runDiffTool(filepath.Join(root, patch.Worktree, patch.RemotePath), filepath.Join(root, patch.LocalPath)) + }, + } + // Helper: Copy text to clipboard (cross-platform) copyToClipboard := func(text string) error { var cmd *exec.Cmd @@ -1061,7 +1405,10 @@ func main() { // Helper: Open shell in target directory (path must be provided) openShellInDir := func(path string, targetType string) error { - meta, _ := loadMetadata() + meta, err := loadMetadata() + if err != nil { + return err + } if len(meta.Patches) == 0 { fmt.Println("No patches configured.") return nil @@ -1119,7 +1466,10 @@ func main() { return &cobra.Command{ Use: use, Short: short, Long: long, RunE: func(cmd *cobra.Command, args []string) error { - meta, _ := loadMetadata() + meta, err := loadMetadata() + if err != nil { + return err + } if len(meta.Patches) == 0 { fmt.Println("No patches configured.") return nil @@ -1170,7 +1520,10 @@ func main() { Use: "list", Short: "Show all configured patches and remotes", RunE: func(cmd *cobra.Command, args []string) error { - meta, _ := loadMetadata() + meta, err := loadMetadata() + if err != nil { + return err + } // Collect unique remote names from patches usedRemotes := make(map[string]bool) @@ -1401,8 +1754,9 @@ patch's diff. Otherwise shows diffs for all patches.`, } replayCmd := &cobra.Command{ - Use: "replay", - Short: "Re-execute all Crossfile commands", + Use: "replay", + Short: "Re-execute all Crossfile commands", + Hidden: true, RunE: func(cmd *cobra.Command, args []string) error { logInfo("Replaying Crossfile...") path, err := getCrossfilePath() @@ -1433,8 +1787,9 @@ patch's diff. Otherwise shows diffs for all patches.`, var pushMessage string pushCmd := &cobra.Command{ - Use: "push [path]", - Short: "Push changes back upstream", + Use: "push [path]", + Short: "Push changes back upstream", + Hidden: true, RunE: func(cmd *cobra.Command, args []string) error { path := "" if len(args) > 0 { @@ -1526,9 +1881,10 @@ patch's diff. Otherwise shows diffs for all patches.`, pushCmd.Flags().StringVarP(&pushMessage, "message", "m", "", "Commit message") execCmd := &cobra.Command{ - Use: "exec [cmd]", - Short: "Run arbitrary command", - Args: cobra.MinimumNArgs(1), + Use: "exec [cmd]", + Short: "Run arbitrary command", + Hidden: true, + Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { fullCmd := strings.Join(args, " ") logInfo("Executing custom command: " + fullCmd) @@ -1694,7 +2050,10 @@ patch's diff. Otherwise shows diffs for all patches.`, }, } - rootCmd.AddCommand(useCmd, patchCmd, syncCmd, removeCmd, pruneCmd, cdCmd, wtCmd, listCmd, statusCmd, diffCmd, replayCmd, pushCmd, execCmd, initCmd) + // Retain superseded implementations in source as internal reference, but do + // not expose them as supported commands. + _, _, _, _ = syncCmd, replayCmd, pushCmd, execCmd + rootCmd.AddCommand(useCmd, patchCmd, updateCmd, compareCmd, removeCmd, pruneCmd, cdCmd, wtCmd, listCmd, statusCmd, diffCmd, initCmd) if err := rootCmd.Execute(); err != nil { os.Exit(1) } diff --git a/test/004_sync.sh b/test/004_sync.sh deleted file mode 100755 index d399afcbb..000000000 --- a/test/004_sync.sh +++ /dev/null @@ -1,164 +0,0 @@ -#!/bin/bash -source test/common.sh - -CLEANUP={$CLEANUP:-true} source test/002_patch.sh - -###### -# Test 1: Basic sync - upstream changed, no local changes -###### -log_header "Test 1: Basic sync with no local changes..." - -# Modify upstream -echo "v2" > "$upstream_path/src/lib/file_sync.txt" -git -C "$upstream_path" add "$upstream_path/src/lib/file_sync.txt" -git -C "$upstream_path" commit -am "Update file" -q - -# Sync -log_header "Running 'just cross sync'..." -just cross sync vendor/lib - -# Verify local updated -assert_grep "vendor/lib/file_sync.txt" "v2" -log_success "Test 1 passed: Basic sync works" - -###### -# Test 2: Sync with uncommitted local changes (should preserve) -###### -log_header "Test 2: Sync with uncommitted local changes..." - -# Create uncommitted changes in local -echo "local-uncommitted-change" > "vendor/lib/local_new_file.txt" -echo "v2-modified-locally" > "vendor/lib/file_sync.txt" - -# Modify upstream (different file to avoid conflict) -echo "v3-upstream-different-file" > "$upstream_path/src/lib/another_file.txt" -git -C "$upstream_path" add "$upstream_path/src/lib/another_file.txt" -git -C "$upstream_path" commit -m "Add another file" -q - -# Sync should stash, pull, rsync, then restore -just cross sync vendor/lib - -# Verify upstream changes arrived -assert_grep "vendor/lib/another_file.txt" "v3-upstream-different-file" - -# Verify local uncommitted changes were preserved -assert_grep "vendor/lib/local_new_file.txt" "local-uncommitted-change" -assert_grep "vendor/lib/file_sync.txt" "v2-modified-locally" - -log_success "Test 2 passed: Uncommitted changes preserved" - -###### -# Test 3: Sync with committed local changes -###### -log_header "Test 3: Sync with committed local changes..." - -# Commit the local changes -git add vendor/lib/ -git commit -m "Local committed changes" -q - -# Modify upstream again (non-conflicting) -echo "v4-upstream" > "$upstream_path/src/lib/upstream_file.txt" -git -C "$upstream_path" add "$upstream_path/src/lib/upstream_file.txt" -git -C "$upstream_path" commit -m "Add upstream file" -q - -# Sync should work smoothly -just cross sync vendor/lib - -# Verify both local and upstream changes exist -assert_grep "vendor/lib/local_new_file.txt" "local-uncommitted-change" -assert_grep "vendor/lib/upstream_file.txt" "v4-upstream" - -log_success "Test 3 passed: Committed local changes synced" - -###### -# Test 4: Sync with conflicting changes (should fail gracefully) -###### -log_header "Test 4: Sync with conflicting changes..." - -# Modify same file locally and upstream -echo "v5-local" > "vendor/lib/file_sync.txt" - -# Modify upstream (same file, different content) -echo "v5-upstream" > "$upstream_path/src/lib/file_sync.txt" -git -C "$upstream_path" commit -am "Conflict update" -q - -# Sync should detect conflict and fail gracefully -cd vendor/lib -if just cross sync; then - log_warn "Sync succeeded but should have detected conflict" - # Check if conflict markers exist - if grep -q "<<<<<<< HEAD" file_sync.txt 2>/dev/null; then - log_success "Test 4 passed: Conflict detected (with markers)" - else - log_warn "No conflict markers found - may have auto-merged" - fi -else - log_success "Test 4 passed: Sync failed as expected (conflict detected)" -fi -cd ../.. - -# Cleanup after Test 4: Reset worktree to clean state -log_header "Cleaning up after conflict test..." -# Find the actual worktree directory dynamically (hash algorithm may vary) -worktree_path=$(find .cross/worktrees -maxdepth 1 -name "repo1_*" -type d 2>/dev/null | head -1) -if [ -n "$worktree_path" ] && [ -d "$worktree_path" ]; then - wt_name=$(basename "$worktree_path") - # Abort any in-progress operations - git -C "$worktree_path" rebase --abort 2>/dev/null || true - git -C "$worktree_path" merge --abort 2>/dev/null || true - - # Remove any leftover rebase directories - rm -rf "$worktree_path/.git/rebase-merge" 2>/dev/null || true - rm -rf "$worktree_path/.git/rebase-apply" 2>/dev/null || true - rm -rf ".git/worktrees/$wt_name/rebase-merge" 2>/dev/null || true - rm -rf ".git/worktrees/$wt_name/rebase-apply" 2>/dev/null || true - - # Checkout correct branch and reset to clean state - git -C "$worktree_path" checkout -B "cross/repo1/main/${wt_name##*_}" 2>/dev/null || true - git -C "$worktree_path" fetch repo1 2>/dev/null || true - git -C "$worktree_path" reset --hard repo1/main 2>/dev/null || true - git -C "$worktree_path" clean -fd 2>/dev/null || true -fi - -# Also clean up local modifications from Test 4 -git restore vendor/lib/file_sync.txt 2>/dev/null || true -git stash drop 2>/dev/null || true # Drop any leftover stash from Test 4 - -###### -# Test 5: Sync with deleted files -###### -log_header "Test 5: Sync with deleted upstream file..." - -# Delete file upstream -rm "$upstream_path/src/lib/another_file.txt" -git -C "$upstream_path" commit -am "Delete another_file.txt" -q - -# Sync should remove the file locally -just cross sync vendor/lib - -# Verify file is deleted -if [ -f "vendor/lib/another_file.txt" ]; then - log_error "Test 5 failed: Deleted file still exists locally" - exit 1 -else - log_success "Test 5 passed: Deleted file removed locally" -fi - -###### -# Test 6: Sync with added files -###### -log_header "Test 6: Sync with new upstream file..." - -# Add new file upstream -echo "brand-new-file" > "$upstream_path/src/lib/new_upstream.txt" -git -C "$upstream_path" add "$upstream_path/src/lib/new_upstream.txt" -git -C "$upstream_path" commit -m "Add new file" -q - -# Sync should add the file locally -just cross sync vendor/lib - -# Verify new file exists -assert_grep "vendor/lib/new_upstream.txt" "brand-new-file" -log_success "Test 6 passed: New file added locally" - -log_success "All sync tests passed!" diff --git a/test/006_push.sh b/test/006_push.sh deleted file mode 100755 index 99db82941..000000000 --- a/test/006_push.sh +++ /dev/null @@ -1,137 +0,0 @@ -#!/usr/bin/env bash -source $(dirname "$0")/common.sh - -# Initialize -setup_sandbox -# common.sh sets SANDBOX and cd's into it, which is our local repo. - -# Setup upstream -upstream_path=$(create_upstream "upstream-repo") -upstream_url="file://$upstream_path" - -# Ensure docs directory exists in upstream -pushd "$upstream_path" >/dev/null -mkdir -p docs -echo "Docs content" > docs/README.md -git add docs/README.md -git commit -m "Add docs" -# Allow pushing to current branch (required for local test repos) -git config receive.denyCurrentBranch ignore -popd >/dev/null - -# Detect the default branch name used by upstream -default_branch=$(git -C "$upstream_path" rev-parse --abbrev-ref HEAD) - -# Use and Patch -just cross use upstream "$upstream_url" -just cross patch upstream:docs vendor/docs - -# Verify proper initial state -test -f vendor/docs/README.md || fail "vendor/docs/README.md should exist" - -# ------------------------------------------------------------------ -# Test 1: Basic Push (Auto-msg, Non-interactive) -# ------------------------------------------------------------------ -log_header "Test 1: Basic push with auto-generated message..." -echo "Change 1" >> vendor/docs/README.md -git add vendor/docs/README.md -git commit -m "Local change 1" - -# Just recipe signature: push path="" branch="" force="false" yes="false" message="" -# Arguments are POSITIONAL: path, branch, force, yes, message -# NOTE: We call Justfile.cross directly because the `just cross` wrapper uses -# *ARGS which loses empty string arguments during re-expansion. -REPO_DIR=$(git rev-parse --show-toplevel) -export REPO_DIR -JUSTFILE_CROSS="$SANDBOX/Justfile.cross" - -REPO_DIR="$REPO_DIR" just --justfile "$JUSTFILE_CROSS" push vendor/docs "" false true - -# Verify upstream has the commit -pushd "$upstream_path" >/dev/null -git reset --hard HEAD # refresh working tree after receiving push -last_msg=$(git log -1 --pretty=%s) -if [[ "$last_msg" != "Local change 1" ]]; then - fail "Expected upstream commit msg 'Local change 1', got '$last_msg'" -fi -popd >/dev/null -log_success "Test 1 passed: Basic push" - -# ------------------------------------------------------------------ -# Test 2: Custom Commit Message (Non-interactive) -# ------------------------------------------------------------------ -log_header "Test 2: Push with custom commit message..." -echo "Change 2" >> vendor/docs/README.md -git add vendor/docs/README.md -git commit -m "Local change 2 to be ignored" - -REPO_DIR="$REPO_DIR" just --justfile "$JUSTFILE_CROSS" push vendor/docs "" false true "Custom Msg" - -pushd "$upstream_path" >/dev/null -git reset --hard HEAD -last_msg=$(git log -1 --pretty=%s) -if [[ "$last_msg" != "Custom Msg" ]]; then - fail "Expected upstream commit msg 'Custom Msg', got '$last_msg'" -fi -popd >/dev/null -log_success "Test 2 passed: Custom commit message" - -# ------------------------------------------------------------------ -# Test 3: Push to a named branch -# ------------------------------------------------------------------ -log_header "Test 3: Push to named branch..." -echo "Change 3" >> vendor/docs/README.md -git add vendor/docs/README.md -git commit -m "Local change 3" - -REPO_DIR="$REPO_DIR" just --justfile "$JUSTFILE_CROSS" push vendor/docs feature-branch false true - -pushd "$upstream_path" >/dev/null -if ! git rev-parse --verify feature-branch >/dev/null 2>&1; then - fail "Branch 'feature-branch' was not created on upstream" -fi -last_msg=$(git -C "$upstream_path" log feature-branch -1 --pretty=%s) -if [[ "$last_msg" != "Local change 3" ]]; then - fail "Expected 'Local change 3' on feature-branch, got '$last_msg'" -fi -popd >/dev/null -log_success "Test 3 passed: Push to named branch" - -# ------------------------------------------------------------------ -# Test 4: Force Push -# ------------------------------------------------------------------ -log_header "Test 4: Force push after divergence..." -# Change history on upstream to cause conflict -pushd "$upstream_path" >/dev/null -git checkout "$default_branch" -q -echo "Conflict" >> docs/README.md -git add docs/README.md -git commit -m "Upstream conflict" -popd >/dev/null - -# Local change that conflicts (divergent history) -echo "Change 4" >> vendor/docs/README.md -git add vendor/docs/README.md -git commit -m "Local change 4" - -# Normal push should fail (non-fast-forward) -if REPO_DIR="$REPO_DIR" just --justfile "$JUSTFILE_CROSS" push vendor/docs "$default_branch" false true 2>/dev/null; then - log_info "Push succeeded unexpectedly (auto-merge may have happened)" -else - log_info "Push failed as expected (non-fast-forward)" -fi - -# Now force push -REPO_DIR="$REPO_DIR" just --justfile "$JUSTFILE_CROSS" push vendor/docs "$default_branch" true true - -pushd "$upstream_path" >/dev/null -git checkout "$default_branch" -q -git reset --hard HEAD -last_msg=$(git log -1 --pretty=%s) -if [[ "$last_msg" != "Local change 4" ]]; then - fail "Expected 'Local change 4' after force push, got '$last_msg'" -fi -popd >/dev/null -log_success "Test 4 passed: Force push" - -echo "Test 006 passed!" diff --git a/test/007_status.sh b/test/007_status.sh index ef7258f0c..6b9ccfabc 100755 --- a/test/007_status.sh +++ b/test/007_status.sh @@ -78,7 +78,7 @@ git commit -m "Upstream update" popd >/dev/null # We need to fetch in the worktree to see "behind" -# 'just cross sync' would pull and update, making it synced again. +# 'just cross update' pulls and installs, making it synced again. # We manually fetch in the worktree to simulate the state where we know about updates but haven't synced. # First, identify worktree wt_dir=$(find .cross/worktrees -maxdepth 1 -name "upstream_*" | head -n 1) @@ -93,24 +93,7 @@ check_status "vendor/docs" "Clean.*1 behind" # Reset upstream to match local first (simplification) # or just make a new commit in WT that is ahead of upstream/master # We are currently 1 behind. Let's sync to get even. -just cross sync vendor/docs - -# After sync, if there are conflicts from stash restore, clean them up -# The sync may leave merge conflict markers which need resolution -if [ -n "$(git ls-files -u vendor/docs 2>/dev/null)" ]; then - # Resolve by accepting all changes - git add vendor/docs/* 2>/dev/null || true - git stash drop 2>/dev/null || true -fi -# Also clean up any staged but uncommitted changes -git reset HEAD vendor/docs 2>/dev/null || true -git checkout vendor/docs 2>/dev/null || true - -# Force resync to ensure files match -wt_dir_fixed=$(find .cross/worktrees -maxdepth 1 -name "upstream_*" | head -n 1) -if [ -n "$wt_dir_fixed" ]; then - rsync -a --delete "$wt_dir_fixed/docs/" "vendor/docs/" -fi +just cross update vendor/docs check_status "vendor/docs" "Clean.*Synced" diff --git a/test/009_go_cli.sh b/test/009_go_cli.sh index bfc283adb..e4f704fee 100755 --- a/test/009_go_cli.sh +++ b/test/009_go_cli.sh @@ -43,6 +43,12 @@ if ! "$GO_BIN" --version >/dev/null 2>&1; then echo "Shell tests (001-007) and CI on native hardware validate the Go implementation." exit 0 fi +command_help=$("$GO_BIN" --help 2>&1) +for retired_command in sync push replay exec; do + if echo "$command_help" | grep -Eq "^[[:space:]]+$retired_command[[:space:]]"; then + fail "Retired command '$retired_command' is still exposed in Go CLI help" + fi +done # Smoke test: create a temp git repo and run 'use' to exercise gogs/git-module # This catches SIGILL from incompatible Go toolchain binaries _smoke_dir=$(mktemp -d) @@ -159,7 +165,7 @@ if ! echo "$status_output" | grep -q "vendor/go-src"; then fail "Go 'status' should show patch 'vendor/go-src'" fi -log_header "Testing Go 'sync' command..." +log_header "Testing Go 'update' command..." # Mock upstream change pushd "$upstream_path" >/dev/null echo "Updated go logic" > src/logic.go @@ -167,9 +173,28 @@ git add src/logic.go git commit -m "Update go logic" popd >/dev/null -"$GO_BIN" sync +"$GO_BIN" update vendor/go-src if ! grep -q "Updated go logic" "vendor/go-src/logic.go"; then - fail "Go 'sync' failed to pull updates" + fail "Go 'update' failed to pull updates" +fi + +log_header "Testing Go update preserves local edits while refreshing worktree..." +echo "local-only edit" >> vendor/go-src/logic.go +pushd "$upstream_path" >/dev/null +echo "upstream update after local edit" >> src/logic.go +git add src/logic.go +git commit -m "Update logic again" -q +popd >/dev/null +update_output=$("$GO_BIN" update vendor/go-src 2>&1) +echo "$update_output" +if ! grep -q "local-only edit" vendor/go-src/logic.go; then + fail "Go update overwrote the local edit" +fi +if ! echo "$update_output" | grep -q "Local edits detected"; then + fail "Go update should report local edits" +fi +if ! echo "$update_output" | grep -q "DirDiff"; then + fail "Go update should print the compare command" fi log_header "Testing Go 'diff' command..." @@ -183,6 +208,23 @@ fi # Revert the change for clean state echo "Updated go logic" > vendor/go-src/logic.go +log_header "Testing Go 'compare' command with configured tool..." +cat > "$SANDBOX/bin/compare-tool" <<'EOF' +#!/usr/bin/env bash +printf '%s\n%s\n' "$1" "$2" > "$COMPARE_TOOL_ARGS" +EOF +chmod +x "$SANDBOX/bin/compare-tool" +export COMPARE_TOOL_ARGS="$SANDBOX/compare-args.txt" +git config cross.diffTool "$SANDBOX/bin/compare-tool" +"$GO_BIN" compare vendor/go-src +if ! grep -q ".cross/worktrees/demo_" "$COMPARE_TOOL_ARGS"; then + fail "Go compare did not pass the sparse worktree path" +fi +if ! grep -q "vendor/go-src" "$COMPARE_TOOL_ARGS"; then + fail "Go compare did not pass the local patch path" +fi +git config --unset cross.diffTool + log_header "Testing Go '.crossignore' override status/diff hint..." mkdir -p vendor/go-src/subdir touch vendor/go-src/subdir/.env @@ -208,22 +250,6 @@ rm -f vendor/go-src/.crossignore rm -f vendor/go-src/subdir/.env rmdir vendor/go-src/subdir 2>/dev/null || true -log_header "Testing Go 'push' command..." -# Allow pushing to current branch in mock upstream -pushd "$upstream_path" >/dev/null -git config receive.denyCurrentBranch ignore -popd >/dev/null - -echo "Local modification" >> vendor/go-src/logic.go -git add vendor/go-src/logic.go -git commit -m "Local go change" - -"$GO_BIN" push vendor/go-src --yes -last_msg=$(git -C "$upstream_path" log -1 --pretty=%s) -if [[ "$last_msg" != "Local go change" ]]; then - fail "Go 'push' failed. Expected 'Local go change', got '$last_msg'" -fi - log_header "Testing Go 'init' command..." mkdir -p init-test pushd init-test >/dev/null @@ -233,28 +259,27 @@ if [ ! -f "Crossfile" ]; then fi popd >/dev/null -log_header "Testing Go 'replay' command..." -# Create a fresh sandbox for replay test -replay_dir="$SANDBOX/replay-test" -mkdir -p "$replay_dir" -pushd "$replay_dir" >/dev/null +log_header "Testing Go 'update' from Crossfile in a fresh repository..." +update_dir="$SANDBOX/update-test" +mkdir -p "$update_dir" +pushd "$update_dir" >/dev/null git init -q git config user.email "test@example.com" git config user.name "Test User" echo "replay test" > README.md git add . && git commit -m "init" -q -# Write a Crossfile manually +# Write declarative Crossfile configuration cat > Crossfile </dev/null log_header "Testing Go 'remove' command..." diff --git a/test/010_worktree.sh b/test/010_worktree.sh index c52dcf4cd..4314c80b4 100644 --- a/test/010_worktree.sh +++ b/test/010_worktree.sh @@ -3,10 +3,10 @@ set -euo pipefail source "$(dirname "$0")/common.sh" -# The cd/wt commands are only implemented in Go and Rust, not in Justfile/shell -# Skip this test when using Justfile implementation -if [ "${TEST_USE_IMPL:-}" != "go" ] && [ "${TEST_USE_IMPL:-}" != "rust" ]; then - echo "Skipping test 010: cd/wt commands only available in Go/Rust implementations" +# The cd/wt commands are only implemented in Go, not in Justfile/shell +# Skip this test unless the Go implementation was explicitly requested. +if [ "${TEST_USE_IMPL:-}" != "go" ]; then + echo "Skipping test 010: cd/wt commands are Go-only" exit 0 fi diff --git a/test/012_sparse_checkout.sh b/test/012_sparse_checkout.sh index 04301d713..f335e8886 100755 --- a/test/012_sparse_checkout.sh +++ b/test/012_sparse_checkout.sh @@ -61,25 +61,4 @@ fi # Clean up rm -rf vendor/app1 .cross/worktrees/* .git/worktrees/* Crossfile -# Test using Rust implementation -log_header "Testing sparse checkout in Rust" -RUST_BIN="$REPO_ROOT/src-rust/target/debug/git-cross-rust" -if [ ! -f "$RUST_BIN" ]; then - if command -v cargo >/dev/null 2>&1; then - cargo build --manifest-path "$REPO_ROOT/src-rust/Cargo.toml" || true - fi -fi -if [ -f "$RUST_BIN" ]; then - "$RUST_BIN" init - "$RUST_BIN" use demo "$upstream_url" - "$RUST_BIN" patch demo:apps/app1 vendor/app1 - - wt_path=$(find .cross/worktrees -maxdepth 1 -name "demo_*" | head -n 1) - if [ -f "$wt_path/root.txt" ]; then - fail "root.txt found in worktree! Sparse checkout failed for Rust." - fi -else - log_warn "Rust binary not available, skipping Rust sparse checkout test" -fi - echo "Sparse checkout validation passed!" diff --git a/test/014_remove.sh b/test/014_remove.sh index f057d32c5..9df9d0ad6 100755 --- a/test/014_remove.sh +++ b/test/014_remove.sh @@ -46,23 +46,6 @@ else echo "SKIP: Go binary not available, skipping Go removal test" fi -# 3. Test removal in Rust implementation -echo "## Testing removal in Rust..." -RUST_BIN="$REPO_ROOT/src-rust/target/debug/git-cross-rust" -if [ ! -f "$RUST_BIN" ] && command -v cargo >/dev/null 2>&1; then - ( cd "$REPO_ROOT/src-rust" && cargo build -q ) || RUST_BIN="" -fi -if [ -n "$RUST_BIN" ] && [ -f "$RUST_BIN" ]; then - just cross patch repo1:src/lib vendor/app-rust - "$RUST_BIN" remove vendor/app-rust - - if [ -d "vendor/app-rust" ]; then fail "vendor/app-rust still exists after remove"; fi - if grep -q "vendor/app-rust" Crossfile; then fail "Crossfile still contains patch entry"; fi - if grep -q "vendor/app-rust" .cross/metadata.json; then fail "Metadata still contains patch entry"; fi -else - echo "SKIP: Rust binary not available, skipping Rust removal test" -fi - # 4. Test list command (Go) - need active patch for remotes to show if [ -n "$GO_BIN" ] && [ -f "$GO_BIN" ]; then echo "## Testing 'list' command (Go)..." @@ -82,24 +65,6 @@ if [ -n "$GO_BIN" ] && [ -f "$GO_BIN" ]; then if [ "$count_after" -ne "$count_before" ]; then fail "Crossfile duplication occurred (Go)"; fi else echo "SKIP: Go binary not available, skipping Go list and dedup tests" - # Still need vendor/dedup-test for Rust dedup test below - just cross patch repo1:src/lib vendor/dedup-test - count_before=$(grep -c "vendor/dedup-test" Crossfile) -fi - -# 6. Test Crossfile deduplication (Rust) -echo "## Testing Crossfile deduplication (Rust)..." -if [ -f "$REPO_ROOT/src-rust/target/debug/git-cross-rust" ]; then - "$REPO_ROOT/src-rust/target/debug/git-cross-rust" patch repo1:main:src/lib vendor/dedup-test - count_after_rust=$(grep -c "vendor/dedup-test" Crossfile) - if [ "$count_after_rust" -ne "$count_before" ]; then fail "Crossfile duplication occurred (Rust)"; fi - - # 7. Test list command (Rust) - echo "## Testing 'list' command (Rust)..." - list_output_rust=$("$REPO_ROOT/src-rust/target/debug/git-cross-rust" list) - if ! echo "$list_output_rust" | grep -q "Configured Remotes"; then fail "Rust list missing Remotes section"; fi -else - echo "SKIP: Rust binary not available, skipping Rust dedup and list tests" fi # 8. Test root-target remove safety guard (Shell/Just) diff --git a/test/017_cd_wt_fix.sh b/test/017_cd_wt_fix.sh index 7035a10aa..576495f83 100755 --- a/test/017_cd_wt_fix.sh +++ b/test/017_cd_wt_fix.sh @@ -110,25 +110,6 @@ else log_warn "Go binary not found at $GO_BIN, skipping Go tests" fi -# Test 7: Test Rust implementation -log_info "Test 7: Testing Rust implementation..." -RUST_BIN="$REPO_ROOT/src-rust/target/debug/git-cross-rust" -if [ -f "$RUST_BIN" ]; then - if "$RUST_BIN" cd non-existent-path 2>&1 | grep -qE "not found|No patches"; then - log_success "Rust: cd correctly reports non-existent path" - else - log_warn "Rust: cd error handling may need improvement" - fi - - if "$RUST_BIN" wt non-existent-path 2>&1 | grep -qE "not found|No patches"; then - log_success "Rust: wt correctly reports non-existent path" - else - log_warn "Rust: wt error handling may need improvement" - fi -else - log_warn "Rust binary not found at $RUST_BIN, skipping Rust tests" -fi - # Cleanup cd / rm -rf "$test_repo" "$upstream" diff --git a/test/018_sbx_sandbox.sh b/test/018_sbx_sandbox.sh index 0327d2974..7d56a9858 100644 --- a/test/018_sbx_sandbox.sh +++ b/test/018_sbx_sandbox.sh @@ -1,173 +1,51 @@ #!/usr/bin/env bash set -euo pipefail - -# Test: AI sandbox (sbx/docker sandbox) workflow with git-cross. -# -# Simulates the workflow where: -# 1. Host sets up git-cross patches -# 2. A sandbox/container only sees the vendor subfolder (no .git/) -# 3. AI tool modifies files inside the sandbox -# 4. Host pushes changes back upstream via git-cross -# -# Since we cannot run actual Docker/sbx containers in CI, this test -# simulates the sandbox boundary by copying the vendor subfolder to -# an isolated directory (simulating a container mount) and verifying -# the full round-trip works. - source "$(dirname "$0")/common.sh" setup_sandbox cd "$SANDBOX" -# Build or reuse Go binary GO_BIN="$REPO_ROOT/src-go/git-cross-go" if [ ! -f "$GO_BIN" ]; then - if command -v go >/dev/null 2>&1; then - rm -r "$REPO_ROOT/src-go/vendor" 2>/dev/null || true - ( cd "$REPO_ROOT/src-go" && CGO_ENABLED=0 go build -mod=mod -tags purego -o git-cross-go main.go ) - else - echo "SKIP: Go not available, skipping sbx sandbox test" + if ! command -v go >/dev/null 2>&1; then + echo "SKIP: Go not available" exit 0 fi -fi -if ! "$GO_BIN" --version >/dev/null 2>&1; then - echo "SKIP: Go binary not working on this platform" - exit 0 + rm -rf "$REPO_ROOT/src-go/vendor" 2>/dev/null || true + (cd "$REPO_ROOT/src-go" && CGO_ENABLED=0 go build -mod=mod -tags purego -o git-cross-go main.go) fi -# --- 1. Host: create upstream with realistic content --- -log_header "Setting up upstream repo with multi-file project..." upstream_path=$(create_upstream "ai-project") -upstream_url="file://$upstream_path" +mkdir -p "$upstream_path/src" +echo "v1" > "$upstream_path/src/app.js" +git -C "$upstream_path" add src/app.js +git -C "$upstream_path" commit -m "Add app" -q -pushd "$upstream_path" >/dev/null -mkdir -p src/components -echo 'export function App() { return "Hello"; }' > src/components/App.js -echo 'export function utils() { return true; }' > src/components/utils.js -echo '{"name": "ai-project"}' > src/package.json -git add . -git commit -m "Initial project structure" -q -popd >/dev/null - -# --- 2. Host: set up git-cross patches --- -log_header "Host: setting up git-cross vendor..." -"$GO_BIN" use ai-project "$upstream_url" +"$GO_BIN" use ai-project "file://$upstream_path" "$GO_BIN" patch ai-project:src vendor/ai-src -assert_file_exists "vendor/ai-src/components/App.js" -assert_file_exists "vendor/ai-src/components/utils.js" -assert_file_exists "vendor/ai-src/package.json" -log_success "Vendor directory populated" - -# --- 3. Simulate sandbox: copy vendor subfolder to isolated directory --- -# This mimics what `sbx create --mount vendor/ai-src` does: -# the container only sees vendor/ai-src/, with NO .git/ directory. -log_header "Simulating sandbox mount (isolated copy, no .git)..." -SBX_DIR=$(mktemp -d) -# rsync just the vendor subfolder — sandbox doesn't get .git/ or .cross/ -rsync -a vendor/ai-src/ "$SBX_DIR/" - -# Verify sandbox isolation: no git metadata -if [ -d "$SBX_DIR/.git" ]; then - fail "Sandbox should NOT contain .git directory" +# Simulate local/sandbox edits and a concurrent upstream update. +echo "local AI change" > vendor/ai-src/app.js +echo "upstream v2" > "$upstream_path/src/app.js" +echo "new upstream file" > "$upstream_path/src/new.js" +git -C "$upstream_path" add src +git -C "$upstream_path" commit -m "Upstream update" -q + +output=$("$GO_BIN" update vendor/ai-src 2>&1) +echo "$output" +if ! grep -q "local AI change" vendor/ai-src/app.js; then + fail "Update overwrote local changes" fi -if [ -d "$SBX_DIR/.cross" ]; then - fail "Sandbox should NOT contain .cross directory" -fi -assert_file_exists "$SBX_DIR/components/App.js" -log_success "Sandbox is isolated (no .git, no .cross)" - -# --- 4. Simulate AI tool modifying files in the sandbox --- -log_header "AI tool modifying files in sandbox..." -# AI adds a new component -echo 'export function NewFeature() { return "AI-generated"; }' > "$SBX_DIR/components/NewFeature.js" -# AI modifies an existing file -echo 'export function App() { return "Hello from AI"; }' > "$SBX_DIR/components/App.js" -# AI adds a test file -mkdir -p "$SBX_DIR/tests" -echo 'test("App renders", () => { /* AI test */ });' > "$SBX_DIR/tests/App.test.js" -log_success "AI modifications applied in sandbox" - -# --- 5. Host: copy sandbox changes back to vendor subfolder --- -# This mimics the sandbox unmount / file sync back to host -log_header "Syncing sandbox changes back to host vendor dir..." -rsync -a "$SBX_DIR/" vendor/ai-src/ - -# Verify host has the AI changes -assert_file_exists "vendor/ai-src/components/NewFeature.js" -assert_grep "vendor/ai-src/components/App.js" "Hello from AI" -assert_file_exists "vendor/ai-src/tests/App.test.js" -log_success "Host vendor dir updated with AI changes" - -# --- 6. Host: use git-cross diff to review changes --- -log_header "Reviewing AI changes with git cross diff..." -diff_output=$("$GO_BIN" diff vendor/ai-src 2>&1 || true) -if ! echo "$diff_output" | grep -q "NewFeature"; then - fail "diff should show new AI-generated file" +if ! echo "$output" | grep -q "Local edits detected"; then + fail "Update did not report the conflict review workflow" fi -if ! echo "$diff_output" | grep -q "Hello from AI"; then - fail "diff should show AI modification" +if ! echo "$output" | grep -q "DirDiff"; then + fail "Update did not show the default comparison tool command" fi -log_success "git cross diff shows AI changes correctly" -# --- 7. Host: push AI changes back upstream --- -log_header "Pushing AI changes upstream via git cross push..." -# Allow pushing to current branch in mock upstream -pushd "$upstream_path" >/dev/null -git config receive.denyCurrentBranch ignore -popd >/dev/null - -# Commit the AI changes locally first -git add vendor/ai-src/ -git commit -m "AI-generated improvements" -q - -"$GO_BIN" push vendor/ai-src --yes - -# Verify upstream received the changes -pushd "$upstream_path" >/dev/null -git checkout HEAD -- . 2>/dev/null || true -if [ ! -f "src/components/NewFeature.js" ]; then - fail "Upstream should have AI-generated NewFeature.js" +wt=$(jq -r '.patches[0].worktree' .cross/metadata.json) +if ! git -C "$wt" show HEAD:src/app.js | grep -q "upstream v2"; then + fail "Sparse worktree did not update from upstream" fi -popd >/dev/null -log_success "AI changes pushed to upstream" - -# --- 8. Simulate fresh sandbox setup via replay --- -log_header "Testing Crossfile replay (fresh sandbox setup)..." -replay_dir="$SANDBOX/replay-sbx" -mkdir -p "$replay_dir" -pushd "$replay_dir" >/dev/null -git init -q -git config user.email "test@example.com" -git config user.name "Test User" -echo "fresh" > README.md -git add . && git commit -m "init" -q - -# Write Crossfile as if setting up a new dev environment -cat > Crossfile </dev/null - -# --- 9. Verify sync pulls latest upstream changes --- -log_header "Testing sync after upstream changes..." -pushd "$upstream_path" >/dev/null -echo 'export function Hotfix() { return "urgent"; }' > src/components/Hotfix.js -git add . -git commit -m "Upstream hotfix" -q -popd >/dev/null - -"$GO_BIN" sync vendor/ai-src -assert_file_exists "vendor/ai-src/components/Hotfix.js" -log_success "Sync pulled upstream hotfix into vendor" - -# Cleanup -rm -r "$SBX_DIR" 2>/dev/null || true - -echo "" -echo "AI sandbox (sbx) workflow test passed!" +assert_file_exists "$wt/src/new.js" +echo "Update workflow test passed." diff --git a/test/run-all.sh b/test/run-all.sh index 54376840d..2311420f7 100755 --- a/test/run-all.sh +++ b/test/run-all.sh @@ -55,6 +55,17 @@ else tests=(test/[0-9]*.sh) fi +active_tests=() +for t in "${tests[@]}"; do + case "$(basename "$t")" in + 005_replay.sh|006_push.sh|008_rust_cli.sh|011_rust_push.sh) + echo "Skipping retired workflow test: $t" + ;; + *) active_tests+=("$t") ;; + esac +done +tests=("${active_tests[@]}") + for t in "${tests[@]}"; do # If the file doesn't exist (e.g. glob failed), skip diff --git a/test/test-all-implementations.sh b/test/test-all-implementations.sh index 4a242d00f..150b6ed1d 100755 --- a/test/test-all-implementations.sh +++ b/test/test-all-implementations.sh @@ -18,9 +18,6 @@ run_implementation_tests() { shell) ./test/run-all.sh ;; - rust) - ./test/008_rust_cli.sh - ;; go) ./test/009_go_cli.sh ;; @@ -32,7 +29,7 @@ run_implementation_tests() { } failed_count=0 -impls=("shell" "rust" "go") +impls=("shell" "go") for impl in "${impls[@]}"; do if ! run_implementation_tests "$impl"; then From 84467f409dcccd7f3034ab342af54c347168b2be Mon Sep 17 00:00:00 2001 From: Petr Michalec Date: Thu, 5 Nov 2026 14:14:51 +0100 Subject: [PATCH 02/22] add opencode --- opencode.jsonc | 52 ++++++++++++++++++++++++++++++++++++++++++ sbxenv.yaml | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 opencode.jsonc create mode 100644 sbxenv.yaml diff --git a/opencode.jsonc b/opencode.jsonc new file mode 100644 index 000000000..eb000890d --- /dev/null +++ b/opencode.jsonc @@ -0,0 +1,52 @@ +// V2-compatible copy of opencode.jsonc. +// sbx-init-template: ~/.config/opencode/opencode2-requesty.jsonc +{ + "$schema": "https://opencode.ai/config.json", + "default_agent": "plan", + "share": "disabled", + "instructions": [ + "AGENTS.md", + "CLAUDE.md", + "GEMINI.md" + ], + "lsp": true, + "update": "disable", + "permissions": [ + // Don't let the agent push to git. + { "action": "shell", "resource": "git push *", "effect": "deny" }, + // Never decrypt SOPS secrets. + { "action": "shell", "resource": "*sops -d*", "effect": "deny" }, + // Destructive recursive deletion is unnecessary in this sandbox setup. + { "action": "shell", "resource": "rm -rf *", "effect": "deny" }, + { "action": "external_directory", "resource": "~/.local/share/opencode/worktree/*", "effect": "allow" } + ], + // These local plugins require an image that bundles them under /etc/opencode/plugins/. + "plugins": [ + //"@hueyexe/opencode-ensemble@0.18.0", + "@dylanrussell/agent-router@latest" + //"github:regolo-ai/brick" + ], + "providers": { + "requesty": { + "name": "Requesty", + "env": ["REQUESTY_API_KEY"], + "package": "@opencode/ai/providers/openai-compatible", + "settings": { + "baseURL": "https://router.requesty.ai/v1", + "setCacheKey": true, + "timeout": 600000, + "headerTimeout": 300000, + "chunkTimeout": 180000 + }, + "models": { + "openai/gpt-6-luna:flex": { + "name": "GPT-6 Luna Flex (Global)" + }, + "azure/gpt-6-luna@westeurope": { + "name": "GPT-6 Luna (Azure West Europe)" + } + } + } + }, + "model": "requesty/openai/gpt-6-luna:flex" +} diff --git a/sbxenv.yaml b/sbxenv.yaml new file mode 100644 index 000000000..e86c637c6 --- /dev/null +++ b/sbxenv.yaml @@ -0,0 +1,62 @@ +# Docker Sandbox environment file (schema version 1). +# See https://docs.docker.com/ai/sandboxes/configuration/environment-files/ +# +# https://docs.docker.com/ai/sandboxes/configuration/environment-files/ +# https://docs.docker.com/ai/sandboxes/configuration/environment-files/#add-v3-kits +# https://docs.docker.com/ai/sandboxes/customize/use-kits/ +# +# https://github.com/docker/sbx-kits-contrib/tree/v3 +# +# https://docs.docker.com/ai/sandboxes/customize/use-kits/#published-v3-workloads +# https://hub.docker.com/search?type=sbx_kit&badges=verified_publisher +# +# sbx env run sbxenv.yaml sbxenv.local.yaml + + + +schemaVersion: "1" +workspace: . + +# MUST MATCH KIT +agent: opencode-v2 +#agent: sbx-kit-opencode + +# Optional host-global OpenCode extensions. Prefer project-local +# .opencode/plugins and .opencode/agents where possible. Uncomment only the +# directories you use, and replace /home/you with your host home directory. +#additionalWorkspaces: +# - path: /home/you/.config/opencode/plugins +# target: /home/agent/.config/opencode/plugins +# readOnly: true +# - path: /home/you/.config/opencode/agent +# target: /home/agent/.config/opencode/agent +# readOnly: true +# - path: /home/you/.config/opencode/agents +# target: /home/agent/.config/opencode/agents +# readOnly: true + +env: + OPENCODE_CONFIG: ./opencode.jsonc + +kits: + # collision with sbx's built-in `opencode` agent. + - /home/epcim/.config/sbx-kits/opencode-v2 + + # MIXINS + # Docker v3 kit sources. Mem0 context and gh are spec examples; + # Neovim and Docker Agent mixin are from the contrib catalog. + # sbx settings set kit.allowedSources '["docker.io/","github.com/docker/"]' + # + # - "git+https://github.com/docker/sandbox-kit-spec.git#ref=main&dir=examples/mem0-context" + # - "git+https://github.com/docker/sbx-kits-contrib.git#ref=v3&dir=neovim" + # - "git+https://github.com/docker/sbx-kits-contrib.git#ref=v3&dir=docker-agent-mixin" + # - "git+https://github.com/docker/sandbox-kit-spec.git#ref=main&dir=examples/gh" + + # Add local kits as needed; replace with absolute host paths: + - /home/epcim/.config/sbx-kits/requesty + - /home/epcim/.config/sbx-kits/apealive + # - /home/you/.config/sbx-kits/cuelang + # - /home/you/.config/sbx-kits/mxc + +# Keep machine-specific overrides in sbxenv.local.yaml and run: +# sbx env run sbxenv.yaml sbxenv.local.yaml From 962a128f6c60d0bfd55fa7a86fdbae0f46e91f9e Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 19:14:00 +0100 Subject: [PATCH 03/22] =?UTF-8?q?feat:=20UX=20refresh=20=E2=80=94=20row=20?= =?UTF-8?q?listings,=20diffTool=20templates,=20.git=20exclusion,=20cd/wt?= =?UTF-8?q?=20path=20output,=20help=20groups,=20list=20--raw?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Go + Justfile.cross implementations with tests and docs: - update: concise warning, relative paths; .git pointer file excluded from comparisons (whole-repo patches update again) - compare: {left}/{right} diffTool template (default vim +DirDiffIgnore='.git'), cmp alias, fzf/patch-row fallback instead of Usage dump - diff: pathspec exclude for .git; CWD auto-detect -> fzf -> rows ladder - cd/wt: print absolute path only (no subshell, no clipboard) - bare 'git cross' prints local_pathworktree rows - help grouped: Repository / Inspect & Navigate / Patch Lifecycle - list --raw/--no-header (TSV, deterministic order, descriptive headers) - local_path normalization (./mxc2) at ingestion and matching - root Justfile: forward args with "$@" (metacharacter-safe) - tests: new 019/020/021/023 + reworked 003/004/007/009/010/014/016/017/018 --- AGENTS.md | 57 +- CHANGELOG.md | 24 +- Justfile | 9 +- Justfile.cross | 390 +++++++++----- README.md | 236 ++++++++- src-go/main.go | 640 ++++++++++++++--------- test/003_diff.sh | 7 +- test/004_update.sh | 52 ++ test/007_status.sh | 22 + test/009_go_cli.sh | 105 +++- test/010_worktree.sh | 54 +- test/014_remove.sh | 50 ++ test/016_diff_context.sh | 70 ++- test/017_cd_wt_fix.sh | 251 +++++---- test/018_sbx_sandbox.sh | 17 +- test/019_whole_repo_patch_and_listing.sh | 189 +++++++ test/020_help_groups.sh | 75 +++ test/021_fzf_diff_compare.sh | 200 +++++++ test/023_localpath_normalization.sh | 187 +++++++ test/common.sh | 80 +++ 20 files changed, 2122 insertions(+), 593 deletions(-) create mode 100755 test/004_update.sh create mode 100755 test/019_whole_repo_patch_and_listing.sh create mode 100755 test/020_help_groups.sh create mode 100755 test/021_fzf_diff_compare.sh create mode 100755 test/023_localpath_normalization.sh diff --git a/AGENTS.md b/AGENTS.md index 01d65765a..1199b9fc2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,7 +29,7 @@ src-rust/Cargo.toml # Rust dependencies worktrees/ # Hidden git worktrees for each patch test/common.sh # Shared test helpers (setup_sandbox, create_upstream, assertions) test/run-all.sh # Test runner: discovers and executes test/NNN_*.sh files -test/001-018_*.sh # Individual test files (see coverage matrix below) +test/001-023_*.sh # Individual test files (see coverage matrix below) ``` ## Commands (all implementations) @@ -39,15 +39,17 @@ test/001-018_*.sh # Individual test files (see coverage matrix below) | `use` | ` ` | Register remote, detect default branch | | `patch` | ` [local_path]` | Sparse-checkout worktree, rsync to local | | `update` | `[path]` | Read Crossfile and update upstream patches; preserve local edits | -| `diff` | `[path]` | `git diff --no-index` between worktree and local (context-aware: auto-detects patch from CWD) | -| `list` | | Table of remotes and patches | +| `diff` | `[path]` | Console `git diff --no-index`; resolves patch via CWD auto-detect → fzf → rows + exit 1 | +| `list` | `[--raw] [--no-header]` | Table (default) or TSV rows of remotes and patches | | `status` | | Health: local diffs, upstream divergence, conflicts | -| `compare` | `[path]` | Open configured directory diff tool between local copy and worktree | +| `compare` | `[path]` (alias `cmp`) | Open configured directory diff tool; exactly one patch, same resolution ladder as `diff` | | `remove` | `` | Delete patch, clean Crossfile and metadata | | `prune` | `[remote]` | Remove remote and all its patches, prune stale worktrees | | `init` | | Create empty Crossfile | -| `cd` | `[path]` | Open shell in local_path (or fzf select + clipboard) | -| `wt` | `[path]` | Open shell in worktree (or fzf select + clipboard) | +| `cd` | `[path]` | Print absolute local_path to stdout (wrap with `cd "$(git cross cd)"`) | +| `wt` | `[path]` | Print absolute worktree path to stdout | + +Bare `git cross` prints one `local_pathworktree` row per patch to stdout (hint to stderr); `-h` prints the grouped help. Help grouping is Go-only CLI presentation — Just/Fish exposes the same behavior through recipes, not through a grouped help renderer. ## Implementation Comparison @@ -79,7 +81,7 @@ test/001-018_*.sh # Individual test files (see coverage matrix below) ### Known historical issues -1. **`cd`/`wt` code duplication**: Near-identical blocks in Go (80 lines) and Rust (56 lines). Should be a single parameterized function. +1. **`cd`/`wt` duplication (resolved)**: Go now uses one parameterized `makeDirCmd`; Just has one recipe per target. Rust retains its own unsupported implementation. 2. **`remove`/`prune` code duplication**: Prune copy-pastes remove logic. Should call a shared `removePatch()` helper. 3. The retired `sync` flow rebased local changes. The supported `update` flow fetches upstream, fast-forwards a clean worktree, and preserves local files for manual review if they differ. 4. **Crossfile removal is fragile**: All three use substring matching that can corrupt unrelated lines. @@ -89,34 +91,40 @@ test/001-018_*.sh # Individual test files (see coverage matrix below) ### Test Structure -Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 exercises Go. Rust, push, and replay legacy tests are excluded from the default runner. Tests 010-018 are focused feature tests. +Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 exercises Go. Rust, push, and replay legacy tests are excluded from the default runner. Tests 010-023 are focused feature tests; 019-023 cover the UX refresh (row listings and whole-repo patches, grouped help, fzf selection, `local_path` normalization). ### Coverage Matrix -| Command | Just/Fish | Go | +| Command / behavior | Just/Fish | Go | |---------|:---:|:---:| | `use` | 001 | 009 | -| `patch` | 002 | 009 | -| `update` (upstream/local edit behavior) | 004 | 009, 018 | +| `patch` | 002 | 009, 019, 023 | +| `update` (upstream/local edit behavior) | 004 | 009, 018, 019 | | `diff` (basic) | 003 | 009 | -| `diff` (context-aware CWD) | 003, 016 | 016 | +| `diff` (context-aware CWD) | 003, 016 | 016, 021 | +| `diff` (no path: fzf / rows ladder) | -- | 021 | | `diff` (relative paths) | 003 | -- | -| `list` | (017) | 009, 014 | -| `status` (all states) | 007 | 009* | -| `compare` | -- | 009 | -| `remove` | 014 | 014 | +| `list` (table) | -- | 009, 014 | +| `list --raw` / `--no-header` | -- | 009, 014 | +| `status` (all states) | 007 | 009*, 019, 023 | +| `compare` (incl. `cmp` alias) | -- | 009, 019, 021 | +| `remove` | 014 | 014, 023 | | `prune` | 015 | 009 | -| `cd`/`wt` | 017 | 017 | +| `cd`/`wt` (print path) | 017 | 017, 023 | | `init` | -- | 009 | | `sparse checkout` | 012 | 012 | | `sbx/update workflow` | -- | 018 | +| whole-repo patch (`.git` exclusion) | 019‡ | 019 | +| grouped `--help` | n/a | 020 | +| `local_path` normalization | 023‡ | 023 | -`*` = partial/basic assertions only. `--` = not tested. +`*` = partial/basic assertions only. `--` = not tested. `‡` = variant guarded by Fish availability (skips gracefully when `fish` is absent). ### Gaps Worth Addressing - **Just update behavior**: requires Fish to be installed; run `test/004_update.sh` in an environment with Fish. -- **`list` for Just/Fish**: no dedicated test. +- **Just `list` output**: no dedicated test; `test/019` exercises patch row listings when Fish is available. +- **Just variants**: `test/019` and `test/023` include Fish-guarded variants that skip when `fish` is absent; `test/020` and `test/021` are Go-only. CI should keep Fish present to avoid silent gaps. ## Agent Workflow @@ -179,9 +187,13 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 ## Implementation Details -- **Hidden worktrees**: `.git/cross/worktrees/_`. +- **Hidden worktrees**: `.cross/worktrees/_` (verified in `src-go/main.go`; Justfile.cross uses the same path). A stale `AICONTEXT` comment in `Justfile.cross` (line 697) still says `.git/cross/worktrees/` and should be corrected by the Just owner. +- **`.git` exclusion**: a worktree root contains a `.git` pointer file that never exists in the local copy (rsync uses `--exclude .git`). Boolean tree comparisons use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff uses `git diff --no-index -- ':(exclude).git' ':(glob)**'`. Without both exclusions, whole-repo patches always look modified. - **Sparse checkout**: `git sparse-checkout init --no-cone` + `git sparse-checkout set /` + `git read-tree -mu HEAD`. The trailing `/` on the pattern is required for reliable directory matching in `--no-cone` mode on newer Git versions (2.43+). `read-tree -mu HEAD` explicitly materializes the worktree (bare `git checkout` can no-op after `--no-checkout`). - **Rsync**: `rsync -av --delete --exclude .git` for worktree-to-local sync. `--delete` removes files locally that were deleted upstream. +- **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `vim "+DirDiffIgnore='.git' DirDiff {left} {right}"`. Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). +- **Patch rows**: bare `git cross`, and path-miss cases in `compare`/`diff`/`remove`/`cd`/`wt`, print `local_pathworktree` rows to stdout; hints go to stderr and the command exits 1 where nothing was resolved. +- **`list --raw` schema**: remotes first (`REMOTE_NAMEREMOTE_URL`), then patches (`REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`); no banners, no borders, deterministic remote order. - **Crossfile format**: Lines like `cross use ` or `cross patch :: `. `update` interprets only these declarative commands; arbitrary shell commands are not executed. - **.crossignore**: Located in the root of each local_path, uses gitignore-style patterns to exclude files from status and diff comparisons. Implemented by filtering directory trees using git add and git clean to remove ignored files before comparison. @@ -190,6 +202,5 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 When time allows, these structural improvements would most benefit the codebase: 1. **Extract `removePatch()` helper** in Go and Rust — eliminates duplication between `remove` and `prune`. -2. **Unify `cd`/`wt`** into a single parameterized function in Go and Rust. -3. **Fix Crossfile removal** — use structured parsing (split line, match local_path field) instead of substring matching. -4. **Consolidate Go's git interface** — pick either `gogs/git-module` or `os/exec` and use it consistently. +2. **Fix Crossfile removal** — use structured parsing (split line, match local_path field) instead of substring matching. +3. **Consolidate Go's git interface** — pick either `gogs/git-module` or `os/exec` and use it consistently. diff --git a/CHANGELOG.md b/CHANGELOG.md index 05e60b74a..5c4ac2728 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### UX Refresh — navigation, selection, listing, diff tool + +#### Added +- **`git cross cmp`** - Short alias for `compare`; the canonical name is unchanged. +- **Grouped `--help` output** - Commands are now listed under `Repository:`, `Inspect & Navigate:`, and `Patch Lifecycle:` instead of one flat list. `git cross -h` still prints full help. +- **`list --raw` and `list --no-header`** - `--raw` emits tab-separated rows with no table borders and no `==>` banners; `--no-header` omits the header line. Raw column order is documented and fixed: `REMOTE_NAMEREMOTE_URL` first, then `REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`. Remote rows are sorted deterministically, remotes with distinct fetch/push URLs produce one row per URL without `(fetch)`/`(push)` suffixes, and the empty-state message goes to stderr in raw mode. +- **Patch row listings** - Bare `git cross` prints one `local_pathworktree` row per patch to stdout (hint to stderr) instead of Cobra help. Unresolved `compare` / `diff` / `remove` / `cd` / `wt` invocations print the same rows and exit 1 instead of dumping a usage block. +- **Tests 019, 020, 021, 023** - Cover whole-repo patches plus row listings, grouped help, fzf-driven `diff`/`compare`, and `local_path` normalization. + +#### Changed +- **BREAKING: `cd` / `wt` print a path instead of opening a shell** - Both commands print the absolute destination path to stdout (hints to stderr). They no longer start a subshell and no longer copy anything to the clipboard. Use `cd "$(git cross cd)"`, `cd "$(git cross wt)"`, or the documented `crosscd`/`crosswt` wrappers for bash/zsh/fish. Without an argument `fzf` selects the patch; if `fzf` is missing, rows plus a hint are printed and the command exits 1. +- **Behavior change: interactive `diff` selection** - With no path, `diff` now resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. +- **`compare` selection ladder** - With no path, `compare` uses the same CWD auto-detect → `fzf` → rows + hint + exit 1 ladder and always operates on exactly one patch. +- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is now `vim "+DirDiffIgnore='.git' DirDiff {left} {right}"`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. +- **Concise `update` warning** - Local edits now produce one relative, actionable line: `'' differs from upstream; local copy preserved. Compare with: git cross diff `. The `cross.diffTool` configuration hint and the broken DirDiff invocation are gone. + +#### Fixed +- **DirDiff invocation** - `compare` passed the two paths as vim file arguments, where DirDiff never saw them. Paths now go inside the vim `+` command string. +- **`.git` false positives in comparisons** - The worktree's `.git` pointer file (never present in the local copy) counted as a local deletion. Boolean checks now use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff excludes `.git` with the `:(exclude).git` pathspec. As a result, whole-repo patches (`remote:.`) no longer always report `Modified` in `status` or always warn in `update`; clean whole-repo patches now update. +- **`local_path` normalization** - A local path such as `./mxc2` was stored verbatim and broke CWD auto-detection (`compare`, `diff`, `cd`/`wt`, `remove`). Paths are normalized on ingestion, normalized defensively during matching, and self-healed on metadata load; the `Crossfile` keeps the user's original spelling. +- **Deterministic `list` ordering** - Remotes are sorted instead of following Go map iteration order. + ### Changed - **Simplified upstream workflow** - Added `git cross update [path]` to read declarative `use`/`patch` entries from `Crossfile`, fetch upstream, fast-forward sparse worktrees, and install only when the local copy has no edits. Local edits are preserved while the worktree advances for manual comparison. -- **Manual contribution workflow** - Retired `push`; use `wt`, `compare`, and ordinary Git commands to manually copy and commit desired changes in the sparse worktree. Configure the directory diff command with `git config --global cross.diffTool 'vim "+DirDiff"'`. +- **Manual contribution workflow** - Retired `push`; use `wt`, `compare`, and ordinary Git commands to manually copy and commit desired changes in the sparse worktree. The comparison tool is configured with `cross.diffTool` (see the Directory Diff Tool section in `README.md`). - **Retired replay and arbitrary Crossfile commands** - `update` interprets only `use` and `patch`; hooks and shell commands are no longer run from Crossfile. - **Supported implementations** - Go remains primary and Just/Fish the reference. Rust source is retained but no longer maintained; release artifacts are Go-only. - **Retired sync workflow** - The prior stash/copy/rebase logic is removed from the supported CLI and Just recipes. diff --git a/Justfile b/Justfile index f02154f59..f08e3179f 100644 --- a/Justfile +++ b/Justfile @@ -2,21 +2,24 @@ import? "git.just" # Delegate all invocations to the full recipe set [no-cd] +[positional-arguments] @cross *ARGS: REPO_DIR=$(git rev-parse --show-toplevel) \ USER_CWD=${USER_CWD:-$(pwd)} \ - just --justfile "{{source_dir()}}/Justfile.cross" {{ARGS}} + just --justfile "{{source_dir()}}/Justfile.cross" "$@" # keep compatibility with `just test-cross` [no-cd] +[positional-arguments] @cross-test *ARGS: REPO_DIR=$(git rev-parse --show-toplevel) \ - just --justfile "{{source_dir()}}/Justfile.cross" test "{{ARGS}}" + just --justfile "{{source_dir()}}/Justfile.cross" test "$@" # Run the Go implementation [no-cd] +[positional-arguments] @cross-go *ARGS: - go run -C "{{source_dir()}}/src-go" main.go {{ARGS}} + go run -C "{{source_dir()}}/src-go" main.go "$@" # Install git alias for git-cross (Go or Just) [no-cd] diff --git a/Justfile.cross b/Justfile.cross index 663883578..c8fd92f67 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -8,8 +8,6 @@ METADATA := "$CROSSDIR/metadata.json" JUST_DIR := env("JUST_DIR", source_dir()) REPO_DIR := env ("REPO_DIR", "$(git rev-parse --show-toplevel)") SHELL := env("SHELL") -dry := "" - # Auto-setup environment on first use # AICONTEXT: Optional target to help user to ensure correct setup for tool usage. Taks: Call direnv, loading .envrc and from that .env file. Ideally short implementation. @@ -106,6 +104,10 @@ _resolve_context2 path="": check-initialized #!/usr/bin/env fish # Resolve git repo relative path of target + if test "$path" = "." -o "$path" = "./" + # "." means the caller's directory — same as no path + set path "" + end if test -z "$path" # Use USER_CWD (set by root Justfile cross recipe) to preserve caller's CWD if test -n "$USER_CWD" -a -n "$REPO_DIR" @@ -125,12 +127,17 @@ _resolve_context2 path="": check-initialized end # Query metadata.json and export matching key as env variables # Find patch whose local_path is a prefix of (or equal to) the given path - # i.e. path starts with local_path — handles both exact match and subdirectory cases + # i.e. path starts with local_path — handles both exact match and subdirectory cases. + # Paths are normalized ("^\\./" stripped) so "./mxc2" in metadata still matches "mxc2". jq -r --arg path "$path" ' .patches - | map(. as $patch | select($path | startswith($patch.local_path))) - | map(. + {mlen:(.local_path|length)}) + | map(. as $patch + | ($patch.local_path | ltrimstr("./")) as $lp + | select(($path | ltrimstr("./")) | startswith($lp)) + | $patch + {mlen: ($lp | length)}) | max_by(.mlen) + | select(. != null) + | del(.mlen) | to_entries | map("set -x \(.key) \(.value|@sh)") | .[] ' "{{REPO_DIR}}/{{METADATA}}" @@ -220,6 +227,35 @@ _log level +message: echo "==> {{message}}" end +# Print one row per patch: local_pathworktree (machine-parseable). +# hint is variadic because the Justfile wrapper word-splits arguments. +[no-cd] +_list_patches *hint="": + #!/usr/bin/env fish + if not test -f "{{REPO_DIR}}/.cross/metadata.json" + just cross _log info "No patches configured." + exit 0 + end + set -l hint_text "{{hint}}" + if test -n "$hint_text" + echo "$hint_text" >&2 + end + jq -r '.patches[] | "\(.local_path)\t\(.worktree)"' "{{REPO_DIR}}/.cross/metadata.json" + +# Interactive patch selection; prints the selected local_path. +# Cancels silently (empty output). If fzf is missing: rows+hint to stderr, exit 1. +[no-cd] +_select_patch *prompt="patch": + #!/usr/bin/env fish + if not command -v fzf >/dev/null 2>&1 + just cross _list_patches "fzf is not installed, cd into a patched directory first or pass a path. Patches, columns local_path TAB worktree" >&2 + exit 1 + end + set -l row (just cross _list_patches | fzf --height 40% --select-1 --exit-0 --prompt "Select {{prompt}}> ") + test -z "$row"; and exit 0 + set -l cols (string split \t -- $row) + echo "$cols[1]" + # Initialize a new project with Crossfile [no-cd] init: @@ -248,15 +284,16 @@ use name url: check-deps [no-cd] remove path: check-deps #!/usr/bin/env fish - set l_path "{{path}}" + set l_path (path normalize "{{path}}") pushd "{{REPO_DIR}}" if not test -f {{METADATA}} just cross _log error "No metadata found." exit 1 end - set entry (jq -r --arg lp "$l_path" '.patches[] | select(.local_path == $lp)' {{METADATA}}) + set entry (jq -r --arg lp "$l_path" '.patches[] | select((.local_path | ltrimstr("./")) == $lp)' {{METADATA}}) if test -z "$entry" + just cross _list_patches "No patch detected, available patches, columns local_path TAB worktree" just cross _log error "Patch not found for path: $l_path" exit 1 end @@ -282,7 +319,7 @@ remove path: check-deps for f in $fields test "$f" = "patch" && set is_patch true end - if test "$is_patch" = true -a (count $fields) -gt 0 -a "$fields[-1]" = "$l_path" + if test "$is_patch" = true -a (count $fields) -gt 0 -a (path normalize "$fields[-1]") = "$l_path" continue # skip this line end echo "$line" >> "$tmp" @@ -293,7 +330,7 @@ remove path: check-deps # 3. Update metadata just cross _log info "Updating metadata..." set tmp_meta (mktemp) - jq --arg lp "$l_path" '.patches |= map(select(.local_path != $lp))' {{METADATA}} > "$tmp_meta" + jq --arg lp "$l_path" '.patches |= map(select((.local_path | ltrimstr("./")) != $lp))' {{METADATA}} > "$tmp_meta" mv "$tmp_meta" {{METADATA}} # 4. Remove local directory (with root guard) @@ -409,7 +446,7 @@ patch remote_spec local_path="": check-deps set remote $parts[1] set remote_path $parts[2] case '*' - just cross _log error "Error: Invalid format Use remote[:branch]:remote_path [local_path]" + just cross _log error "Error: Invalid format. Use remote[:branch]:remote_path LOCAL_PATH" exit 1 end @@ -419,16 +456,18 @@ patch remote_spec local_path="": check-deps set l_path "{{local_path}}" if test -z "$l_path" -a "$r_path" = "." - just cross _log error "Error: local_path is required when patching whole repo (path is '.')" + just cross _log error "Error: local_path is required when patching whole repo, path is '.'" exit 1 end test -n "$l_path"; or set l_path "$r_path" + # Normalize the local path so "./mxc2" is stored/matched as "mxc2" + set l_path (path normalize "$l_path") pushd "{{REPO_DIR}}" # validate remote if not git remote show $remote |grep -vq "^$remote\$" - just cross _log error "Error: Remote $remote not found. Run: just use $remote " + just cross _log error "Error: Remote $remote not found. Run: just cross use $remote URL" exit 1 end @@ -504,14 +543,16 @@ patch remote_spec local_path="": check-deps [no-cd] @check-initialized: cd {{REPO_DIR}} && test -d {{CROSSDIR}}/worktrees && test -f {{METADATA}} \ - || { just cross _log warn "No patches to update"; exit 0; } + || { just cross _log warn "No patches to update" >&2; exit 0; } # Update Crossfile-managed patches from upstream. Local edits are preserved and # left for manual review against the refreshed sparse worktree. [no-cd] _update_patch spec local_path: #!/usr/bin/env fish - if test "{{local_path}}" = "." + # Normalize the local path so "./mxc2" in Crossfile matches "mxc2" in metadata + set l_path (path normalize "{{local_path}}") + if test "$l_path" = "." just cross _log error "Updating a repository-root patch is not supported safely yet." exit 1 end @@ -520,13 +561,13 @@ _update_patch spec local_path: set remote $fields[1] set remote_path (string trim -c '/' -- $fields[-1]) test -n "$remote_path"; or set remote_path "." - set entry (jq -c --arg lp "{{local_path}}" '.patches[]? | select(.local_path == $lp)' {{METADATA}} 2>/dev/null) + set entry (jq -c --arg lp "$l_path" '.patches[]? | select((.local_path | ltrimstr("./")) == $lp)' {{METADATA}} 2>/dev/null) if test -z "$entry" - if test -e "{{REPO_DIR}}/{{local_path}}" - just cross _log error "Local path already exists but is not registered; refusing to overwrite it: {{local_path}}" + if test -e "{{REPO_DIR}}/$l_path" + just cross _log error "Local path already exists but is not registered, refusing to overwrite it: $l_path" exit 1 end - just cross patch "{{spec}}" "{{local_path}}" + just cross patch "{{spec}}" "$l_path" exit $status end set wt (echo "$entry" | jq -r '.worktree') @@ -534,32 +575,35 @@ _update_patch spec local_path: set entry_remote (echo "$entry" | jq -r '.remote') set entry_remote_path (echo "$entry" | jq -r '.remote_path') if test "$remote" != "$entry_remote" -o "$remote_path" != "$entry_remote_path" - just cross _log error "Crossfile source changed for {{local_path}}; remove and patch it explicitly before updating." + just cross _log error "Crossfile source changed for $l_path, remove and patch it explicitly before updating." exit 1 end set spec_parts (string split ':' -- "{{spec}}") if test (count $spec_parts) -eq 3 -a "$spec_parts[2]" != "$branch" - just cross _log error "Crossfile branch changed for {{local_path}}; remove and patch it explicitly before updating." + just cross _log error "Crossfile branch changed for $l_path, remove and patch it explicitly before updating." exit 1 end - set local_abs "{{REPO_DIR}}/{{local_path}}" + set local_abs "{{REPO_DIR}}/$l_path" set wt_abs "{{REPO_DIR}}/$wt/$remote_path" + # Detect local edits with an rsync itemized dry-run (excludes .git, the + # worktree's pointer file never exists in the local copy). set local_changed false if test -d "$local_abs" - git diff --no-index --quiet -- "$wt_abs" "$local_abs" - set diff_status $status - if test $diff_status -eq 1 - set local_changed true - else if test $diff_status -gt 1 + set itemized (rsync -rlcn --delete --exclude=.git --itemize-changes "$wt_abs/" "$local_abs/") + set rsync_status $status + if test $rsync_status -ne 0 just cross _log error "Could not compare local path and worktree." exit 1 end + if test (count $itemized) -gt 0 + set local_changed true + end end git fetch $remote $branch; or exit 1 set fetched_commit (git rev-parse FETCH_HEAD); or exit 1 set worktree_dirty (git -C "$wt" status --porcelain) if test -n "$worktree_dirty" - just cross _log error "Worktree has manual changes; leaving it untouched: $wt" + just cross _log error "Worktree has manual changes, leaving it untouched: $wt" exit 1 end git -C "$wt" merge --ff-only "$fetched_commit"; or begin @@ -567,11 +611,7 @@ _update_patch spec local_path: exit 1 end if test "$local_changed" = "true" - just cross _log warn "Local edits detected; preserving $local_abs. Compare manually:" - set tool (git config --get cross.diffTool 2>/dev/null) - test -n "$tool"; or set tool 'vim "+DirDiff"' - printf ' git cross compare "%s"\n' "{{local_path}}" - printf ' %s "%s" "%s"\n' "$tool" "$wt_abs" "$local_abs" + just cross _log warn "'$l_path' differs from upstream; local copy preserved. Compare with: git cross diff $l_path" exit 0 end mkdir -p "$local_abs" @@ -619,13 +659,18 @@ update path="": check-deps set local_path $fields[3] end test -n "$local_path"; or set local_path "." - if test -n "{{path}}" -a "$local_path" != "{{path}}" - continue + # Normalize so "./mxc2" and "mxc2" identify the same patch + set local_path (path normalize "$local_path") + if test -n "{{path}}" + set filter_path (path normalize "{{path}}") + if test "$local_path" != "$filter_path" + continue + end end just cross _update_patch $fields[2] $local_path; or exit 1 set updates (math $updates + 1) else - just cross _log error "Unsupported Crossfile command: $line (update supports use and patch only)" + just cross _log error "Unsupported Crossfile command: $line. update supports use and patch only" exit 1 end end < "{{REPO_DIR}}/Crossfile" @@ -662,15 +707,34 @@ diff path="": check-initialized popd >/dev/null end - # Query metadata.json - just cross _resolve_context2 "$resolved_path" | source \ - || { just cross _log error "Error: Could not resolve metadata for '$resolved_path'."; exit 1; } + # Resolve metadata: explicit path, CWD auto-detect, then fzf selection. + # An empty resolution means either no path/target or no matching patch. + set -l ctx (just cross _resolve_context2 "$resolved_path" 2>/dev/null) + if test (count $ctx) -eq 0 + if test -z "$resolved_path" + if not command -v fzf >/dev/null 2>&1 + just cross _list_patches "fzf is not installed, cd into a patched directory first or pass a path. Patches, columns local_path TAB worktree" + exit 1 + end + set -l sel (just cross _select_patch patch) + test -z "$sel"; and exit 0 + set resolved_path "$sel" + set ctx (just cross _resolve_context2 "$sel" 2>/dev/null) + end + if test (count $ctx) -eq 0 + just cross _list_patches "No patch detected, available patches, columns local_path TAB worktree" + exit 1 + end + end + printf '%s\n' $ctx | source pushd "{{REPO_DIR}}" if test -d $worktree set overrides (just cross _crossignore_overrides "{{REPO_DIR}}/$local_path") if test -z "$overrides[1]" - git diff --no-index $worktree/$remote_path $local_path || true + # Exclude .git (worktree pointer file has no local counterpart) while + # keeping real content diffs and the difference exit status. + git diff --no-index $worktree/$remote_path $local_path -- ':(exclude).git' ':(glob)**' || true else for override in $overrides printf 'git diff --no-index "%s" "%s"\n' "{{REPO_DIR}}/$worktree/$remote_path/$override" "{{REPO_DIR}}/$local_path/$override" @@ -686,140 +750,191 @@ diff path="": check-initialized [no-cd] compare path="": check-initialized #!/usr/bin/env fish - just cross _resolve_context2 "{{path}}" | source \ - || { just cross _log error "Provide a patch path or run inside a patch directory."; exit 1; } + # cross.diffTool may contain {left}/{right} placeholders (repo-relative paths); + # without placeholders the paths are appended as arguments (legacy form). + # Resolve metadata: explicit path, CWD auto-detect, then fzf selection + set -l ctx (just cross _resolve_context2 "{{path}}" 2>/dev/null) + if test (count $ctx) -eq 0 + if test -z "{{path}}" + if not command -v fzf >/dev/null 2>&1 + just cross _list_patches "fzf is not installed, cd into a patched directory first or pass a path. Patches, columns local_path TAB worktree" + exit 1 + end + set -l sel (just cross _select_patch patch) + test -z "$sel"; and exit 0 + set ctx (just cross _resolve_context2 "$sel" 2>/dev/null) + end + if test (count $ctx) -eq 0 + just cross _list_patches "No patch detected, available patches, columns local_path TAB worktree" + exit 1 + end + end + printf '%s\n' $ctx | source + set tool (git config --get cross.diffTool 2>/dev/null) - test -n "$tool"; or set tool 'vim "+DirDiff"' - set worktree_path "{{REPO_DIR}}/$worktree/$remote_path" - set local_path_abs "{{REPO_DIR}}/$local_path" - bash -c "$tool \"\$1\" \"\$2\"" cross-compare "$worktree_path" "$local_path_abs" + test -n "$tool"; or set tool "vim \"+DirDiffIgnore='.git' DirDiff {left} {right}\"" + set left "$worktree/$remote_path" + set right "$local_path" + if string match -q "*{left}*" -- $tool; or string match -q "*{right}*" -- $tool + set cmd (string replace -a '{right}' "$right" "$tool") + set cmd (string replace -a '{left}' "$left" "$cmd") + pushd "{{REPO_DIR}}" >/dev/null + bash -c "$cmd" + popd >/dev/null + else + bash -c "$tool \"\$1\" \"\$2\"" cross-compare "{{REPO_DIR}}/$left" "{{REPO_DIR}}/$right" + end -# AICONTEXT: "list" lists all patches in local repo, by reading Crossfile and `git worktree list` under .git/cross/worktrees. The listing shall be combined with status of each WT and git status of local_path. The logic can be take from "status" implementation. -# List all patches +# Alias for: compare [no-cd] -list: check-deps +cmp path="": (compare path) + +# AICONTEXT: "list" lists remotes used by patches and all patches from .cross/metadata.json +# (worktrees live under .cross/worktrees/). raw: TSV rows with no banners/borders; +# no_header: omit header lines. Output order is fixed: remotes first, then patches. +# Usage: list [raw] [no_header] (e.g. `just cross list 1`, `just cross list raw=1 no_header=1`) +# List all remotes and patches +[no-cd] +list raw="" no_header="": check-deps #!/usr/bin/env fish + # just binds recipe parameters positionally; tolerate both `1` and `raw=1` tokens + set -l raw_arg "{{raw}}" + set -l header_arg "{{no_header}}" + set -l show_raw false + set -l show_header true + if test -n "$raw_arg" + if string match -q 'no_header=*' -- $raw_arg + set header_arg $raw_arg + else + set show_raw true + end + end + test -n "$header_arg"; and set show_header false pushd "{{REPO_DIR}}" >/dev/null if test -f .cross/metadata.json # Get unique remotes used by patches set used_remotes (jq -r '.patches[].remote' .cross/metadata.json | sort -u) - + if test (count $used_remotes) -gt 0 - just cross _log info "Configured Remotes:" - printf "%-20s %s\n" "NAME" "URL" - printf "%s\n" (string repeat -n 70 "-") - - # Build grep pattern for used remotes - set pattern (string join "|" $used_remotes) - - # Get remotes, filter by used, deduplicate fetch/push - git remote -v | grep -E "^($pattern)\s" | awk ' - { - name=$1; url=$2; type=$3 - if (!(name in seen)) { - seen[name] = url - types[name] = type - } else if (seen[name] != url) { - # Different fetch/push URLs - printf "%-20s %s\n", name, seen[name] " " types[name] - printf "%-20s %s\n", name, url " " type - delete seen[name] - } - } - END { - for (name in seen) { - printf "%-20s %s\n", name, seen[name] - } - } - ' - echo "" + if $show_raw + if $show_header + printf 'REMOTE_NAME\tREMOTE_URL\n' + end + else + just cross _log info "Configured Remotes:" + if $show_header + printf "%-20s %s\n" "REMOTE NAME" "REMOTE URL" + printf "%s\n" (string repeat -n 70 "-") + end + end + + # Deterministic order: remotes sorted, fetch URL first, then push-only URLs + for name in $used_remotes + set -l urls (git remote get-url --all $name 2>/dev/null) + for url in (git remote get-url --push --all $name 2>/dev/null) + contains $url $urls; or set urls $urls $url + end + for url in $urls + if $show_raw + printf '%s\t%s\n' $name $url + else + printf "%-20s %s\n" $name $url + end + end + end + + if not $show_raw + echo "" + end end end if not test -f Crossfile - just cross _log warn "No patches found (Crossfile missing)." + if $show_raw + echo "No patches found, Crossfile missing." >&2 + else + just cross _log warn "No patches found, Crossfile missing." + end popd >/dev/null exit 0 end - - just cross _log info "Configured Patches:" - printf "%-20s %-30s %-20s\n" "REMOTE" "REMOTE PATH" "LOCAL PATH" - printf "%s\n" (string repeat -n 70 "-") - + + if $show_raw + if $show_header + printf 'REMOTE\tREMOTE_PATH\tLOCAL_PATH\tWORKTREE\tBRANCH\n' + end + else + just cross _log info "Configured Patches:" + if $show_header + printf "%-20s %-30s %-20s %-26s %-15s\n" "REMOTE" "REMOTE PATH" "LOCAL PATH" "WORKTREE" "BRANCH" + printf "%s\n" (string repeat -n 70 "-") + end + end + if test -f .cross/metadata.json - jq -r '.patches[] | "\(.remote) \(.remote_path) \(.local_path)"' .cross/metadata.json | while read -l remote rpath lpath - printf "%-20s %-30s %-20s\n" $remote $rpath $lpath + set -l patch_rows (jq -r '.patches[] | [.remote, .remote_path, .local_path, .worktree, .branch] | @tsv' .cross/metadata.json | sort) + for row in $patch_rows + if $show_raw + printf '%s\n' $row + else + set -l cols (string split \t -- $row) + printf "%-20s %-30s %-20s %-26s %-15s\n" $cols[1] $cols[2] $cols[3] $cols[4] $cols[5] + end end + else if $show_raw + echo "No patches found. Run: just cross patch REMOTE_PATH LOCAL_PATH" >&2 else - just cross _log info "No patches found. Run 'just cross patch ' to start." + just cross _log info "No patches found. Run: just cross patch REMOTE_PATH LOCAL_PATH" end popd >/dev/null # wt wrapper [no-cd] worktree path="": - just cross cd "{{path}}" dry="{{dry}}" - -# Internal: Copy text to clipboard (cross-platform) -[no-cd] -_copy_to_clipboard text: - #!/usr/bin/env bash - if command -v pbcopy >/dev/null 2>&1; then - # macOS - echo "{{text}}" | pbcopy - elif command -v xclip >/dev/null 2>&1; then - # Linux with xclip - echo "{{text}}" | xclip -selection clipboard - elif command -v xsel >/dev/null 2>&1; then - # Linux with xsel - echo "{{text}}" | xsel --clipboard --input - else - echo "Error: No clipboard tool found (pbcopy/xclip/xsel)" - exit 1 - fi + just cross wt "{{path}}" -# Internal: Open shell in target directory -# target: "local_path" or "worktree" -# path: must be provided (non-empty) -[no-cd] -_open_shell target path: - #!/usr/bin/env fish - just cross _resolve_context2 "{{path}}" | source || exit 1 - set -l dir (test "{{target}}" = "local_path" && echo $local_path || echo $worktree) - cd {{REPO_DIR}}/$dir && exec $SHELL - -# Go to worktree directory (for working with git history) -# With path: opens subshell -# Without path: uses fzf selection and copies to clipboard +# Print a patch worktree to cd into (use: cd (just cross wt [path])) [no-cd] wt path="": #!/usr/bin/env fish if test -n "{{path}}" - just cross _open_shell worktree "{{path}}" + set -l ctx (just cross _resolve_context2 "{{path}}" 2>/dev/null) + if test (count $ctx) -eq 0 + just cross _list_patches "No patch detected, available patches, columns local_path TAB worktree" + exit 1 + end + printf '%s\n' $ctx | source + echo "{{REPO_DIR}}/$worktree" + else if not command -v fzf >/dev/null 2>&1 + just cross _list_patches "fzf is not installed, cd manually. Destinations, columns local_path TAB worktree" + exit 1 else - set -l selected (just cross list | tail -n +3 | fzf --height 40% --select-1 --exit-0 --prompt "Select patch (wt)> " 2>/dev/null | awk '{print $NF}') - test -z "$selected" && exit 0 - just cross _resolve_context2 "$selected" | source || exit 1 - set -l rel_dir (realpath -m --relative-to=$PWD {{REPO_DIR}}/$worktree) - just cross _copy_to_clipboard $rel_dir - just cross _log success "Path copied: $rel_dir" + set -l row (just cross _list_patches | fzf --height 40% --select-1 --exit-0 --prompt "Select patch (wt)> ") + test -z "$row"; and exit 0 + set -l cols (string split \t -- $row) + echo "{{REPO_DIR}}/$cols[2]" end -# Go to local_path directory (for editing patched files) -# With path: opens subshell -# Without path: uses fzf selection and copies to clipboard +# Print a patch local_path to cd into (use: cd (just cross cd [path])) [no-cd] cd path="": #!/usr/bin/env fish if test -n "{{path}}" - just cross _open_shell local_path "{{path}}" + set -l ctx (just cross _resolve_context2 "{{path}}" 2>/dev/null) + if test (count $ctx) -eq 0 + just cross _list_patches "No patch detected, available patches, columns local_path TAB worktree" + exit 1 + end + printf '%s\n' $ctx | source + echo "{{REPO_DIR}}/$local_path" + else if not command -v fzf >/dev/null 2>&1 + just cross _list_patches "fzf is not installed, cd manually. Destinations, columns local_path TAB worktree" + exit 1 else - set -l selected (just cross list | tail -n +3 | fzf --height 40% --select-1 --exit-0 --prompt "Select patch (cd)> " 2>/dev/null | awk '{print $NF}') - test -z "$selected" && exit 0 - just cross _resolve_context2 "$selected" | source || exit 1 - set -l rel_dir (realpath -m --relative-to=$PWD {{REPO_DIR}}/$local_path) - just cross _copy_to_clipboard $rel_dir - just cross _log success "Path copied: $rel_dir" + set -l row (just cross _list_patches | fzf --height 40% --select-1 --exit-0 --prompt "Select patch (cd)> ") + test -z "$row"; and exit 0 + set -l cols (string split \t -- $row) + echo "{{REPO_DIR}}/$cols[1]" end @@ -848,7 +963,10 @@ status: check-deps set overrides (just cross _crossignore_overrides "{{REPO_DIR}}/$local_path") if test (count $overrides) -gt 0 set diff_stat "Override" - else if not git diff --no-index --quiet $wt/$rpath $local_path 2>/dev/null + else if not test -d $local_path + set diff_stat "Modified" + else if test (rsync -rlcn --delete --exclude=.git --itemize-changes "$wt/$rpath/" "$local_path/" 2>/dev/null | count) -gt 0 + # .git excluded: the worktree pointer file has no local counterpart set diff_stat "Modified" end diff --git a/README.md b/README.md index 2463501d6..d5563a3b0 100644 --- a/README.md +++ b/README.md @@ -146,17 +146,18 @@ Your own repository stores the final combined result, including local overlay fi When you want to contribute upstream-managed changes back: ```bash -git cross wt vendor/app -git config --global cross.diffTool 'vim "+DirDiff"' +cd "$(git cross wt vendor/app)" # or use the crosswt wrapper git cross compare vendor/app ``` Recommended pattern: -1. Open the sparse worktree with `git cross wt vendor/app`. -2. Compare it with the local patch using `git cross compare vendor/app` or your own directory diff tool. +1. Enter the sparse worktree with `git cross wt vendor/app` (or `crosswt vendor/app`). +2. Compare it with the local patch using `git cross compare vendor/app`, or print a console diff with `git cross diff vendor/app`. 3. Manually copy desired changes into the worktree, then commit and push with Git. +`compare` uses the command configured in `cross.diffTool`; see [Directory Diff Tool](#directory-diff-tool-crossdifftool). + This lets your main repo keep its local opinionated result while the upstream contribution stays focused. ## Tutorials @@ -170,6 +171,43 @@ This lets your main repo keep its local opinionated result while the upstream co ## Commands +`git cross --help` groups commands by intent: + +```text +Repository: + compare Open the configured directory comparison tool for a patch + init Create an empty Crossfile + list Show all configured patches and remotes + status Show patch status + update Update patches from Crossfile declarations + +Inspect & Navigate: + cd Print a patch local_path to cd into + diff Show changes between local and upstream + wt Print a patch worktree to cd into + +Patch Lifecycle: + patch Create a patch from a remote path + prune Remove a remote and all its patches + remove Remove a patch + use Add a remote repository +``` + +`compare` also answers to the short alias `git cross cmp`. + +Running `git cross` with no subcommand does not print help. It prints one row +per configured patch to stdout, `local_pathworktree`, and a hint to stderr: + +```text +$ git cross +Patches (local_path worktree). See: git cross --help +vendor/app .cross/worktrees/app_1a2b3c4d +``` + +Rows are the machine-readable listing used throughout the tool: hints and +warnings go to stderr, so `git cross 2>/dev/null | cut -f1` yields local paths. +Use `git cross -h` or `git cross --help` for the grouped help shown above. + ### `use` ```bash @@ -192,15 +230,26 @@ Create or reuse a hidden worktree, sparse-check out the upstream path, and sync git cross update [path] ``` -Read `Crossfile`, fetch upstream updates, and update each patch. If the local copy differs from the previously installed upstream content, `update` preserves local files, advances the sparse worktree, and prints a comparison command for manual review. Configure a directory diff tool with `git config --global cross.diffTool 'vim "+DirDiff"'`. +Read `Crossfile`, fetch upstream updates, and update each patch. + +If the local copy still matches the previously installed upstream content, `update` refreshes it in place. If the local copy has edits, `update` preserves it, advances the sparse worktree to the new upstream state, and prints a single warning: + +```text +'vendor/docs' differs from upstream; local copy preserved. Compare with: git cross diff vendor/docs +``` + +Review the differences and merge manually. Whole-repository patches (`remote:.` and `remote:/`) take part in this check correctly: the worktree's `.git` pointer file is not counted as a local edit, so a clean whole-repo patch is updated instead of warned about. ### `compare` ```bash git cross compare [path] +git cross cmp [path] ``` -Open the configured directory comparison tool for a local patch and its sparse worktree. +Open the configured directory comparison tool between one patch's local copy and its sparse worktree. + +`compare` works on exactly one patch. With no path argument it resolves the patch the same way `diff` does: CWD auto-detect first, then an `fzf` selection. If no patch can be resolved (including when `fzf` is missing), it prints the available patches as rows, exits with status 1, and does not dump a usage block. ### `diff` @@ -208,7 +257,81 @@ Open the configured directory comparison tool for a local patch and its sparse w git cross diff [path] ``` -Compare local files with the hidden worktree copy. +Print a unified diff between local files and the hidden worktree copy on the console. + +With no path argument, the patch is resolved in this order: + +1. **CWD auto-detect** — if the current directory is inside a patch's `local_path`, that patch is used (and an auto-detect note is printed). +2. **`fzf` selection** — otherwise, if `fzf` is installed, pick a patch interactively. +3. **Rows + hint** — if `fzf` is not installed, print the available patch rows plus a hint to `cd` into a patch directory or pass a path, and exit 1. + +Cancelling the `fzf` selection (Esc) exits 0 without doing anything. + +**Behavior change:** `diff` with no path from outside a patch directory used to dump diffs for all patches. It is now interactive. + +### Choosing between `diff` and `compare` + +Both commands view the same pair of directories — the local copy and the sparse worktree — but they target different workflows: + +| | `diff` | `compare` | +|---|---|---| +| Output | unified diff on stdout | the tool from `cross.diffTool` | +| Scope | one patch (from a path, CWD, or `fzf`) | exactly one patch (from a path, CWD, or `fzf`) | +| Unresolved patch | rows + exit 1 | rows + exit 1 | +| Typical use | quick review, scripting, CI | side-by-side editing in an editor | + +`.crossignore` overrides are still review signals: `status` shows `Override`, and `diff` prints manual `git diff --no-index ...` commands for the override paths instead of a full diff. + +### `list` + +```bash +git cross list [--raw] [--no-header] +``` + +Show configured remotes and patches. Default output is a table with +`Configured Remotes:` / `Configured Patches:` banners and descriptive column +headers. + +`--raw` switches to machine-readable output: tab-separated rows, no table +borders, and no banners. `--no-header` omits the header line in both table and +raw mode. In raw mode the section order is fixed — all remotes first, then all +patches: + +```text +REMOTE_NAME REMOTE_URL +REMOTE REMOTE_PATH LOCAL_PATH WORKTREE BRANCH +``` + +Each remote with a different fetch and push URL produces one row per URL; both +rows stay in the two-column schema, so the URL field is never decorated with +`(fetch)` / `(push)` suffixes. Remote rows are sorted by name. Header rows are +themselves tab-separated, so use `--no-header` in pipelines. + +Parsing examples: + +```bash +# Local paths only (patch rows have 5 fields, remote rows have 2) +git cross list --raw --no-header | awk -F'\t' 'NF == 5 { print $3 }' + +# Worktree paths +git cross list --raw --no-header | awk -F'\t' 'NF == 5 { print $4 }' + +# ":" for every patch +git cross list --raw --no-header | awk -F'\t' 'NF == 5 { print $1 ":" $5 }' + +# Remote URLs +git cross list --raw --no-header | awk -F'\t' 'NF == 2 { print $2 }' +``` + +A plain `cut` works on the patch rows, but leaves blank lines for the +two-column remote rows: + +```bash +git cross list --raw --no-header | cut -f3 | sed '/^$/d' +``` + +When nothing is configured, raw mode writes the empty-state message to stderr +so stdout stays a clean pipe. ### `status` @@ -234,6 +357,105 @@ git cross prune [remote] Remove unused remotes, stale worktrees, or all patches for one remote. +### `cd` and `wt` + +```bash +git cross cd [path] +git cross wt [path] +``` + +Print the absolute destination path for one patch: `cd` targets the local copy +(`local_path`), `wt` targets the hidden sparse worktree. + +The path is the only thing written to stdout; hints and errors go to stderr. +These commands do not start a subshell and do not copy anything to the +clipboard; they print a path for your shell to `cd` into: + +```bash +cd "$(git cross cd vendor/app)" # local copy +cd "$(git cross wt vendor/app)" # sparse worktree +``` + +For convenience, add wrappers to your shell configuration. + +bash / zsh: + +```bash +crosscd() { cd "$(git cross cd "$@")"; } +crosswt() { cd "$(git cross wt "$@")"; } +``` + +fish: + +```fish +function crosscd; cd (git cross cd $argv); end +function crosswt; cd (git cross wt $argv); end +``` + +A child process cannot change the working directory of the shell that started +it, so the tool cannot `cd` for you. The wrapper does the `cd` in your shell +using the path the tool prints. Keeping stdout path-only also makes the output +composable in scripts (`dir=$(git cross cd vendor/app)`) and editor +integrations. + +With an explicit path the patch is resolved directly. Without one, `fzf` is +used to select a patch. If `fzf` is not installed, the command prints the +available patch rows plus a hint to `cd` manually, and exits 1. + +## Directory Diff Tool (`cross.diffTool`) + +`compare` uses the command configured in `cross.diffTool`. Configure it +globally or per repository: + +```bash +git config --global cross.diffTool '' +``` + +### Template form (current) + +If the command contains `{left}` or `{right}`, both placeholders are replaced +before the command is run: + +- `{left}` — the patch's path inside the sparse worktree +- `{right}` — the patch's local copy + +The substituted paths are **repo-relative**, and the command runs with the +repository root as its working directory. The default, used when +`cross.diffTool` is unset, is: + +```text +vim "+DirDiffIgnore='.git' DirDiff {left} {right}" +``` + +To make it explicit: + +```bash +git config --global cross.diffTool "vim \"+DirDiffIgnore='.git' DirDiff {left} {right}\"" +``` + +A custom ignore list passes DirDiff a comma-separated list of names to skip: + +```bash +git config --global cross.diffTool "nvim \"+DirDiffIgnore='ves.io,f5fed.com,volterra.us' DirDiff {left} {right}\"" +``` + +In this form the paths are part of the vim `+` command string, which is where +DirDiff reads them. The repository default already ignores `.git`, so the +worktree's `.git` pointer file never appears in the comparison. + +### Legacy append form (deprecated) + +A command without `{left}` / `{right}` keeps the old behavior: the two absolute +paths are appended as trailing arguments. + +```bash +# Deprecated: paths become vim file arguments, not DirDiff arguments. +git config --global cross.diffTool 'vim "+DirDiff"' +``` + +This form is deprecated because it does not invoke DirDiff correctly. Migrate +to the template form above. + ## Safety Notes - `remove` and `prune` now guard against deleting repo root contents when a patch targets `.` diff --git a/src-go/main.go b/src-go/main.go index 09e6bc224..d04b2974e 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -5,12 +5,12 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "os" "os/exec" "path/filepath" "sort" - "strconv" "strings" "github.com/fatih/color" @@ -274,28 +274,38 @@ func logWarn(msg string) { fmt.Println(msg) } +const defaultDiffTool = `vim "+DirDiffIgnore='.git' DirDiff {left} {right}"` + func diffTool() string { if out, err := exec.Command("git", "config", "--get", "cross.diffTool").Output(); err == nil { if tool := strings.TrimSpace(string(out)); tool != "" { return tool } } - return `vim "+DirDiff"` -} - -func printDiffCommand(left, right string) { - tool := diffTool() - fmt.Printf(" git config --global cross.diffTool %s\n", strconv.Quote(tool)) - fmt.Printf(" %s %q %q\n", tool, left, right) + return defaultDiffTool } -func runDiffTool(left, right string) error { +// runDiffTool executes the configured diff tool. If the tool string contains +// {left}/{right} placeholders, they are substituted with repo-relative paths +// and the command runs with cwd = repo root. Legacy configs without +// placeholders keep the old behavior (paths appended as arguments). +func runDiffTool(root, left, right string) error { tool := diffTool() - cmd := exec.Command("bash", "-c", tool+` "$@"`, "cross-diff", left, right) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - return cmd.Run() + relLeft, errL := filepath.Rel(root, left) + relRight, errR := filepath.Rel(root, right) + if errL != nil || errR != nil { + relLeft, relRight = left, right + } + var c *exec.Cmd + if strings.Contains(tool, "{left}") || strings.Contains(tool, "{right}") { + cmdline := strings.NewReplacer("{left}", relLeft, "{right}", relRight).Replace(tool) + c = exec.Command("bash", "-c", cmdline, "cross-diff") + } else { + c = exec.Command("bash", "-c", tool+` "$@"`, "cross-diff", left, right) + } + c.Dir = root + c.Stdin, c.Stdout, c.Stderr = os.Stdin, os.Stdout, os.Stderr + return c.Run() } func localDiffersFromWorktree(localPath, worktreePath string) (bool, error) { @@ -312,6 +322,31 @@ func logError(msg string) { fmt.Println(msg) } +// printPatchRows prints one row per patch: local_path worktree. +// Rows go to stdout (parseable via cut -f1); hint goes to stderr, so +// `git cross compare 2>/dev/null | cut -f1` yields local paths. +func printPatchRows(hint string) error { + meta, err := loadMetadata() + if err != nil { + return err + } + if len(meta.Patches) == 0 { + logInfo("No patches configured.") + return nil + } + if hint != "" { + fmt.Fprintln(os.Stderr, hint) + } + for _, p := range meta.Patches { + fmt.Printf("%s\t%s\n", p.LocalPath, p.Worktree) + } + return nil +} + +// errPatchNotFound is returned after rows were already printed; commands +// that use it set SilenceErrors+SilenceUsage so nothing extra is printed. +var errPatchNotFound = errors.New("patch not found") + func loadMetadata() (Metadata, error) { var meta Metadata path, err := getMetadataPath() @@ -326,7 +361,15 @@ func loadMetadata() (Metadata, error) { return meta, err } err = json.Unmarshal(data, &meta) - return meta, err + if err != nil { + return meta, err + } + // Self-heal legacy local paths (e.g. "./mxc2" -> "mxc2") so the next + // save rewrites normalized paths. + for i := range meta.Patches { + meta.Patches[i].LocalPath = filepath.ToSlash(filepath.Clean(meta.Patches[i].LocalPath)) + } + return meta, nil } func saveMetadata(meta Metadata) error { @@ -423,18 +466,19 @@ func runSync(src, dst string) error { return nil } +// directoriesDiffer reports whether two directory trees differ, ignoring +// .git (the worktree's pointer file never exists in the local copy). +// -c: checksum compare; no -t so time-only changes don't produce lines. +// --delete: files existing only on the right side are reported. func directoriesDiffer(left, right string) (bool, error) { - cmd := exec.Command("git", "diff", "--no-index", "--quiet", "--", left, right) - err := cmd.Run() - if err == nil { - return false, nil - } - if exitErr, ok := err.(*exec.ExitError); ok { - if exitErr.ExitCode() == 1 { - return true, nil - } + c := exec.Command("rsync", "-rlcn", "--delete", "--exclude=.git", + "--itemize-changes", + left+string(os.PathSeparator), right+string(os.PathSeparator)) + out, err := c.Output() + if err != nil { + return false, fmt.Errorf("rsync compare %s vs %s: %w\n%s", left, right, err, out) } - return false, fmt.Errorf("compare %s and %s: %w", left, right, err) + return strings.TrimSpace(string(out)) != "", nil } func crossfileCommands(path string) ([][]string, error) { @@ -534,7 +578,7 @@ func removeFromCrossfile(localPath string) { break } } - if isPatchLine && len(fields) > 0 && fields[len(fields)-1] == localPath { + if isPatchLine && len(fields) > 0 && filepath.ToSlash(filepath.Clean(fields[len(fields)-1])) == localPath { continue // skip this line } newLines = append(newLines, line) @@ -617,11 +661,21 @@ func findPatchForPath(meta Metadata, rel string) *Patch { if rel == "" { return nil } + rel = strings.Trim(filepath.ToSlash(filepath.Clean(rel)), "/") + if rel == "" { + return nil + } var selected *Patch longest := -1 for i := range meta.Patches { - lp := strings.Trim(meta.Patches[i].LocalPath, "/") + raw := strings.TrimSpace(meta.Patches[i].LocalPath) + if raw == "" { + continue + } + // Clean stored paths defensively so legacy metadata (e.g. "./mxc2") + // still matches; this heals without a migration step. + lp := strings.Trim(filepath.ToSlash(filepath.Clean(raw)), "/") if lp == "" { continue } @@ -683,11 +737,9 @@ func resolvePathToRepoRelative(inputPath string) (string, error) { absPath = filepath.Clean(absPath) // Evaluate symlinks to handle /tmp -> /private/tmp on macOS - absPath, err = filepath.EvalSymlinks(absPath) - if err != nil { - // If EvalSymlinks fails (path doesn't exist), continue with cleaned path - // This allows diff to work even if path doesn't exist yet - absPath = filepath.Clean(absPath) + // If the path doesn't exist yet, keep the cleaned absolute path. + if resolved, err := filepath.EvalSymlinks(absPath); err == nil { + absPath = resolved } // Also evaluate symlinks for root to ensure consistent comparison @@ -747,13 +799,9 @@ func selectPatchInteractive(meta *Metadata) (*Patch, error) { ) cmd.Stdin = strings.NewReader(b.String()) out, err := cmd.Output() - if err != nil { - return nil, err - } - selection := strings.TrimSpace(string(out)) - if selection == "" { - return nil, nil + if err != nil || selection == "" { + return nil, nil // user cancelled (ESC / empty) } parts := strings.Split(selection, "\t") @@ -783,15 +831,44 @@ func selectPatchInteractive(meta *Metadata) (*Patch, error) { func main() { var dry string rootCmd := &cobra.Command{ - Use: "git-cross", - Version: "0.3.0", + Use: "git-cross", + Version: "0.3.0", + Short: "Manage vendored cross-repo patches (worktree + rsync)", + SilenceUsage: true, // no Usage dump on errors + RunE: func(cmd *cobra.Command, args []string) error { + return printPatchRows("Patches (local_path worktree). See: git cross --help") + }, + CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true}, } + rootCmd.AddGroup( + &cobra.Group{ID: "repo", Title: "Repository:"}, + &cobra.Group{ID: "inspect", Title: "Inspect & Navigate:"}, + &cobra.Group{ID: "patches", Title: "Patch Lifecycle:"}, + ) + // Group the builtin help command so no ungrouped visible command remains + // (Cobra otherwise renders it under "Additional Commands:"). + rootCmd.SetHelpCommand(&cobra.Command{ + Use: "help [command]", + Short: "Help about any command", + GroupID: "repo", + Run: func(c *cobra.Command, args []string) { + target, _, err := c.Root().Find(args) + if target == nil || err != nil { + c.Printf("Unknown help topic %q\n", args) + _ = c.Root().Usage() + return + } + target.InitDefaultHelpFlag() + _ = target.Help() + }, + }) rootCmd.PersistentFlags().StringVar(&dry, "dry", "", "Dry run command (e.g. echo)") useCmd := &cobra.Command{ - Use: "use [name] [url]", - Short: "Add a remote repository", - Args: cobra.ExactArgs(2), + Use: "use [name] [url]", + Short: "Add a remote repository", + GroupID: "patches", + Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { name, url := args[0], args[1] logInfo(fmt.Sprintf("Adding remote %s (%s)...", name, url)) @@ -834,9 +911,10 @@ func main() { } patchCmd := &cobra.Command{ - Use: "patch [spec] [local_path]", - Short: "Vendor a directory from a remote", - Args: cobra.MinimumNArgs(1), + Use: "patch [spec] [local_path]", + Short: "Vendor a directory from a remote", + GroupID: "patches", + Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { specInput := args[0] spec, err := parsePatchSpec(specInput) @@ -851,6 +929,7 @@ func main() { if localPath == "" { localPath = filepath.Base(spec.RemotePath) } + localPath = filepath.ToSlash(filepath.Clean(localPath)) // "./mxc2" -> "mxc2" repo, err := git.Open(".") if err != nil { @@ -1131,9 +1210,10 @@ func main() { } updateCmd := &cobra.Command{ - Use: "update [path]", - Short: "Update Crossfile patches from upstream", - Args: cobra.MaximumNArgs(1), + Use: "update [path]", + Short: "Update Crossfile patches from upstream", + GroupID: "repo", + Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { root, err := getRepoRoot() if err != nil { @@ -1313,8 +1393,8 @@ func main() { } updated++ if localChanged { - logWarn(fmt.Sprintf("Local edits detected; preserving %s. Compare the worktree and local copy manually:", localPath)) - printDiffCommand(upstreamAbs, localAbs) + logWarn(fmt.Sprintf("'%s' differs from upstream; local copy preserved. Compare with: git cross diff %s", + localPath, localPath)) continue } if err := os.MkdirAll(localAbs, 0o755); err != nil { @@ -1336,9 +1416,13 @@ func main() { } compareCmd := &cobra.Command{ - Use: "compare [path]", - Short: "Open the configured directory comparison tool for a patch", - Args: cobra.MaximumNArgs(1), + Use: "compare [path]", + Aliases: []string{"cmp"}, + Short: "Open the configured directory comparison tool for a patch", + GroupID: "repo", + Args: cobra.MaximumNArgs(1), + SilenceErrors: true, + SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { meta, err := loadMetadata() if err != nil { @@ -1358,168 +1442,125 @@ func main() { } } if patch == nil { - return fmt.Errorf("patch not found; provide a path or run from inside a patched directory") + selected, serr := selectPatchInteractive(&meta) + if serr != nil { // fzf missing + if rerr := printPatchRows("fzf is not installed; cd into a patched directory first or pass a path. Patches (local_path worktree):"); rerr != nil { + return rerr + } + return errPatchNotFound + } + if selected == nil { + return nil // cancelled + } + patch = selected } root, err := getRepoRoot() if err != nil { return err } - return runDiffTool(filepath.Join(root, patch.Worktree, patch.RemotePath), filepath.Join(root, patch.LocalPath)) + return runDiffTool(root, + filepath.Join(root, patch.Worktree, patch.RemotePath), + filepath.Join(root, patch.LocalPath)) }, } - // Helper: Copy text to clipboard (cross-platform) - copyToClipboard := func(text string) error { - var cmd *exec.Cmd - - // Detect platform and use appropriate command - if _, err := exec.LookPath("pbcopy"); err == nil { - // macOS - cmd = exec.Command("pbcopy") - } else if _, err := exec.LookPath("xclip"); err == nil { - // Linux with xclip - cmd = exec.Command("xclip", "-selection", "clipboard") - } else if _, err := exec.LookPath("xsel"); err == nil { - // Linux with xsel - cmd = exec.Command("xsel", "--clipboard", "--input") - } else { - return fmt.Errorf("no clipboard tool found (pbcopy/xclip/xsel)") - } - - cmd.Stdin = strings.NewReader(text) - return cmd.Run() - } - - // Helper: Get relative path from PWD to target - getRelativePath := func(targetPath string) string { - pwd, err := os.Getwd() - if err != nil { - return targetPath // fallback to absolute - } - relPath, err := filepath.Rel(pwd, targetPath) - if err != nil { - return targetPath // fallback to absolute - } - return relPath - } - - // Helper: Open shell in target directory (path must be provided) - openShellInDir := func(path string, targetType string) error { - meta, err := loadMetadata() - if err != nil { - return err - } - if len(meta.Patches) == 0 { - fmt.Println("No patches configured.") - return nil - } - - // Find patch for provided path - patch := findPatchForPath(meta, path) - if patch == nil { - for i := range meta.Patches { - if meta.Patches[i].LocalPath == path { - patch = &meta.Patches[i] - break - } - } - } - if patch == nil { - return fmt.Errorf("patch not found for path: %s", path) - } - - // Determine target directory - var targetDir string - if targetType == "worktree" { - targetDir = patch.Worktree - } else { - targetDir = patch.LocalPath - } - - if _, err := os.Stat(targetDir); os.IsNotExist(err) { - return fmt.Errorf("%s not found: %s", targetType, targetDir) - } - - // Open subshell - shell := os.Getenv("SHELL") - if shell == "" { - shell = "/bin/sh" - } - - if dry != "" { - fmt.Printf("%s cd %s\n", dry, targetDir) - fmt.Printf("%s exec %s\n", dry, shell) - return nil - } - - logInfo(fmt.Sprintf("Opening shell in %s", targetDir)) - c := exec.Command(shell) - c.Dir = targetDir - c.Stdin = os.Stdin - c.Stdout = os.Stdout - c.Stderr = os.Stderr - return c.Run() - } - - // Shared logic for cd/wt commands — only the target field differs + // Shared logic for cd/wt commands — only the target field differs. + // Prints the selected/resolved absolute path to stdout; the caller cds via + // `cd "$(git cross cd)"` (a child process cannot change the parent shell). makeDirCmd := func(use, short, long, target string) *cobra.Command { return &cobra.Command{ Use: use, Short: short, Long: long, + SilenceErrors: true, SilenceUsage: true, + GroupID: "inspect", RunE: func(cmd *cobra.Command, args []string) error { meta, err := loadMetadata() if err != nil { return err } if len(meta.Patches) == 0 { - fmt.Println("No patches configured.") + logInfo("No patches configured.") return nil } + var patch *Patch if len(args) > 0 { - return openShellInDir(strings.TrimSpace(args[0]), target) - } - selected, err := selectPatchInteractive(&meta) - if err != nil { - logInfo("fzf not available. Showing patch list; rerun with a path.") - table := tablewriter.NewWriter(os.Stdout) - table.Header("REMOTE", "REMOTE PATH", "LOCAL PATH") - for _, p := range meta.Patches { - table.Append(p.Remote, p.RemotePath, p.LocalPath) + arg := strings.TrimSpace(args[0]) + relPath, rerr := resolvePathToRepoRelative(arg) + if rerr != nil { + return rerr + } + patch = findPatchForPath(meta, relPath) + if patch == nil { + cleanArg := filepath.ToSlash(filepath.Clean(arg)) + for i := range meta.Patches { + if meta.Patches[i].LocalPath == cleanArg { + patch = &meta.Patches[i] + break + } + } + } + if patch == nil { + if err := printPatchRows("No patch detected; available patches (local_path worktree):"); err != nil { + return err + } + return errPatchNotFound + } + } else { + // No path: CWD auto-detect, then fzf, then rows+hint. + if detected, derr := findPatchForPathFromCWD(meta); derr == nil && detected != nil { + patch = detected + } else { + selected, err := selectPatchInteractive(&meta) + if err != nil { // fzf not available + if rerr := printPatchRows("fzf is not installed; cd manually, e.g. `cd ` or `cd `. Destinations (local_path worktree):"); rerr != nil { + return rerr + } + return errPatchNotFound + } + if selected == nil { + return nil // no selection made (ESC) + } + patch = selected } - table.Render() - return nil - } - if selected == nil { - logInfo("No selection made.") - return nil } - targetPath := selected.LocalPath + targetPath := patch.LocalPath if target == "worktree" { - targetPath = selected.Worktree + targetPath = patch.Worktree } - relPath := getRelativePath(targetPath) - if err := copyToClipboard(relPath); err != nil { - return fmt.Errorf("failed to copy to clipboard: %v", err) + root, err := getRepoRoot() + if err != nil { + return err } - logSuccess(fmt.Sprintf("Path copied to clipboard: %s", relPath)) + abs := filepath.Join(root, targetPath) + if _, err := os.Stat(abs); os.IsNotExist(err) { + return fmt.Errorf("%s not found: %s", target, targetPath) + } + if dry != "" { + fmt.Printf("%s cd %s\n", dry, abs) + return nil + } + fmt.Println(abs) // stdout contract: path only return nil }, } } cdCmd := makeDirCmd("cd [path]", - "Open a shell in the patch local_path (for editing files)", - "Open a shell in the patch local_path (for editing files).\n\nWith path: opens subshell in the specified local_path directory.\nWithout path: uses fzf to select a patch, then copies the path to clipboard.", + "Print a patch local_path to cd into (use: cd \"$(git cross cd)\")", + "Print the absolute path of a patch local_path to stdout (use: cd \"$(git cross cd)\").\n\nWith path: prints the specified local_path.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.", "local_path") wtCmd := makeDirCmd("wt [path]", - "Open a shell in the patch worktree (for working with git history)", - "Open a shell in the patch worktree (for working with git history).\n\nWith path: opens subshell in the specified worktree directory.\nWithout path: uses fzf to select a patch, then copies the path to clipboard.", + "Print a patch worktree to cd into (use: cd \"$(git cross wt)\")", + "Print the absolute path of a patch worktree to stdout (use: cd \"$(git cross wt)\").\n\nWith path: prints the specified worktree.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.", "worktree") listCmd := &cobra.Command{ - Use: "list", - Short: "Show all configured patches and remotes", + Use: "list", + Short: "Show all configured patches and remotes", + GroupID: "repo", RunE: func(cmd *cobra.Command, args []string) error { + raw, _ := cmd.Flags().GetBool("raw") + noHeader, _ := cmd.Flags().GetBool("no-header") meta, err := loadMetadata() if err != nil { return err @@ -1531,56 +1572,97 @@ func main() { usedRemotes[p.Remote] = true } + // Map to track fetch/push URLs per remote for deduplication + type remoteInfo struct { + fetch string + push string + } + remoteMap := make(map[string]*remoteInfo) + repo, err := git.Open(".") if err == nil && len(usedRemotes) > 0 { remotes, _ := git.NewCommand("remote", "-v").RunInDir(repo.Path()) - if len(remotes) > 0 { - logInfo("Configured Remotes:") - remotesStr := strings.TrimSpace(string(remotes)) - lines := strings.Split(remotesStr, "\n") - - // Map to track fetch/push URLs per remote for deduplication - type remoteInfo struct { - fetch string - push string + for _, line := range strings.Split(strings.TrimSpace(string(remotes)), "\n") { + fields := strings.Fields(line) + if len(fields) < 3 { + continue } - remoteMap := make(map[string]*remoteInfo) + name := fields[0] + url := fields[1] + rtype := fields[2] // (fetch) or (push) - for _, line := range lines { - fields := strings.Fields(line) - if len(fields) >= 3 { - name := fields[0] - url := fields[1] - rtype := fields[2] // (fetch) or (push) + if !usedRemotes[name] { + continue + } - if !usedRemotes[name] { - continue - } + if remoteMap[name] == nil { + remoteMap[name] = &remoteInfo{} + } + if strings.Contains(rtype, "fetch") { + remoteMap[name].fetch = url + } else if strings.Contains(rtype, "push") { + remoteMap[name].push = url + } + } + } - if remoteMap[name] == nil { - remoteMap[name] = &remoteInfo{} - } - if strings.Contains(rtype, "fetch") { - remoteMap[name].fetch = url - } else if strings.Contains(rtype, "push") { - remoteMap[name].push = url - } + // Deterministic remote order in both output modes. + remoteNames := make([]string, 0, len(remoteMap)) + for name := range remoteMap { + remoteNames = append(remoteNames, name) + } + sort.Strings(remoteNames) + + if raw { + // Machine-readable: tab-separated rows, no banners, no borders. + if len(remoteNames) > 0 { + if !noHeader { + fmt.Printf("REMOTE_NAME\tREMOTE_URL\n") + } + for _, name := range remoteNames { + info := remoteMap[name] + if info.fetch == "" { + continue + } + fmt.Printf("%s\t%s\n", name, info.fetch) + if info.push != "" && info.push != info.fetch { + fmt.Printf("%s\t%s\n", name, info.push) } } + } + if len(meta.Patches) == 0 { + fmt.Fprintln(os.Stderr, "No patches configured.") + return nil + } + if !noHeader { + fmt.Printf("REMOTE\tREMOTE_PATH\tLOCAL_PATH\tWORKTREE\tBRANCH\n") + } + for _, p := range meta.Patches { + fmt.Printf("%s\t%s\t%s\t%s\t%s\n", p.Remote, p.RemotePath, p.LocalPath, p.Worktree, p.Branch) + } + return nil + } - table := tablewriter.NewWriter(os.Stdout) - table.Header("NAME", "URL") - for name, info := range remoteMap { - if info.fetch == info.push || info.push == "" { - table.Append(name, info.fetch) - } else { - table.Append(name, info.fetch+" (fetch)") - table.Append(name, info.push+" (push)") - } + if len(remoteNames) > 0 { + logInfo("Configured Remotes:") + table := tablewriter.NewWriter(os.Stdout) + if !noHeader { + table.Header("REMOTE NAME", "REMOTE URL") + } + for _, name := range remoteNames { + info := remoteMap[name] + if info.fetch == "" { + continue + } + if info.fetch == info.push || info.push == "" { + table.Append(name, info.fetch) + } else { + table.Append(name, info.fetch+" (fetch)") + table.Append(name, info.push+" (push)") } - table.Render() - fmt.Println() } + table.Render() + fmt.Println() } if len(meta.Patches) == 0 { @@ -1589,18 +1671,23 @@ func main() { } logInfo("Configured Patches:") table := tablewriter.NewWriter(os.Stdout) - table.Header("REMOTE", "REMOTE PATH", "LOCAL PATH", "WORKTREE") + if !noHeader { + table.Header("REMOTE", "REMOTE PATH", "LOCAL PATH", "WORKTREE", "BRANCH") + } for _, p := range meta.Patches { - table.Append(p.Remote, p.RemotePath, p.LocalPath, p.Worktree) + table.Append(p.Remote, p.RemotePath, p.LocalPath, p.Worktree, p.Branch) } table.Render() return nil }, } + listCmd.Flags().Bool("raw", false, "machine-readable output: tab-separated rows, no borders, no banners") + listCmd.Flags().Bool("no-header", false, "omit header line (applies to table mode and --raw)") statusCmd := &cobra.Command{ - Use: "status", - Short: "Show patch status", + Use: "status", + Short: "Show patch status", + GroupID: "repo", RunE: func(cmd *cobra.Command, args []string) error { meta, _ := loadMetadata() if len(meta.Patches) == 0 { @@ -1626,18 +1713,17 @@ func main() { if _, err := os.Stat(worktreePath); os.IsNotExist(err) { diff = "Missing WT" } else { - hasOverrides, err := hasCrossOverrides(filepath.Join(root, p.LocalPath)) + localAbsPath := filepath.Join(root, p.LocalPath) + hasOverrides, err := hasCrossOverrides(localAbsPath) if err != nil { return fmt.Errorf("failed to read .crossignore for %s: %w", p.LocalPath, err) } if hasOverrides { diff = "Override" } else { - // Quick diff check - use absolute paths + // Quick diff check — .git excluded, checksum-based. upstreamPath := filepath.Join(worktreePath, p.RemotePath) - localPath := filepath.Join(root, p.LocalPath) - c := exec.Command("git", "diff", "--no-index", "--quiet", upstreamPath, localPath) - if err := c.Run(); err != nil { + if differ, derr := directoriesDiffer(upstreamPath, localAbsPath); derr == nil && differ { diff = "Modified" } } @@ -1659,7 +1745,6 @@ func main() { } // Also check conflicts in local path (from failed stash restore) - localAbsPath := filepath.Join(root, p.LocalPath) if out, _ := git.NewCommand("ls-files", "-u", localAbsPath).RunInDir(root); len(out) > 0 { conflicts = "YES" } @@ -1671,13 +1756,16 @@ func main() { } diffCmd := &cobra.Command{ - Use: "diff [path]", - Short: "Show changes between local and upstream", + Use: "diff [path]", + Short: "Show changes between local and upstream", + GroupID: "inspect", + SilenceErrors: true, + SilenceUsage: true, Long: `Show diff between local vendored files and their upstream worktree source. When run without a path argument, auto-detects the current patch from the -working directory: if CWD is inside a patched local_path, shows only that -patch's diff. Otherwise shows diffs for all patches.`, +working directory. Outside a patched directory it uses fzf to select a patch; +if fzf is unavailable it prints the available patches.`, RunE: func(cmd *cobra.Command, args []string) error { path := "" if len(args) > 0 { @@ -1688,20 +1776,30 @@ patch's diff. Otherwise shows diffs for all patches.`, } path = resolved } else { - // No explicit path: detect from CWD - cwd, err := os.Getwd() - if err == nil { - root, _ := getRepoRoot() - meta, _ := loadMetadata() - for _, p := range meta.Patches { - absLocal := filepath.Join(root, p.LocalPath) - if strings.HasPrefix(cwd+string(os.PathSeparator), absLocal+string(os.PathSeparator)) || - cwd == absLocal { - path = p.LocalPath - logInfo(fmt.Sprintf("Auto-detected patch from CWD: %s", path)) - break + // No explicit path: CWD auto-detect, then fzf, then rows+hint + meta, err := loadMetadata() + if err != nil { + return err + } + patch, perr := findPatchForPathFromCWD(meta) + if perr == nil && patch != nil { + path = patch.LocalPath + logInfo(fmt.Sprintf("Auto-detected patch from CWD: %s", path)) + } else if len(meta.Patches) == 0 { + logInfo("No patches configured.") + return nil + } else { + selected, serr := selectPatchInteractive(&meta) + if serr != nil { // fzf missing + if rerr := printPatchRows("fzf is not installed; cd into a patched directory first or pass a path. Patches (local_path worktree):"); rerr != nil { + return rerr } + return errPatchNotFound + } + if selected == nil { + return nil // cancelled } + path = selected.LocalPath } } @@ -1711,7 +1809,10 @@ patch's diff. Otherwise shows diffs for all patches.`, return fmt.Errorf("failed to get repo root: %w", err) } - meta, _ := loadMetadata() + meta, err := loadMetadata() + if err != nil { + return err + } found := false for _, p := range meta.Patches { if path != "" && p.LocalPath != path { @@ -1739,15 +1840,20 @@ patch's diff. Otherwise shows diffs for all patches.`, fmt.Printf("git diff --no-index %q %q\n", filepath.Join(upstreamPath, override), filepath.Join(localPath, override)) } } else { - c := exec.Command("git", "diff", "--no-index", upstreamPath, localPath) + c := exec.Command("git", "diff", "--no-index", + upstreamPath, localPath, + "--", ":(exclude).git", ":(glob)**") c.Stdout = os.Stdout c.Stderr = os.Stderr // git diff --no-index returns 1 if there are differences, which cobra might treat as error _ = c.Run() } } - if !found && path != "" { - return fmt.Errorf("patch not found for path: %s", path) + if !found { + if err := printPatchRows("No patch detected; available patches (local_path worktree):"); err != nil { + return err + } + return errPatchNotFound } return nil }, @@ -1896,8 +2002,9 @@ patch's diff. Otherwise shows diffs for all patches.`, } initCmd := &cobra.Command{ - Use: "init", - Short: "Initialize a new project with Crossfile", + Use: "init", + Short: "Initialize a new project with Crossfile", + GroupID: "repo", RunE: func(cmd *cobra.Command, args []string) error { path := "Crossfile" if _, err := os.Stat(path); err == nil { @@ -1914,12 +2021,32 @@ patch's diff. Otherwise shows diffs for all patches.`, } removeCmd := &cobra.Command{ - Use: "remove [path]", - Short: "Remove a patch and its worktree", - Args: cobra.ExactArgs(1), + Use: "remove [path]", + Short: "Remove a patch and its worktree", + GroupID: "patches", + Args: cobra.ExactArgs(1), + SilenceErrors: true, + SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { - meta, _ := loadMetadata() - if err := removeSinglePatch(&meta, args[0]); err != nil { + meta, err := loadMetadata() + if err != nil { + return err + } + localPath := filepath.ToSlash(filepath.Clean(strings.TrimSpace(args[0]))) + found := false + for _, p := range meta.Patches { + if p.LocalPath == localPath { + found = true + break + } + } + if !found { + if err := printPatchRows("No patch detected; available patches (local_path worktree):"); err != nil { + return err + } + return errPatchNotFound + } + if err := removeSinglePatch(&meta, localPath); err != nil { return err } if err := saveMetadata(meta); err != nil { @@ -1931,9 +2058,10 @@ patch's diff. Otherwise shows diffs for all patches.`, } pruneCmd := &cobra.Command{ - Use: "prune [remote]", - Short: "Prune unused remotes and worktrees, or remove all patches for a specific remote", - Args: cobra.MaximumNArgs(1), + Use: "prune [remote]", + Short: "Prune unused remotes and worktrees, or remove all patches for a specific remote", + GroupID: "patches", + Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { meta, _ := loadMetadata() diff --git a/test/003_diff.sh b/test/003_diff.sh index bb3e0a0da..cc717202f 100755 --- a/test/003_diff.sh +++ b/test/003_diff.sh @@ -47,8 +47,11 @@ log_header "Testing 'just cross status'..." # Find worktree # AICONTEXT: finding worktree, shall be possible with metadata.yaml and with just cross _resolve_context, better keep the test code DRY principle. -hash=$(echo "vendor/lib" | md5sum | cut -d' ' -f1 | cut -c1-8) -wt=".cross/worktrees/repo1_$hash" +wt=$(jq -r '.patches[] | select(.local_path == "vendor/lib") | .worktree' .cross/metadata.json) +if [ -z "$wt" ] || [ ! -d "$wt" ]; then + echo "Failed: worktree for vendor/lib not found in metadata." + exit 1 +fi git -C "$wt" fetch -q diff --git a/test/004_update.sh b/test/004_update.sh new file mode 100755 index 000000000..62aaca2e6 --- /dev/null +++ b/test/004_update.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +source test/common.sh + +source test/002_patch.sh + +log_header "Updating a clean patch from upstream..." +echo "upstream-v2" > "$upstream_path/src/lib/lib.txt" +git -C "$upstream_path" add src/lib/lib.txt +git -C "$upstream_path" commit -m "Update library" -q +clean_output=$(just cross update vendor/lib 2>&1) +echo "$clean_output" +assert_grep "vendor/lib/lib.txt" "upstream-v2" +if echo "$clean_output" | grep -q "differs from upstream"; then + fail "Update should not warn about local edits for a clean patch" +fi +log_success "Clean patch updated" + +log_header "Preserving local edits and refreshing sparse worktree..." +echo "local-edit" > vendor/lib/lib.txt +echo "upstream-v3" > "$upstream_path/src/lib/lib.txt" +git -C "$upstream_path" add src/lib/lib.txt +git -C "$upstream_path" commit -m "Conflicting upstream update" -q +output=$(just cross update vendor/lib 2>&1) +echo "$output" +assert_grep "vendor/lib/lib.txt" "local-edit" +if ! echo "$output" | grep -q "differs from upstream"; then + fail "Update should report that the local copy differs from upstream" +fi +if ! echo "$output" | grep -q "cross diff vendor/lib"; then + fail "Update should point at 'git cross diff ' for review" +fi +# The old verbose workflow (global config hint + tool invocation) is gone. +if echo "$output" | grep -q "Local edits detected"; then + fail "Update still prints the old 'Local edits detected' wording" +fi +if echo "$output" | grep -q "DirDiff"; then + fail "Update should not print the configured diff tool command" +fi +if echo "$output" | grep -q "git config --global cross.diffTool"; then + fail "Update should not print the global cross.diffTool hint" +fi +wt_path=$(jq -r '.patches[] | select(.local_path == "vendor/lib") | .worktree' .cross/metadata.json) +if ! git -C "$wt_path" log -1 --oneline >/dev/null 2>&1; then + fail "Expected sparse worktree to remain available" +fi + +if ! git -C "$wt_path" show HEAD:src/lib/lib.txt | grep -q upstream-v3; then + fail "Sparse worktree should advance to upstream version while local stays unchanged" +fi +assert_grep "vendor/lib/lib.txt" "local-edit" + +log_success "Update conflict behavior verified" diff --git a/test/007_status.sh b/test/007_status.sh index 6b9ccfabc..adfe59f27 100755 --- a/test/007_status.sh +++ b/test/007_status.sh @@ -112,4 +112,26 @@ check_status "vendor/docs" ".*1 ahead" rm -rf "$wt_dir" check_status "vendor/docs" "Missing WT" +# ------------------------------------------------------------------ +# Test 6: Whole-repo patch (.git pointer must not look like a local change) +# ------------------------------------------------------------------ +log_header "Testing whole-repo patch status stays Clean..." +setup_sandbox +cd "$SANDBOX" + +whole_upstream=$(create_upstream "whole-status") +pushd "$whole_upstream" >/dev/null +mkdir -p nested +echo "nested content" > nested/file.txt +git add nested/file.txt +git commit -m "Add nested content" -q +popd >/dev/null + +just cross use whole "file://$whole_upstream" +just cross patch "whole:." ./whole + +# The sparse worktree root contains a .git pointer that the local copy never +# has; status must still report Clean. +check_status "whole" "Clean.*Synced" + echo "Test 007 passed!" diff --git a/test/009_go_cli.sh b/test/009_go_cli.sh index e4f704fee..aeca6aa86 100755 --- a/test/009_go_cli.sh +++ b/test/009_go_cli.sh @@ -28,6 +28,10 @@ export PATH="$SANDBOX/bin:$PATH" # Compile go binary GO_BIN="$REPO_ROOT/src-go/git-cross-go" +# Rebuild if the source changed since the binary was built. +if [ -f "$GO_BIN" ] && [ "$REPO_ROOT/src-go/main.go" -nt "$GO_BIN" ]; then + rm -f "$GO_BIN" +fi if [ ! -f "$GO_BIN" ]; then echo "Go binary not found at $GO_BIN. Building..." export PATH=$HOME/homebrew/bin:$PATH @@ -158,6 +162,66 @@ if ! echo "$list_output" | grep -q "vendor/go-src"; then fail "Go 'list' should show patch path 'vendor/go-src'" fi +log_header "Testing Go 'list --raw' machine-readable output..." +raw_output=$("$GO_BIN" list --raw 2>/dev/null) +echo "$raw_output" +if echo "$raw_output" | grep -q "==>"; then + fail "Go 'list --raw' must not print section banners" +fi +if echo "$raw_output" | grep -q '^+'; then + fail "Go 'list --raw' must not print table borders ('+')" +fi +if echo "$raw_output" | grep -q '|'; then + fail "Go 'list --raw' must not print table borders ('|')" +fi +if ! echo "$raw_output" | grep -q "REMOTE_NAME" || ! echo "$raw_output" | grep -q "REMOTE_URL"; then + fail "Go 'list --raw' should print the REMOTE_NAME/REMOTE_URL header" +fi +if ! echo "$raw_output" | grep -q "LOCAL_PATH" || ! echo "$raw_output" | grep -q "WORKTREE" || ! echo "$raw_output" | grep -q "BRANCH"; then + fail "Go 'list --raw' should print the patch header with LOCAL_PATH, WORKTREE and BRANCH" +fi +if ! printf '%s\n' "$raw_output" | cut -f3 | grep -qx "vendor/go-src"; then + fail "Go 'list --raw' patches block: 'cut -f3' should yield local paths" +fi +if ! printf '%s\n' "$raw_output" | cut -f1 | grep -qx "demo"; then + fail "Go 'list --raw' remotes block should start with the remote name" +fi + +raw_again=$("$GO_BIN" list --raw 2>/dev/null) +if [ "$raw_output" != "$raw_again" ]; then + fail "Go 'list --raw' output is not deterministic between runs" +fi + +noheader_output=$("$GO_BIN" list --raw --no-header 2>/dev/null) +echo "$noheader_output" +if echo "$noheader_output" | grep -q "REMOTE_NAME" || echo "$noheader_output" | grep -q "LOCAL_PATH"; then + fail "Go 'list --raw --no-header' should omit the header lines" +fi +if ! printf '%s\n' "$noheader_output" | cut -f3 | grep -qx "vendor/go-src"; then + fail "Go 'list --raw --no-header' should still print patch rows" +fi + +table_noheader=$("$GO_BIN" list --no-header 2>&1) +if echo "$table_noheader" | grep -q "REMOTE PATH" || echo "$table_noheader" | grep -q "LOCAL PATH"; then + fail "Go 'list --no-header' should omit the table headers" +fi +if ! echo "$table_noheader" | grep -q "vendor/go-src"; then + fail "Go 'list --no-header' should still print the patch rows" +fi + +# A remote whose fetch and push URLs differ gets two rows under the same schema. +git remote set-url --push demo "file://$upstream_path-push" +pushpull_output=$("$GO_BIN" list --raw 2>/dev/null) +echo "$pushpull_output" +demo_rows=$(printf '%s\n' "$pushpull_output" | awk -F'\t' '$1=="demo" && NF==2' | wc -l | tr -d ' ') +if [ "$demo_rows" -ne 2 ]; then + fail "Go 'list --raw' should emit two rows for a fetch!=push remote (got $demo_rows)" +fi +if printf '%s\n' "$pushpull_output" | grep -q "(fetch)\|(push)"; then + fail "Go 'list --raw' must not add (fetch)/(push) suffixes to URLs" +fi +git remote set-url --push demo "$upstream_url" + log_header "Testing Go 'status' command..." status_output=$("$GO_BIN" status 2>&1) echo "$status_output" @@ -190,11 +254,17 @@ echo "$update_output" if ! grep -q "local-only edit" vendor/go-src/logic.go; then fail "Go update overwrote the local edit" fi -if ! echo "$update_output" | grep -q "Local edits detected"; then - fail "Go update should report local edits" +if ! echo "$update_output" | grep -q "differs from upstream"; then + fail "Go update should report that the local copy differs from upstream" +fi +if echo "$update_output" | grep -q "Local edits detected"; then + fail "Go update still prints the old 'Local edits detected' wording" fi -if ! echo "$update_output" | grep -q "DirDiff"; then - fail "Go update should print the compare command" +if echo "$update_output" | grep -q "DirDiff"; then + fail "Go update should not print the configured diff tool command" +fi +if echo "$update_output" | grep -q "git config --global cross.diffTool"; then + fail "Go update should not print the global cross.diffTool hint" fi log_header "Testing Go 'diff' command..." @@ -215,7 +285,8 @@ printf '%s\n%s\n' "$1" "$2" > "$COMPARE_TOOL_ARGS" EOF chmod +x "$SANDBOX/bin/compare-tool" export COMPARE_TOOL_ARGS="$SANDBOX/compare-args.txt" -git config cross.diffTool "$SANDBOX/bin/compare-tool" +# Template form: placeholders are substituted with repo-relative paths. +git config cross.diffTool "$SANDBOX/bin/compare-tool {left} {right}" "$GO_BIN" compare vendor/go-src if ! grep -q ".cross/worktrees/demo_" "$COMPARE_TOOL_ARGS"; then fail "Go compare did not pass the sparse worktree path" @@ -223,6 +294,30 @@ fi if ! grep -q "vendor/go-src" "$COMPARE_TOOL_ARGS"; then fail "Go compare did not pass the local patch path" fi +if grep -q "^/" "$COMPARE_TOOL_ARGS"; then + fail "Go compare template should substitute repo-relative paths, got absolute paths" +fi + +# Legacy form (no placeholders) still appends the paths as arguments. +rm -f "$COMPARE_TOOL_ARGS" +git config cross.diffTool "$SANDBOX/bin/compare-tool" +"$GO_BIN" compare vendor/go-src +if ! grep -q ".cross/worktrees/demo_" "$COMPARE_TOOL_ARGS"; then + fail "Go compare legacy form did not pass the sparse worktree path" +fi +if ! grep -q "vendor/go-src" "$COMPARE_TOOL_ARGS"; then + fail "Go compare legacy form did not pass the local patch path" +fi +git config --unset cross.diffTool +unset COMPARE_TOOL_ARGS + +# The 'cmp' alias behaves like 'compare'. +git config cross.diffTool 'echo TOOL {left} {right}' +cmp_output=$("$GO_BIN" cmp vendor/go-src 2>&1 || true) +echo "$cmp_output" +if ! echo "$cmp_output" | grep -Eq "TOOL \.cross/worktrees/demo_[0-9a-f]+/src vendor/go-src"; then + fail "Go 'cmp' alias should resolve and run the diff tool like 'compare'" +fi git config --unset cross.diffTool log_header "Testing Go '.crossignore' override status/diff hint..." diff --git a/test/010_worktree.sh b/test/010_worktree.sh index 4314c80b4..d454bbef0 100644 --- a/test/010_worktree.sh +++ b/test/010_worktree.sh @@ -3,37 +3,16 @@ set -euo pipefail source "$(dirname "$0")/common.sh" -# The cd/wt commands are only implemented in Go, not in Justfile/shell +# The cd/wt commands now print a path instead of opening a subshell. # Skip this test unless the Go implementation was explicitly requested. if [ "${TEST_USE_IMPL:-}" != "go" ]; then - echo "Skipping test 010: cd/wt commands are Go-only" + echo "Skipping test 010: cd/wt implementation checks are opt-in (TEST_USE_IMPL=go)" exit 0 fi setup_sandbox cd "$SANDBOX" -mkdir -p "$SANDBOX/bin" -cat > "$SANDBOX/bin/fzf" <<'EOF' -#!/usr/bin/env bash -lines=() -while IFS= read -r line; do - lines+=("$line") -done -for (( idx=${#lines[@]}-1; idx>=0; idx--)); do - line="${lines[$idx]}" - trimmed="$(echo "$line" | tr -d '[:space:]')" - if [[ -z "$trimmed" ]]; then continue; fi - if [[ "$line" == *"REMOTE"* && "$line" != *"/"* ]]; then continue; fi - if [[ "$line" =~ ^[-+]+$ ]]; then continue; fi - echo "$line" - exit 0 -done -exit 0 -EOF -chmod +x "$SANDBOX/bin/fzf" -export PATH="$SANDBOX/bin:$PATH" - upstream_path=$(create_upstream "shell-worktree") upstream_url="file://$upstream_path" @@ -44,20 +23,29 @@ git add src/data.txt git commit -m "Add shell data" >/dev/null popd >/dev/null -just cross use demo "$upstream_url" -just cross patch demo:src vendor/shell-src +just cross use demo "$upstream_url" >/dev/null +just cross patch demo:src vendor/shell-src >/dev/null + +# Test cd with explicit path: stdout is exactly the absolute local path. +expected_local=$(cd vendor/shell-src && pwd -P) +output=$(just cross cd vendor/shell-src 2>/dev/null) +if [ "$output" != "$expected_local" ]; then + fail "cd with explicit path returned '$output', expected '$expected_local'" +fi -# Test cd with explicit path -output=$(just cross dry=echo cd vendor/shell-src | grep "exec ") -if [[ "$output" != *"exec $SHELL"* ]]; then - fail "cd with explicit path failed. Output: $output" +# Test wt with explicit path: stdout is exactly the absolute worktree path. +wt=$(jq -r '.patches[] | select(.local_path == "vendor/shell-src") | .worktree' .cross/metadata.json) +expected_wt=$(cd "$wt" && pwd -P) +output=$(just cross wt vendor/shell-src 2>/dev/null) +if [ "$output" != "$expected_wt" ]; then + fail "wt with explicit path returned '$output', expected '$expected_wt'" fi -# Test cd from patch directory (implicit context) +# Test cd from patch directory (implicit context). pushd vendor/shell-src >/dev/null -output=$(just cross dry=echo cd | grep "exec ") -if [[ "$output" != *"exec $SHELL"* ]]; then - fail "cd from patch directory failed. Output: $output" +output=$(just cross cd 2>/dev/null) +if [ "$output" != "$expected_local" ]; then + fail "cd from patch directory returned '$output', expected '$expected_local'" fi popd >/dev/null diff --git a/test/014_remove.sh b/test/014_remove.sh index 9df9d0ad6..a8811478d 100755 --- a/test/014_remove.sh +++ b/test/014_remove.sh @@ -19,6 +19,9 @@ if git worktree list | grep -q "vendor/lib"; then fail "Worktree still exists"; # Build Go binary (reuse existing or build fresh) GO_BIN="$REPO_ROOT/src-go/git-cross-go" +if [ -f "$GO_BIN" ] && [ "$REPO_ROOT/src-go/main.go" -nt "$GO_BIN" ]; then + rm -f "$GO_BIN" +fi if [ ! -f "$GO_BIN" ]; then if command -v go >/dev/null 2>&1; then # Remove stale vendor dir that causes "inconsistent vendoring" errors @@ -51,10 +54,57 @@ if [ -n "$GO_BIN" ] && [ -f "$GO_BIN" ]; then echo "## Testing 'list' command (Go)..." just cross patch repo1:src/lib vendor/list-test list_output=$("$GO_BIN" list) + echo "$list_output" if ! echo "$list_output" | grep -q "Configured Remotes"; then fail "Go list missing Remotes section"; fi if ! echo "$list_output" | grep -q "repo1"; then fail "Go list missing repo1 remote"; fi + if ! echo "$list_output" | grep -q "REMOTE URL"; then fail "Go list missing descriptive 'REMOTE URL' header"; fi + if ! echo "$list_output" | grep -q "LOCAL PATH"; then fail "Go list missing 'LOCAL PATH' header"; fi + + echo "## Testing 'list --raw' (Go)..." + raw_output=$("$GO_BIN" list --raw) + echo "$raw_output" + if echo "$raw_output" | grep -q "==>"; then fail "Go list --raw must not print banners"; fi + if echo "$raw_output" | grep -q '^+' || echo "$raw_output" | grep -q '|'; then + fail "Go list --raw must not print table borders" + fi + if ! echo "$raw_output" | grep -q "REMOTE_NAME"; then fail "Go list --raw missing REMOTE_NAME header"; fi + if ! printf '%s\n' "$raw_output" | cut -f3 | grep -qx "vendor/list-test"; then + fail "Go list --raw: cut -f3 should yield local paths" + fi + raw_again=$("$GO_BIN" list --raw) + if [ "$raw_output" != "$raw_again" ]; then fail "Go list --raw is not deterministic"; fi + noheader_output=$("$GO_BIN" list --raw --no-header) + if echo "$noheader_output" | grep -q "REMOTE_NAME"; then + fail "Go list --raw --no-header must omit headers" + fi + if ! printf '%s\n' "$noheader_output" | cut -f3 | grep -qx "vendor/list-test"; then + fail "Go list --raw --no-header should still print patch rows" + fi just cross remove vendor/list-test + # 4b. Test list --raw for the Just/Fish implementation when fish is available + if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1; then + echo "## Testing 'list raw=1' (Just/Fish)..." + just cross patch repo1:src/lib vendor/list-test + raw_output=$(just cross list raw=1) + echo "$raw_output" + if echo "$raw_output" | grep -q "==>"; then fail "Just list raw=1 must not print banners"; fi + if echo "$raw_output" | grep -q '^+' || echo "$raw_output" | grep -q '|'; then + fail "Just list raw=1 must not print table borders" + fi + if ! echo "$raw_output" | grep -q "REMOTE_NAME"; then fail "Just list raw=1 missing REMOTE_NAME header"; fi + if ! printf '%s\n' "$raw_output" | cut -f3 | grep -qx "vendor/list-test"; then + fail "Just list raw=1: cut -f3 should yield local paths" + fi + raw_again=$(just cross list raw=1) + if [ "$raw_output" != "$raw_again" ]; then fail "Just list raw=1 is not deterministic"; fi + noheader_output=$(just cross list raw=1 no_header=1) + if echo "$noheader_output" | grep -q "REMOTE_NAME"; then + fail "Just list raw=1 no_header=1 must omit headers" + fi + just cross remove vendor/list-test + fi + # 5. Test Crossfile deduplication (Go) echo "## Testing Crossfile deduplication (Go)..." just cross patch repo1:src/lib vendor/dedup-test diff --git a/test/016_diff_context.sh b/test/016_diff_context.sh index 59a98a9b0..34077f970 100755 --- a/test/016_diff_context.sh +++ b/test/016_diff_context.sh @@ -77,8 +77,31 @@ fi popd >/dev/null log_success "Test 4 passed: diff . works from inside patch" +# --- Test 4b: diff from repo root without a path, fzf absent → rows + hint --- +log_header "Test 4b: diff from repo root (no path, no fzf) prints rows and exits 1..." +nofzf_path=$(make_path_without_fzf "$SANDBOX/no-fzf-bin") +diff_rc=0 +output=$(PATH="$nofzf_path" just cross diff 2>&1) || diff_rc=$? +echo "$output" +if [ "$diff_rc" -eq 0 ]; then + fail "Test 4b: diff without a path outside a patch should exit non-zero" +fi +if ! printf '%s\n' "$output" | awk -F'\t' '$1=="vendor/alpha"{found=1} END{exit found?0:1}'; then + fail "Test 4b: diff should list patch rows (local_pathworktree)" +fi +if echo "$output" | grep -q "Usage:"; then + fail "Test 4b: diff should not dump a Usage message" +fi +if ! echo "$output" | grep -q "fzf is not installed"; then + fail "Test 4b: diff should explain that fzf is missing" +fi +log_success "Test 4b passed: Just diff falls back to rows+hint" + # --- Go implementation tests (when binary is available) --- GO_BIN="$REPO_ROOT/src-go/git-cross-go" +if [ -f "$GO_BIN" ] && [ "$REPO_ROOT/src-go/main.go" -nt "$GO_BIN" ]; then + rm -f "$GO_BIN" +fi if [ ! -f "$GO_BIN" ]; then (cd "$REPO_ROOT/src-go" && CGO_ENABLED=0 go build -o git-cross-go main.go 2>/dev/null) fi @@ -89,17 +112,26 @@ git init -q "$_smoke_dir" if [ "$_go_ok" = false ]; then log_warn "Go binary not working on this platform, skipping Go-specific diff context tests" else - log_header "Test 5 (Go): diff from repo root shows all patches..." - output=$("$GO_BIN" diff 2>&1 || true) + # Without a path and outside a patch dir the new contract is: fzf selection, + # or rows + hint + exit 1 when fzf is missing. (It used to dump all patches.) + log_header "Test 5 (Go): diff from repo root without fzf prints rows and exits 1..." + nofzf_path=$(make_path_without_fzf "$SANDBOX/no-fzf-bin") + diff_rc=0 + output=$(PATH="$nofzf_path" "$GO_BIN" diff 2>&1) || diff_rc=$? echo "$output" - if ! echo "$output" | grep -q "alpha" || ! echo "$output" | grep -q "beta"; then - fail "Test 5 (Go): diff from repo root should include both patches" + [ "$diff_rc" -eq 1 ] || fail "Test 5 (Go): diff without fzf should exit 1, got $diff_rc" + if ! printf '%s\n' "$output" | cut -f1 | grep -qx "vendor/alpha" \ + || ! printf '%s\n' "$output" | cut -f1 | grep -qx "vendor/beta"; then + fail "Test 5 (Go): diff should list all patches as rows" fi - log_success "Test 5 passed: Go diff from repo root shows all patches" + if ! echo "$output" | grep -q "fzf is not installed"; then + fail "Test 5 (Go): diff should explain that fzf is missing" + fi + log_success "Test 5 passed: Go diff falls back to rows+hint" log_header "Test 6 (Go): diff from inside patch auto-detects..." pushd vendor/alpha >/dev/null - output=$("$GO_BIN" diff 2>&1 || true) + output=$(PATH="$nofzf_path" "$GO_BIN" diff 2>&1 || true) echo "$output" if ! echo "$output" | grep -q "alpha"; then fail "Test 6 (Go): auto-detect should show alpha diff" @@ -110,12 +142,28 @@ else popd >/dev/null log_success "Test 6 passed: Go auto-detects patch from CWD" - log_header "Test 7 (Go): diff from repo root (no patches match CWD) shows all..." - output=$("$GO_BIN" diff 2>&1 || true) - if ! echo "$output" | grep -q "alpha" || ! echo "$output" | grep -q "beta"; then - fail "Test 7 (Go): diff from repo root should show all patches" + log_header "Test 7 (Go): diff honours the fzf selection..." + shim_dir="$SANDBOX/fzf-shim-bin" + mkdir -p "$shim_dir" + cat > "$shim_dir/fzf" <<'EOF' +#!/usr/bin/env bash +cat >/dev/null +if [ -n "${FZF_SELECT:-}" ]; then + printf '%b\n' "$FZF_SELECT" + exit 0 +fi +exit 130 +EOF + chmod +x "$shim_dir/fzf" + output=$(FZF_SELECT='upstream\t.\tvendor/beta' PATH="$shim_dir:$PATH" "$GO_BIN" diff 2>&1 || true) + echo "$output" + if ! echo "$output" | grep -q "beta"; then + fail "Test 7 (Go): fzf selection should show the beta diff" + fi + if echo "$output" | grep -q "alpha"; then + fail "Test 7 (Go): fzf selection should NOT show the alpha diff" fi - log_success "Test 7 passed: Go shows all patches from repo root" + log_success "Test 7 passed: Go diff uses the fzf selection" fi # --- Test 8: override markers print manual diff commands --- diff --git a/test/017_cd_wt_fix.sh b/test/017_cd_wt_fix.sh index 576495f83..62f738312 100755 --- a/test/017_cd_wt_fix.sh +++ b/test/017_cd_wt_fix.sh @@ -1,123 +1,150 @@ -#!/bin/bash -source test/common.sh - -###### -# Test: cd/wt command behavior -# - With explicit path: opens subshell (difficult to test) -# - Without path: uses fzf or copies to clipboard (difficult to test) -# This test verifies basic functionality and error handling -###### -log_header "Test: cd/wt command behavior..." - -# Save repo root -REPO_ROOT=$(pwd) - -# Setup: Create test environment -test_repo=$(mktemp -d) -cd "$test_repo" || exit 1 - -# Initialize main repo -git init -q -git config user.name "Test User" -git config user.email "test@example.com" -echo "main repo" > README.md -git add . && git commit -m "init" -q - -# Copy Justfiles to test repo -cp "$REPO_ROOT/Justfile" . -cp "$REPO_ROOT/Justfile.cross" . - -# Create upstream repo -upstream=$(mktemp -d) -git -C "$upstream" init -q -git -C "$upstream" config user.name "Test User" -git -C "$upstream" config user.email "test@example.com" -mkdir -p "$upstream/src" -echo "upstream content" > "$upstream/src/file.txt" -git -C "$upstream" add . && git -C "$upstream" commit -m "init" -q - -# Initialize cross and create patch -mkdir -p .cross -echo '{"patches":[]}' > .cross/metadata.json -git remote add demo "$upstream" - -log_info "Creating patch..." -just cross patch demo:src vendor/src || { log_error "Patch failed"; exit 1; } - -# Test 1: Verify cd command exists and doesn't crash on invalid path -log_info "Test 1: cd with non-existent path should fail gracefully..." -output=$(just cross cd non-existent-path 2>&1 || true) -if echo "$output" | grep -qE "not found|No patches|Directory not found"; then - log_success "cd correctly reports non-existent path" +#!/usr/bin/env bash +# Test 017: cd/wt path-printing contract. +# +# The command cannot change the caller's shell, so it prints exactly one +# absolute path to stdout (hints go to stderr). No subshell, no clipboard. +# Without a path and without fzf: rows + hint, exit 1. +source "$(dirname "$0")/common.sh" + +PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +GO_BIN="$(ensure_go_bin "$PROJECT_ROOT")" + +assert_one_abs_path() { + local label=$1 + local output=$2 + local expected=$3 + local line_count + line_count=$(printf '%s\n' "$output" | sed '/^$/d' | wc -l | tr -d ' ') + [ "$line_count" -eq 1 ] || fail "$label: expected exactly one line, got $line_count: $output" + case "$output" in + /*) ;; + *) fail "$label: expected an absolute path, got: $output" ;; + esac + assert_not_contains "$output" "Opening shell" "$label: must not open a subshell" + assert_not_contains "$output" "clipboard" "$label: must not copy to the clipboard" + [ "$output" = "$expected" ] || fail "$label: expected '$expected', got '$output'" +} + +cd "$PROJECT_ROOT" +setup_sandbox +cd "$SANDBOX" + +upstream_path=$(create_upstream "cd-wt-demo") +pushd "$upstream_path" >/dev/null +mkdir -p src +echo "upstream content" > src/file.txt +git add src/file.txt +git commit -m "Add src" -q +popd >/dev/null +upstream_url="file://$upstream_path" + +# Create the patch with whichever implementation is available. +if [ -n "$GO_BIN" ]; then + "$GO_BIN" use demo "$upstream_url" >/dev/null + "$GO_BIN" patch demo:src vendor/src >/dev/null else - log_warn "cd error handling may need improvement: $output" + just cross use demo "$upstream_url" >/dev/null + just cross patch demo:src vendor/src >/dev/null fi -# Test 2: Verify wt command exists and doesn't crash on invalid path -log_info "Test 2: wt with non-existent path should fail gracefully..." -output=$(just cross wt non-existent-path 2>&1 || true) -if echo "$output" | grep -qE "not found|No patches|Directory not found"; then - log_success "wt correctly reports non-existent path" -else - log_warn "wt error handling may need improvement: $output" +wt_path=$(jq -r '.patches[] | select(.local_path == "vendor/src") | .worktree' .cross/metadata.json) +[ -n "$wt_path" ] || fail "metadata missing the vendor/src worktree" +local_abs=$(cd vendor/src && pwd -P) +wt_abs=$(cd "$wt_path" && pwd -P) + +# ---------------------------------------------------------------- Go section +if [ -n "$GO_BIN" ]; then + log_header "017: Go cd/wt print one absolute path" + out=$("$GO_BIN" cd vendor/src 2>/dev/null) || fail "Go cd with a path failed" + assert_one_abs_path "Go cd vendor/src" "$out" "$local_abs" + + out=$("$GO_BIN" wt vendor/src 2>/dev/null) || fail "Go wt with a path failed" + assert_one_abs_path "Go wt vendor/src" "$out" "$wt_abs" + log_success "Go prints absolute paths" + + log_header "017: Go fzf-missing fallback prints rows and exits 1" + nofzf_path=$(make_path_without_fzf "$SANDBOX/no-fzf-bin") + + cd_rc=0 + cd_out=$(PATH="$nofzf_path" "$GO_BIN" cd 2>"$SANDBOX/cd.err") || cd_rc=$? + echo "$cd_out" + echo "--- stderr ---" + cat "$SANDBOX/cd.err" + [ "$cd_rc" -eq 1 ] || fail "Go cd without fzf should exit 1, got $cd_rc" + printf '%s\n' "$cd_out" | cut -f1 | grep -qx "vendor/src" \ + || fail "Go cd fallback should list local_path rows" + printf '%s\n' "$cd_out" | cut -f2 | grep -q '^\.cross/worktrees/demo_' \ + || fail "Go cd fallback should list worktree rows" + assert_contains "$(cat "$SANDBOX/cd.err")" "fzf is not installed" \ + "Go cd fallback should say fzf is missing" + + wt_rc=0 + wt_out=$(PATH="$nofzf_path" "$GO_BIN" wt 2>"$SANDBOX/wt.err") || wt_rc=$? + echo "$wt_out" + [ "$wt_rc" -eq 1 ] || fail "Go wt without fzf should exit 1, got $wt_rc" + printf '%s\n' "$wt_out" | cut -f2 | grep -q '^\.cross/worktrees/demo_' \ + || fail "Go wt fallback should list worktree rows" + assert_contains "$(cat "$SANDBOX/wt.err")" "fzf is not installed" \ + "Go wt fallback should say fzf is missing" + log_success "Go fzf-missing fallback verified" + + log_header "017: Go fzf selection prints the selected path" + shim_dir="$SANDBOX/fzf-shim-bin" + mkdir -p "$shim_dir" + cat > "$shim_dir/fzf" <<'EOF' +#!/usr/bin/env bash +cat >/dev/null +if [ -n "${FZF_SELECT:-}" ]; then + printf '%b\n' "$FZF_SELECT" + exit 0 fi - -# Test 3: Verify cd with valid path (can't test subshell directly) -log_info "Test 3: cd target directory exists..." -if [ -d "vendor/src" ]; then - log_success "cd target directory exists: vendor/src" -else - log_error "cd target directory doesn't exist" - exit 1 -fi - -# Test 4: Verify wt with valid path (can't test subshell directly) -log_info "Test 4: wt target worktree exists..." -# Worktree path includes a hash, so find it dynamically -if [ -d ".cross/worktrees" ] && ls .cross/worktrees/demo_* >/dev/null 2>&1; then - log_success "wt target worktree exists" +exit 130 +EOF + chmod +x "$shim_dir/fzf" + selection="demo\tsrc\tvendor/src" + + out=$(FZF_SELECT="$selection" PATH="$shim_dir:$PATH" "$GO_BIN" cd 2>/dev/null) \ + || fail "Go cd with an fzf selection failed" + assert_one_abs_path "Go cd (fzf)" "$out" "$local_abs" + + out=$(FZF_SELECT="$selection" PATH="$shim_dir:$PATH" "$GO_BIN" wt 2>/dev/null) \ + || fail "Go wt with an fzf selection failed" + assert_one_abs_path "Go wt (fzf)" "$out" "$wt_abs" + log_success "Go fzf selection verified" else - log_error "wt target worktree doesn't exist" - ls -la .cross/worktrees/ || true - exit 1 + echo "SKIP: Go CLI unavailable; skipping Go cd/wt assertions" fi -# Test 5: Verify list output for cd/wt reference -log_info "Test 5: Verify patch list for reference..." -if just cross list | grep -q "vendor/src"; then - log_success "Patch list shows correct local_path" -else - log_error "Patch list doesn't show expected path" - exit 1 -fi - -# Test 6: Test Go implementation -log_info "Test 6: Testing Go implementation..." -GO_BIN="$REPO_ROOT/src-go/git-cross-go" -if [ -f "$GO_BIN" ]; then - if "$GO_BIN" cd non-existent-path 2>&1 | grep -qE "not found|No patches"; then - log_success "Go: cd correctly reports non-existent path" - else - log_warn "Go: cd error handling may need improvement" - fi - - if "$GO_BIN" wt non-existent-path 2>&1 | grep -qE "not found|No patches"; then - log_success "Go: wt correctly reports non-existent path" - else - log_warn "Go: wt error handling may need improvement" +# -------------------------------------------------------------- Just section +if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command -v just >/dev/null 2>&1; then + log_header "017: Just cd/wt print one absolute path" + out=$(just cross cd vendor/src 2>/dev/null) || fail "Just cd with a path failed" + assert_one_abs_path "Just cd vendor/src" "$out" "$local_abs" + + out=$(just cross wt vendor/src 2>/dev/null) || fail "Just wt with a path failed" + assert_one_abs_path "Just wt vendor/src" "$out" "$wt_abs" + log_success "Just prints absolute paths" + + log_header "017: Just fzf-missing fallback prints rows and exits 1" + nofzf_path=$(make_path_without_fzf "$SANDBOX/no-fzf-bin") + + cd_rc=0 + cd_out=$(PATH="$nofzf_path" just cross cd 2>&1) || cd_rc=$? + echo "$cd_out" + [ "$cd_rc" -eq 1 ] || fail "Just cd without fzf should exit 1, got $cd_rc" + if ! printf '%s\n' "$cd_out" | awk -F'\t' '$1=="vendor/src"{found=1} END{exit found?0:1}'; then + fail "Just cd fallback should list local_pathworktree rows" fi + assert_contains "$cd_out" "fzf is not installed" "Just cd fallback should say fzf is missing" + + wt_rc=0 + wt_out=$(PATH="$nofzf_path" just cross wt 2>&1) || wt_rc=$? + echo "$wt_out" + [ "$wt_rc" -eq 1 ] || fail "Just wt without fzf should exit 1, got $wt_rc" + assert_contains "$wt_out" "fzf is not installed" "Just wt fallback should say fzf is missing" + log_success "Just fzf-missing fallback verified" else - log_warn "Go binary not found at $GO_BIN, skipping Go tests" + echo "SKIP: fish and/or jq/just unavailable; skipping Just cd/wt assertions" fi -# Cleanup -cd / -rm -rf "$test_repo" "$upstream" - -log_success "cd/wt tests completed successfully!" -echo "" -echo "Note: This test verifies basic functionality and error handling." -echo "Manual testing required for:" -echo " - Subshell opening with explicit path (cd/wt with path)" -echo " - Clipboard copying with fzf selection (cd/wt without path)" -echo " - fzf interactive selection behavior" +echo "Test 017 passed!" diff --git a/test/018_sbx_sandbox.sh b/test/018_sbx_sandbox.sh index 7d56a9858..5daf3ce81 100644 --- a/test/018_sbx_sandbox.sh +++ b/test/018_sbx_sandbox.sh @@ -6,6 +6,9 @@ setup_sandbox cd "$SANDBOX" GO_BIN="$REPO_ROOT/src-go/git-cross-go" +if [ -f "$GO_BIN" ] && [ "$REPO_ROOT/src-go/main.go" -nt "$GO_BIN" ]; then + rm -f "$GO_BIN" +fi if [ ! -f "$GO_BIN" ]; then if ! command -v go >/dev/null 2>&1; then echo "SKIP: Go not available" @@ -36,11 +39,17 @@ echo "$output" if ! grep -q "local AI change" vendor/ai-src/app.js; then fail "Update overwrote local changes" fi -if ! echo "$output" | grep -q "Local edits detected"; then - fail "Update did not report the conflict review workflow" +if ! echo "$output" | grep -q "differs from upstream"; then + fail "Update did not report that the local copy differs from upstream" +fi +if ! echo "$output" | grep -q "cross diff vendor/ai-src"; then + fail "Update did not point at 'git cross diff ' for review" +fi +if echo "$output" | grep -q "Local edits detected"; then + fail "Update still prints the old 'Local edits detected' wording" fi -if ! echo "$output" | grep -q "DirDiff"; then - fail "Update did not show the default comparison tool command" +if echo "$output" | grep -q "DirDiff"; then + fail "Update should not print the configured diff tool command" fi wt=$(jq -r '.patches[0].worktree' .cross/metadata.json) diff --git a/test/019_whole_repo_patch_and_listing.sh b/test/019_whole_repo_patch_and_listing.sh new file mode 100755 index 000000000..9523150c9 --- /dev/null +++ b/test/019_whole_repo_patch_and_listing.sh @@ -0,0 +1,189 @@ +#!/usr/bin/env bash +# Test 019: whole-repo patches (remote path ".") + row-based patch listing. +# +# Covers the UX refresh contract: +# - the worktree's `.git` pointer must not count as a local change, so +# `update` re-syncs and `status` reports Clean for whole-repo patches +# - `diff` shows real changes and never the `.git` pointer +# - bare `git-cross` and an unresolved `compare` print machine-parseable +# rows (`local_pathworktree`) instead of a Usage dump +# - `cross.diffTool` template placeholders receive repo-relative paths +source "$(dirname "$0")/common.sh" + +PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +GO_BIN="$(ensure_go_bin "$PROJECT_ROOT")" + +if [ -z "$GO_BIN" ]; then + echo "SKIP: Go CLI unavailable; skipping whole-repo Go assertions" +fi + +# ---------------------------------------------------------------- Go section +if [ -n "$GO_BIN" ]; then + cd "$PROJECT_ROOT" + setup_sandbox + cd "$SANDBOX" + + log_header "019: whole-repo patch via Go (remote path '.')" + upstream_path=$(create_upstream "whole-repo") + pushd "$upstream_path" >/dev/null + mkdir -p docs + echo "docs v1" > docs/guide.md + git add docs/guide.md + git commit -m "Add docs" -q + popd >/dev/null + upstream_url="file://$upstream_path" + + "$GO_BIN" use up "$upstream_url" >/dev/null + "$GO_BIN" patch "up:." ./sub >/dev/null + assert_file_exists "sub/README.md" + assert_file_exists "sub/docs/guide.md" + log_success "whole-repo patch created at sub/" + + # --- upstream commit + update must re-sync without a .git false positive + log_header "019: update re-syncs whole-repo patch (no .git false positive)" + pushd "$upstream_path" >/dev/null + echo "docs v2 upstream, longer content" > docs/guide.md + echo "brand new" > new-file.txt + git add -A + git commit -m "Upstream v2" -q + popd >/dev/null + + update_output=$("$GO_BIN" update 2>&1) + echo "$update_output" + assert_not_contains "$update_output" "differs from upstream" \ + "update falsely reported local edits for a whole-repo patch (.git leak)" + assert_grep "sub/docs/guide.md" "docs v2" + assert_file_exists "sub/new-file.txt" + assert_grep "sub/new-file.txt" "brand new" + log_success "update re-synced the whole-repo patch" + + # --- status must not report Modified just because of the .git pointer + log_header "019: status reports Clean for a synced whole-repo patch" + status_output=$("$GO_BIN" status 2>&1) + echo "$status_output" + sub_line=$(printf '%s\n' "$status_output" | grep -E '(^|[[:space:]])sub([[:space:]]|$)' | head -n 1) + [ -n "$sub_line" ] || fail "status did not list the whole-repo patch 'sub'" + assert_contains "$sub_line" "Clean" "status reported a non-Clean diff for a synced whole-repo patch" + assert_not_contains "$sub_line" "Modified" "status falsely reported Modified (worktree .git leak)" + log_success "status reports Clean" + + # --- diff shows the real change, never the .git pointer + log_header "019: diff shows real content and excludes .git" + echo "local docs tweak" >> sub/docs/guide.md + diff_output=$("$GO_BIN" diff sub 2>&1 || true) + echo "$diff_output" + assert_contains "$diff_output" "local docs tweak" + assert_not_contains "$diff_output" ".git" "diff must not include the worktree .git pointer file" + log_success "diff excludes .git" + + # --- bare command + unresolved compare print rows (fzf absent) + log_header "019: bare listing and unresolved compare print rows" + nofzf_path=$(make_path_without_fzf "$SANDBOX/no-fzf-bin") + + bare_rc=0 + bare_stdout=$(PATH="$nofzf_path" "$GO_BIN" 2>"$SANDBOX/bare.err") || bare_rc=$? + echo "$bare_stdout" + [ "$bare_rc" -eq 0 ] || fail "bare 'git-cross' should exit 0, got $bare_rc" + assert_not_contains "$bare_stdout" "Usage:" "bare 'git-cross' should not print a Usage dump" + printf '%s\n' "$bare_stdout" | cut -f1 | grep -qx "sub" \ + || fail "bare listing missing local_path 'sub' in the first column" + printf '%s\n' "$bare_stdout" | cut -f2 | grep -q '^\.cross/worktrees/up_' \ + || fail "bare listing missing worktree path in the second column" + log_success "bare 'git-cross' prints local_pathworktree rows" + + compare_rc=0 + compare_stdout=$(PATH="$nofzf_path" "$GO_BIN" compare 2>"$SANDBOX/compare.err") || compare_rc=$? + echo "$compare_stdout" + echo "--- stderr ---" + cat "$SANDBOX/compare.err" + [ "$compare_rc" -eq 1 ] || fail "unresolved 'compare' should exit 1, got $compare_rc" + assert_not_contains "$compare_stdout" "Usage:" "unresolved 'compare' should not print a Usage dump" + printf '%s\n' "$compare_stdout" | cut -f1 | grep -qx "sub" \ + || fail "unresolved 'compare' should list 'sub' in the first column" + if ! grep -Eq "fzf is not installed|No patch detected" "$SANDBOX/compare.err"; then + fail "unresolved 'compare' should explain why it could not pick a patch" + fi + log_success "unresolved 'compare' prints rows and exits 1" + + # --- diffTool template substitution uses repo-relative paths + log_header "019: cross.diffTool {left}/{right} template substitution" + git config cross.diffTool 'echo TOOL {left} {right}' + + tool_out=$("$GO_BIN" compare sub 2>&1 || true) + echo "$tool_out" + printf '%s\n' "$tool_out" | grep -Eq "TOOL \.cross/worktrees/up_[0-9a-f]+ sub" \ + || fail "expected 'TOOL .cross/worktrees/up_ sub', got: $tool_out" + assert_not_contains "$tool_out" "$SANDBOX" \ + "template placeholders must be substituted with repo-relative paths" + + alias_out=$("$GO_BIN" cmp sub 2>&1 || true) + echo "$alias_out" + assert_contains "$alias_out" "TOOL .cross/worktrees/up_" "the 'cmp' alias should behave like 'compare'" + git config --unset cross.diffTool || true + log_success "diffTool template substitution verified" +fi + +# -------------------------------------------------------------- Just section +if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command -v just >/dev/null 2>&1; then + cd "$PROJECT_ROOT" + setup_sandbox + cd "$SANDBOX" + + log_header "019: whole-repo patch via Just/Fish" + upstream_path=$(create_upstream "whole-repo-just") + pushd "$upstream_path" >/dev/null + mkdir -p docs + echo "docs v1" > docs/guide.md + git add docs/guide.md + git commit -m "Add docs" -q + popd >/dev/null + upstream_url="file://$upstream_path" + + just cross use up "$upstream_url" >/dev/null + just cross patch "up:." ./sub >/dev/null + assert_file_exists "sub/README.md" + + pushd "$upstream_path" >/dev/null + echo "docs v2 upstream, longer content" > docs/guide.md + echo "brand new" > new-file.txt + git add -A + git commit -m "Upstream v2" -q + popd >/dev/null + + update_output=$(just cross update 2>&1) + echo "$update_output" + assert_not_contains "$update_output" "differs from upstream" \ + "Just update falsely reported local edits for a whole-repo patch (.git leak)" + assert_grep "sub/docs/guide.md" "docs v2" + assert_file_exists "sub/new-file.txt" + + status_output=$(just cross status 2>&1) + echo "$status_output" + sub_line=$(printf '%s\n' "$status_output" | grep -E '(^|[[:space:]])sub([[:space:]]|$)' | head -n 1) + [ -n "$sub_line" ] || fail "Just status did not list the whole-repo patch 'sub'" + assert_contains "$sub_line" "Clean" "Just status reported a non-Clean diff for a synced whole-repo patch" + + echo "local docs tweak" >> sub/docs/guide.md + diff_output=$(just cross diff sub 2>&1 || true) + echo "$diff_output" + assert_contains "$diff_output" "local docs tweak" + assert_not_contains "$diff_output" ".git" "Just diff must not include the worktree .git pointer file" + + nofzf_path=$(make_path_without_fzf "$SANDBOX/no-fzf-bin") + compare_rc=0 + compare_output=$(PATH="$nofzf_path" just cross compare 2>&1) || compare_rc=$? + echo "$compare_output" + [ "$compare_rc" -eq 1 ] || fail "Just unresolved 'compare' should exit 1, got $compare_rc" + assert_not_contains "$compare_output" "Usage:" "Just unresolved 'compare' should not print a Usage dump" + if ! printf '%s\n' "$compare_output" | awk -F'\t' '$1=="sub"{found=1} END{exit found?0:1}'; then + fail "Just unresolved 'compare' should print local_pathworktree rows" + fi + if ! printf '%s\n' "$compare_output" | grep -Eq "fzf is not installed|No patch detected"; then + fail "Just unresolved 'compare' should explain why it could not pick a patch" + fi + log_success "Just whole-repo patch behavior verified" +else + echo "SKIP: fish and/or jq/just unavailable; skipping Just whole-repo assertions" +fi + +echo "Test 019 passed!" diff --git a/test/020_help_groups.sh b/test/020_help_groups.sh new file mode 100755 index 000000000..1b90e435f --- /dev/null +++ b/test/020_help_groups.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# Test 020: grouped `git cross --help` output (Go CLI). +# +# The help must render the three command groups and list every visible +# command exactly once, under the right group. +source "$(dirname "$0")/common.sh" + +PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +GO_BIN="$(ensure_go_bin "$PROJECT_ROOT")" + +if [ -z "$GO_BIN" ]; then + echo "SKIP: Go CLI unavailable; skipping grouped help test" + exit 0 +fi + +cd "$PROJECT_ROOT" + +help_output=$("$GO_BIN" --help 2>&1) +echo "$help_output" + +# Print the body of one help section (lines between the title and the next +# section header such as "Flags:"). +section_body() { + printf '%s\n' "$help_output" | awk -v title="$1" ' + $0 == title { inside = 1; next } + inside && /^[A-Za-z][A-Za-z &-]*:$/ { exit } + inside { print } + ' +} + +log_header "020: group titles are present" +for title in "Repository:" "Inspect & Navigate:" "Patch Lifecycle:"; do + assert_contains "$help_output" "$title" "help is missing the '$title' group" +done +log_success "group titles present" + +log_header "020: commands are listed under their group" +repo_section=$(section_body "Repository:") +inspect_section=$(section_body "Inspect & Navigate:") +patches_section=$(section_body "Patch Lifecycle:") + +for cmd in compare init list status update; do + printf '%s\n' "$repo_section" | grep -Eq "^ ${cmd}([[:space:]]|$)" \ + || fail "'$cmd' should be listed under 'Repository:'" +done +for cmd in cd wt diff; do + printf '%s\n' "$inspect_section" | grep -Eq "^ ${cmd}([[:space:]]|$)" \ + || fail "'$cmd' should be listed under 'Inspect & Navigate:'" +done +for cmd in use patch remove prune; do + printf '%s\n' "$patches_section" | grep -Eq "^ ${cmd}([[:space:]]|$)" \ + || fail "'$cmd' should be listed under 'Patch Lifecycle:'" +done +log_success "commands grouped correctly" + +log_header "020: every visible command appears exactly once" +for cmd in compare init list status update cd wt diff use patch remove prune; do + count=$(printf '%s\n' "$help_output" | grep -cE "^ ${cmd}([[:space:]]|$)") + [ "$count" -eq 1 ] || fail "command '$cmd' should appear exactly once in help (found $count)" +done +assert_not_contains "$help_output" "Additional Commands:" \ + "every visible command must have a GroupID (none may fall into 'Additional Commands:')" +if printf '%s\n' "$help_output" | grep -Eq '^ cmp([[:space:]]|$)'; then + fail "the 'cmp' alias must not get its own help row" +fi +log_success "all visible commands listed once" + +log_header "020: -h still prints the grouped help" +short_help=$("$GO_BIN" -h 2>&1) || fail "-h should exit 0" +assert_contains "$short_help" "Repository:" +assert_contains "$short_help" "Inspect & Navigate:" +assert_contains "$short_help" "Patch Lifecycle:" +log_success "-h works" + +echo "Test 020 passed!" diff --git a/test/021_fzf_diff_compare.sh b/test/021_fzf_diff_compare.sh new file mode 100755 index 000000000..3f2c6a829 --- /dev/null +++ b/test/021_fzf_diff_compare.sh @@ -0,0 +1,200 @@ +#!/usr/bin/env bash +# Test 021: fzf selection ladder for `diff` / `compare`. +# +# Contract: +# inside a patched directory -> CWD auto-detect (fzf is never consulted) +# outside, fzf available -> interactive selection, then act on it +# outside, fzf missing -> rows + hint, exit 1 +source "$(dirname "$0")/common.sh" + +PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +GO_BIN="$(ensure_go_bin "$PROJECT_ROOT")" + +# Scratch space for the PATH toy-boxes (kept outside the repo). +TEST_TMP=$(mktemp -d) + +# Make sure the "no fzf" PATH is computed before any shim is added. +nofzf_path=$(make_path_without_fzf "$TEST_TMP/no-fzf-bin") + +# An fzf stand-in: swallows the candidate list and prints FZF_SELECT +# (printf %b expands the \t used in the row payloads). +fzf_shim_dir="$TEST_TMP/fzf-shim-bin" +mkdir -p "$fzf_shim_dir" +cat > "$fzf_shim_dir/fzf" <<'EOF' +#!/usr/bin/env bash +cat >/dev/null +if [ -n "${FZF_SELECT:-}" ]; then + printf '%b\n' "$FZF_SELECT" + exit 0 +fi +exit 130 +EOF +chmod +x "$fzf_shim_dir/fzf" + +# ---------------------------------------------------------------- Go section +if [ -n "$GO_BIN" ]; then + cd "$PROJECT_ROOT" + setup_sandbox + cd "$SANDBOX" + + upstream_path=$(create_upstream "fzf-demo") + pushd "$upstream_path" >/dev/null + mkdir -p src/alpha src/beta + echo "alpha v1" > src/alpha/alpha.txt + echo "beta v1" > src/beta/beta.txt + git add src + git commit -m "Add alpha and beta" -q + popd >/dev/null + upstream_url="file://$upstream_path" + + "$GO_BIN" use upstream "$upstream_url" >/dev/null + "$GO_BIN" patch upstream:src/alpha vendor/alpha >/dev/null + "$GO_BIN" patch upstream:src/beta vendor/beta >/dev/null + echo "local alpha change" >> vendor/alpha/alpha.txt + echo "local beta change" >> vendor/beta/beta.txt + + # --- fzf absent: rows + hint, exit 1 + log_header "021: Go diff/compare without fzf print rows and exit 1" + diff_rc=0 + diff_out=$(PATH="$nofzf_path" "$GO_BIN" diff 2>"$SANDBOX/diff.err") || diff_rc=$? + echo "$diff_out" + echo "--- stderr ---" + cat "$SANDBOX/diff.err" + [ "$diff_rc" -eq 1 ] || fail "Go diff without fzf should exit 1, got $diff_rc" + assert_not_contains "$diff_out" "Usage:" "diff should print rows, not a Usage dump" + printf '%s\n' "$diff_out" | cut -f1 | grep -qx "vendor/alpha" \ + || fail "diff rows missing 'vendor/alpha'" + printf '%s\n' "$diff_out" | cut -f1 | grep -qx "vendor/beta" \ + || fail "diff rows missing 'vendor/beta'" + assert_contains "$(cat "$SANDBOX/diff.err")" "fzf is not installed" \ + "diff should explain that fzf is missing" + + compare_rc=0 + compare_out=$(PATH="$nofzf_path" "$GO_BIN" compare 2>"$SANDBOX/compare.err") || compare_rc=$? + echo "$compare_out" + [ "$compare_rc" -eq 1 ] || fail "Go compare without fzf should exit 1, got $compare_rc" + assert_not_contains "$compare_out" "Usage:" "compare should print rows, not a Usage dump" + printf '%s\n' "$compare_out" | cut -f1 | grep -qx "vendor/alpha" \ + || fail "compare rows missing 'vendor/alpha'" + assert_contains "$(cat "$SANDBOX/compare.err")" "fzf is not installed" \ + "compare should explain that fzf is missing" + log_success "fzf-missing fallback verified" + + # --- fzf shim: selection drives diff/compare + log_header "021: Go diff/compare operate on the fzf selection" + sel_alpha='upstream\t.\tvendor/alpha' + sel_beta='upstream\t.\tvendor/beta' + + out=$(FZF_SELECT="$sel_alpha" PATH="$fzf_shim_dir:$PATH" "$GO_BIN" diff 2>&1) || true + echo "$out" + assert_contains "$out" "local alpha change" "diff should operate on the selected alpha patch" + assert_not_contains "$out" "local beta change" "diff should not include the unselected beta patch" + + out=$(FZF_SELECT="$sel_beta" PATH="$fzf_shim_dir:$PATH" "$GO_BIN" diff 2>&1) || true + echo "$out" + assert_contains "$out" "local beta change" "diff should operate on the selected beta patch" + assert_not_contains "$out" "local alpha change" "diff should not include the unselected alpha patch" + + git config cross.diffTool 'echo TOOL {left} {right}' + out=$(FZF_SELECT="$sel_alpha" PATH="$fzf_shim_dir:$PATH" "$GO_BIN" compare 2>&1) || true + echo "$out" + assert_contains "$out" "TOOL .cross/worktrees/upstream_" "compare should run the tool on the selected worktree" + assert_contains "$out" "vendor/alpha" "compare should run the tool on the selected local path" + assert_not_contains "$out" "vendor/beta" "compare should not touch the unselected patch" + + out=$(FZF_SELECT="$sel_beta" PATH="$fzf_shim_dir:$PATH" "$GO_BIN" cmp 2>&1) || true + echo "$out" + assert_contains "$out" "vendor/beta" "the 'cmp' alias should use the fzf selection" + assert_not_contains "$out" "vendor/alpha" + git config --unset cross.diffTool || true + log_success "fzf selection drives diff/compare" + + # --- inside a patched dir: CWD auto-detect, no fzf needed + log_header "021: CWD auto-detect still wins inside a patch directory" + pushd vendor/alpha >/dev/null + out=$(PATH="$nofzf_path" "$GO_BIN" diff 2>&1) || true + echo "$out" + assert_contains "$out" "local alpha change" "diff inside vendor/alpha should auto-detect" + assert_not_contains "$out" "local beta change" + assert_not_contains "$out" "fzf is not installed" "auto-detect must not consult fzf" + + git config cross.diffTool 'echo TOOL {left} {right}' + out=$(PATH="$nofzf_path" "$GO_BIN" compare 2>&1) || true + echo "$out" + assert_contains "$out" "TOOL .cross/worktrees/upstream_" "compare inside vendor/alpha should auto-detect" + assert_contains "$out" "vendor/alpha" + git config --unset cross.diffTool || true + popd >/dev/null + log_success "auto-detect verified" +fi + +# -------------------------------------------------------------- Just section +if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command -v just >/dev/null 2>&1; then + cd "$PROJECT_ROOT" + setup_sandbox + cd "$SANDBOX" + + upstream_path=$(create_upstream "fzf-demo-just") + pushd "$upstream_path" >/dev/null + mkdir -p src/alpha src/beta + echo "alpha v1" > src/alpha/alpha.txt + echo "beta v1" > src/beta/beta.txt + git add src + git commit -m "Add alpha and beta" -q + popd >/dev/null + upstream_url="file://$upstream_path" + + just cross use upstream "$upstream_url" >/dev/null + just cross patch upstream:src/alpha vendor/alpha >/dev/null + just cross patch upstream:src/beta vendor/beta >/dev/null + echo "local alpha change" >> vendor/alpha/alpha.txt + echo "local beta change" >> vendor/beta/beta.txt + + log_header "021: Just diff/compare without fzf print rows and exit 1" + nofzf_path=$(make_path_without_fzf "$SANDBOX/no-fzf-bin") + diff_rc=0 + diff_out=$(PATH="$nofzf_path" just cross diff 2>&1) || diff_rc=$? + echo "$diff_out" + [ "$diff_rc" -eq 1 ] || fail "Just diff without fzf should exit 1, got $diff_rc" + assert_not_contains "$diff_out" "Usage:" "Just diff should not print a Usage dump" + if ! printf '%s\n' "$diff_out" | awk -F'\t' '$1=="vendor/alpha"{found=1} END{exit found?0:1}'; then + fail "Just diff rows missing 'vendor/alpha'" + fi + assert_contains "$diff_out" "fzf is not installed" "Just diff should explain that fzf is missing" + + compare_rc=0 + compare_out=$(PATH="$nofzf_path" just cross compare 2>&1) || compare_rc=$? + echo "$compare_out" + [ "$compare_rc" -eq 1 ] || fail "Just compare without fzf should exit 1, got $compare_rc" + assert_contains "$compare_out" "fzf is not installed" "Just compare should explain that fzf is missing" + + log_header "021: Just diff/compare operate on the fzf selection" + git config cross.diffTool 'echo TOOL {left} {right}' + wt_alpha=$(jq -r '.patches[] | select(.local_path == "vendor/alpha") | .worktree' .cross/metadata.json) + sel_alpha="vendor/alpha\t$wt_alpha" + out=$(FZF_SELECT="$sel_alpha" PATH="$fzf_shim_dir:$PATH" just cross diff 2>&1) || true + echo "$out" + assert_contains "$out" "local alpha change" "Just diff should operate on the selected alpha patch" + assert_not_contains "$out" "local beta change" "Just diff should not include the unselected beta patch" + + out=$(FZF_SELECT="$sel_alpha" PATH="$fzf_shim_dir:$PATH" just cross compare 2>&1) || true + echo "$out" + assert_contains "$out" "vendor/alpha" "Just compare should resolve the selected local path" + assert_contains "$out" "TOOL .cross/worktrees/upstream_" "Just compare should run the tool on the selected worktree" + git config --unset cross.diffTool || true + + log_header "021: Just CWD auto-detect inside a patch directory" + pushd vendor/alpha >/dev/null + out=$(PATH="$nofzf_path" just cross diff 2>&1) || true + echo "$out" + assert_contains "$out" "local alpha change" + assert_not_contains "$out" "local beta change" + assert_not_contains "$out" "fzf is not installed" + popd >/dev/null + log_success "Just fzf ladder verified" +else + echo "SKIP: fish and/or jq/just unavailable; skipping Just fzf assertions" +fi + +rm -rf "$TEST_TMP" 2>/dev/null || true +echo "Test 021 passed!" diff --git a/test/023_localpath_normalization.sh b/test/023_localpath_normalization.sh new file mode 100755 index 000000000..c445d7320 --- /dev/null +++ b/test/023_localpath_normalization.sh @@ -0,0 +1,187 @@ +#!/usr/bin/env bash +# Test 023: local_path normalization (`./sub` must behave like `sub`). +# +# Regression: `patch :./sub` stored "./sub" in metadata, so CWD +# auto-detection, compare/diff/cd/status and `remove ./sub` failed to match. +source "$(dirname "$0")/common.sh" + +PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +GO_BIN="$(ensure_go_bin "$PROJECT_ROOT")" + +assert_metadata_normalized() { + local meta=".cross/metadata.json" + jq -r '.patches[].local_path' "$meta" | grep -qx "sub" || fail "metadata missing normalized local_path 'sub'" + jq -r '.patches[].local_path' "$meta" | grep -qx "sub2" || fail "metadata missing normalized local_path 'sub2'" + if jq -e '.patches[] | select(.local_path | startswith("./"))' "$meta" >/dev/null 2>&1; then + fail "metadata still contains a './' prefixed local_path" + jq -r '.patches[].local_path' "$meta" | sed 's/^/ /' >&2 + fi +} + +assert_one_abs_path() { + local label=$1 + local output=$2 + local expected=$3 + local line_count + line_count=$(printf '%s\n' "$output" | sed '/^$/d' | wc -l | tr -d ' ') + [ "$line_count" -eq 1 ] || fail "$label: expected exactly one line of output, got $line_count: $output" + case "$output" in + /*) ;; + *) fail "$label: expected an absolute path, got: $output" ;; + esac + assert_not_contains "$output" "Opening shell" "$label: must not mention opening a shell" + assert_not_contains "$output" "clipboard" "$label: must not copy to the clipboard" + [ "$output" = "$expected" ] || fail "$label: expected '$expected', got '$output'" +} + +# ---------------------------------------------------------------- Go section +if [ -n "$GO_BIN" ]; then + cd "$PROJECT_ROOT" + setup_sandbox + cd "$SANDBOX" + + upstream_path=$(create_upstream "normalize-demo") + pushd "$upstream_path" >/dev/null + mkdir -p pkg + echo "root v1" > root.txt + echo "pkg v1" > pkg/pkg.txt + git add root.txt pkg/pkg.txt + git commit -m "Add content" -q + popd >/dev/null + upstream_url="file://$upstream_path" + + log_header "023: patch with './' prefixed local paths (Go)" + "$GO_BIN" use up "$upstream_url" >/dev/null + "$GO_BIN" patch "up:main:." ./sub >/dev/null + "$GO_BIN" patch "up:main:pkg" ./sub2 >/dev/null + assert_dir_exists "sub" + assert_dir_exists "sub2" + assert_metadata_normalized + log_success "metadata stores local_path without './'" + + git config cross.diffTool 'echo TOOL {left} {right}' + + log_header "023: compare/diff/cd/status resolve from inside ./sub" + pushd sub >/dev/null + out=$("$GO_BIN" compare 2>&1) || fail "compare inside a './sub' patch should resolve" + echo "$out" + assert_contains "$out" "TOOL .cross/worktrees/up_" "compare inside ./sub should run the diff tool" + assert_not_contains "$out" "patch not found" + + echo "local sub change" >> root.txt + out=$("$GO_BIN" diff 2>&1) || true + echo "$out" + assert_contains "$out" "local sub change" "diff inside ./sub should auto-detect the patch" + assert_not_contains "$out" "patch not found" + + expected=$(pwd -P) + out=$("$GO_BIN" cd sub 2>/dev/null) || fail "cd sub inside a './sub' patch should resolve" + assert_one_abs_path "cd sub inside ./sub" "$out" "$expected" + + out=$("$GO_BIN" status 2>&1) || true + echo "$out" + assert_contains "$out" "sub" "status should list the normalized local_path" + popd >/dev/null + + log_header "023: compare/diff/cd resolve from inside ./sub2" + pushd sub2 >/dev/null + out=$("$GO_BIN" compare 2>&1) || fail "compare inside a './sub2' patch should resolve" + assert_contains "$out" "TOOL .cross/worktrees/up_" + assert_not_contains "$out" "patch not found" + echo "local sub2 change" >> pkg.txt + out=$("$GO_BIN" diff 2>&1) || true + assert_contains "$out" "local sub2 change" + expected=$(pwd -P) + out=$("$GO_BIN" cd sub2 2>/dev/null) || fail "cd sub2 inside a './sub2' patch should resolve" + assert_one_abs_path "cd sub2 inside ./sub2" "$out" "$expected" + popd >/dev/null + + log_header "023: explicit './' path arguments resolve (Go)" + out=$("$GO_BIN" compare ./sub 2>&1) || fail "compare ./sub from the repo root should resolve" + assert_contains "$out" "TOOL .cross/worktrees/up_" + + out=$("$GO_BIN" diff ./sub 2>&1) || true + assert_contains "$out" "local sub change" + + git config --unset cross.diffTool || true + + log_header "023: remove ./sub2 resolves the normalized entry" + "$GO_BIN" remove ./sub2 >/dev/null 2>&1 || fail "remove ./sub2 should resolve the stored 'sub2' path" + if [ -d "sub2" ]; then + fail "remove ./sub2 left the sub2 directory behind" + fi + if jq -e '.patches[] | select(.local_path == "sub2")' .cross/metadata.json >/dev/null 2>&1; then + fail "remove ./sub2 left the entry in metadata" + fi + if grep -q "sub2" Crossfile 2>/dev/null; then + fail "remove ./sub2 left the entry in Crossfile" + fi + log_success "normalized './' arguments resolve" +fi + +# -------------------------------------------------------------- Just section +if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command -v just >/dev/null 2>&1; then + cd "$PROJECT_ROOT" + setup_sandbox + cd "$SANDBOX" + + upstream_path=$(create_upstream "normalize-demo-just") + pushd "$upstream_path" >/dev/null + mkdir -p pkg + echo "root v1" > root.txt + echo "pkg v1" > pkg/pkg.txt + git add root.txt pkg/pkg.txt + git commit -m "Add content" -q + popd >/dev/null + upstream_url="file://$upstream_path" + + log_header "023: patch with './' prefixed local paths (Just/Fish)" + just cross use up "$upstream_url" >/dev/null + just cross patch "up:main:." ./sub >/dev/null + just cross patch "up:main:pkg" ./sub2 >/dev/null + assert_metadata_normalized + log_success "Just metadata stores local_path without './'" + + log_header "023: Just compare/diff/cd resolve from inside ./sub" + git config cross.diffTool 'echo TOOL {left} {right}' + pushd sub >/dev/null + echo "local sub change" >> root.txt + out=$(just cross compare 2>&1) || fail "Just compare inside './sub' should resolve" + echo "$out" + assert_contains "$out" "TOOL .cross/worktrees/up_" "Just compare inside ./sub should run the diff tool" + assert_not_contains "$out" "patch not found" + + out=$(just cross diff 2>&1) || true + echo "$out" + assert_contains "$out" "local sub change" "Just diff inside ./sub should auto-detect the patch" + assert_not_contains "$out" "patch not found" + + expected=$(pwd -P) + out=$(just cross cd sub 2>/dev/null) || fail "Just cd sub inside './sub' should resolve" + assert_one_abs_path "Just cd sub inside ./sub" "$out" "$expected" + popd >/dev/null + + pushd sub2 >/dev/null + echo "local sub2 change" >> pkg.txt + out=$(just cross compare 2>&1) || fail "Just compare inside './sub2' should resolve" + assert_contains "$out" "TOOL .cross/worktrees/up_" + assert_not_contains "$out" "patch not found" + out=$(just cross diff 2>&1) || true + assert_contains "$out" "local sub2 change" + popd >/dev/null + git config --unset cross.diffTool || true + + log_header "023: Just remove ./sub2 resolves the normalized entry" + just cross remove ./sub2 >/dev/null 2>&1 || fail "Just remove ./sub2 should resolve the stored 'sub2' path" + if [ -d "sub2" ]; then + fail "Just remove ./sub2 left the sub2 directory behind" + fi + if jq -e '.patches[] | select(.local_path == "sub2")' .cross/metadata.json >/dev/null 2>&1; then + fail "Just remove ./sub2 left the entry in metadata" + fi + log_success "Just normalization verified" +else + echo "SKIP: fish and/or jq/just unavailable; skipping Just normalization assertions" +fi + +echo "Test 023 passed!" diff --git a/test/common.sh b/test/common.sh index cae8d003b..0e320307a 100644 --- a/test/common.sh +++ b/test/common.sh @@ -61,6 +61,10 @@ if ! command -v just >/dev/null; then # PATH adjustment for development environm done fi +# Justfile.cross requires SHELL; direct `bash test/NNN.sh` invocations may not +# inherit it (run-all.sh is normally launched from a login shell or `just`). +export SHELL="${SHELL:-/bin/bash}" + setup_sandbox() { basepth="${1:-$(mktemp -d)}" cleanup=${2:-true} @@ -149,6 +153,82 @@ assert_grep() { fi } +# Assert that a string (usually captured command output) contains a literal +# substring. Keeps multiline output out of grep's argument parsing. +assert_contains() { + local haystack=$1 + local needle=$2 + local message=${3:-"expected output to contain: $needle"} + if ! printf '%s' "$haystack" | grep -qF -- "$needle"; then + log_error "$message" + printf '%s\n' "$haystack" >&2 + exit 1 + fi +} + +# Assert that a string does NOT contain a literal substring. +assert_not_contains() { + local haystack=$1 + local needle=$2 + local message=${3:-"expected output to NOT contain: $needle"} + if printf '%s' "$haystack" | grep -qF -- "$needle"; then + log_error "$message" + printf '%s\n' "$haystack" >&2 + exit 1 + fi +} + +# Build (or reuse) the Go CLI and print its path on stdout. +# Prints nothing when Go is unavailable or the binary cannot run, so callers +# can skip Go-specific assertions (same pattern as test/009_go_cli.sh). +ensure_go_bin() { + local repo_root=${1:-${REPO_ROOT:-$(pwd)}} + local go_bin="$repo_root/src-go/git-cross-go" + # Rebuild when the source is newer than the cached binary. + if [ -f "$go_bin" ] && [ "$repo_root/src-go/main.go" -nt "$go_bin" ]; then + rm -f "$go_bin" + fi + if [ ! -f "$go_bin" ]; then + if ! command -v go >/dev/null 2>&1; then + return 0 + fi + # A stale vendor dir breaks `go build -mod=mod` (inconsistent vendoring). + rm -rf "$repo_root/src-go/vendor" 2>/dev/null || true + ( cd "$repo_root/src-go" && CGO_ENABLED=0 go build -mod=mod -tags purego -o git-cross-go main.go ) >/dev/null 2>&1 || return 0 + fi + if ! "$go_bin" --version >/dev/null 2>&1 && ! "$go_bin" --help >/dev/null 2>&1; then + return 0 + fi + printf '%s\n' "$go_bin" +} + +# Print a PATH equivalent to the current one with no `fzf` resolvable. +# +# A symlink farm is used because a directory cannot "hide" a binary that lives +# in another PATH entry. This makes the "fzf is not installed" fallbacks +# testable deterministically, even on hosts/CI images that ship fzf. +make_path_without_fzf() { + local farm=$1 + local IFS=: + local dir entry base + if [ -z "$farm" ]; then + return 1 + fi + mkdir -p "$farm" + for dir in $PATH; do + [ -d "$dir" ] || continue + [ "$dir" = "$farm" ] && continue + for entry in "$dir"/*; do + [ -f "$entry" ] && [ -x "$entry" ] || continue + base=${entry##*/} + [ "$base" = "fzf" ] && continue + [ -e "$farm/$base" ] && continue + ln -s "$entry" "$farm/$base" 2>/dev/null || true + done + done + printf '%s\n' "$farm" +} + cleanup() { if [ "${CLEANUP:-true}" = true ] && [ -n "${SANDBOX:-}" ] && [ -d "$SANDBOX" ]; then rm -rf "$SANDBOX" From 31db576b32bcd376f4e89f36b271b5d803b0dd58 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 19:20:37 +0100 Subject: [PATCH 04/22] test: tolerate builtin help, cover no-path cd/wt CWD auto-detect; matrix notes 021 Just variant --- AGENTS.md | 4 ++-- test/017_cd_wt_fix.sh | 12 ++++++++++++ test/020_help_groups.sh | 11 +++++++++-- test/023_localpath_normalization.sh | 14 ++++++++++++++ 4 files changed, 37 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1199b9fc2..d7566f1b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,7 +102,7 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 | `update` (upstream/local edit behavior) | 004 | 009, 018, 019 | | `diff` (basic) | 003 | 009 | | `diff` (context-aware CWD) | 003, 016 | 016, 021 | -| `diff` (no path: fzf / rows ladder) | -- | 021 | +| `diff` (no path: fzf / rows ladder) | 021‡ | 021 | | `diff` (relative paths) | 003 | -- | | `list` (table) | -- | 009, 014 | | `list --raw` / `--no-header` | -- | 009, 014 | @@ -124,7 +124,7 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 - **Just update behavior**: requires Fish to be installed; run `test/004_update.sh` in an environment with Fish. - **Just `list` output**: no dedicated test; `test/019` exercises patch row listings when Fish is available. -- **Just variants**: `test/019` and `test/023` include Fish-guarded variants that skip when `fish` is absent; `test/020` and `test/021` are Go-only. CI should keep Fish present to avoid silent gaps. +- **Just variants**: `test/019`, `test/021`, `test/023`, and `test/017` include Fish-guarded variants that skip when `fish` is absent; `test/020` is Go-only (grouped help is a Go CLI rendering concern). CI should keep Fish present to avoid silent gaps. ## Agent Workflow diff --git a/test/017_cd_wt_fix.sh b/test/017_cd_wt_fix.sh index 62f738312..08ad8f29d 100755 --- a/test/017_cd_wt_fix.sh +++ b/test/017_cd_wt_fix.sh @@ -88,6 +88,18 @@ if [ -n "$GO_BIN" ]; then "Go wt fallback should say fzf is missing" log_success "Go fzf-missing fallback verified" + log_header "017: Go no-path cd/wt auto-detect from CWD" + pushd vendor/src >/dev/null + out=$(PATH="$nofzf_path" "$GO_BIN" cd 2>/dev/null) \ + || fail "Go cd without a path inside a patch should auto-detect" + assert_one_abs_path "Go cd (CWD auto-detect)" "$out" "$local_abs" + + out=$(PATH="$nofzf_path" "$GO_BIN" wt 2>/dev/null) \ + || fail "Go wt without a path inside a patch should auto-detect" + assert_one_abs_path "Go wt (CWD auto-detect)" "$out" "$wt_abs" + popd >/dev/null + log_success "Go CWD auto-detect verified" + log_header "017: Go fzf selection prints the selected path" shim_dir="$SANDBOX/fzf-shim-bin" mkdir -p "$shim_dir" diff --git a/test/020_help_groups.sh b/test/020_help_groups.sh index 1b90e435f..38ad049af 100755 --- a/test/020_help_groups.sh +++ b/test/020_help_groups.sh @@ -58,8 +58,15 @@ for cmd in compare init list status update cd wt diff use patch remove prune; do count=$(printf '%s\n' "$help_output" | grep -cE "^ ${cmd}([[:space:]]|$)") [ "$count" -eq 1 ] || fail "command '$cmd' should appear exactly once in help (found $count)" done -assert_not_contains "$help_output" "Additional Commands:" \ - "every visible command must have a GroupID (none may fall into 'Additional Commands:')" +# Cobra still renders the auto-generated 'help' (and, if enabled, 'completion') +# command under "Additional Commands:". Tolerate those built-ins, but no +# documented command may end up ungrouped there. +additional_section=$(section_body "Additional Commands:") +for cmd in compare init list status update cd wt diff use patch remove prune; do + if printf '%s\n' "$additional_section" | grep -Eq "^ ${cmd}([[:space:]]|$)"; then + fail "'$cmd' must not fall into 'Additional Commands:' (missing GroupID)" + fi +done if printf '%s\n' "$help_output" | grep -Eq '^ cmp([[:space:]]|$)'; then fail "the 'cmp' alias must not get its own help row" fi diff --git a/test/023_localpath_normalization.sh b/test/023_localpath_normalization.sh index c445d7320..0ccd071e2 100755 --- a/test/023_localpath_normalization.sh +++ b/test/023_localpath_normalization.sh @@ -60,6 +60,9 @@ if [ -n "$GO_BIN" ]; then log_success "metadata stores local_path without './'" git config cross.diffTool 'echo TOOL {left} {right}' + nofzf_path=$(make_path_without_fzf "$SANDBOX/no-fzf-bin") + wt_sub=$(jq -r '.patches[] | select(.local_path == "sub") | .worktree' .cross/metadata.json) + wt_sub_abs=$(cd "$wt_sub" && pwd -P) log_header "023: compare/diff/cd/status resolve from inside ./sub" pushd sub >/dev/null @@ -78,6 +81,14 @@ if [ -n "$GO_BIN" ]; then out=$("$GO_BIN" cd sub 2>/dev/null) || fail "cd sub inside a './sub' patch should resolve" assert_one_abs_path "cd sub inside ./sub" "$out" "$expected" + # No path at all: CWD auto-detect must win before fzf is consulted. + out=$(PATH="$nofzf_path" "$GO_BIN" cd 2>/dev/null) \ + || fail "cd without a path inside ./sub should auto-detect from CWD" + assert_one_abs_path "cd (CWD auto-detect) inside ./sub" "$out" "$expected" + out=$(PATH="$nofzf_path" "$GO_BIN" wt 2>/dev/null) \ + || fail "wt without a path inside ./sub should auto-detect from CWD" + assert_one_abs_path "wt (CWD auto-detect) inside ./sub" "$out" "$wt_sub_abs" + out=$("$GO_BIN" status 2>&1) || true echo "$out" assert_contains "$out" "sub" "status should list the normalized local_path" @@ -94,6 +105,9 @@ if [ -n "$GO_BIN" ]; then expected=$(pwd -P) out=$("$GO_BIN" cd sub2 2>/dev/null) || fail "cd sub2 inside a './sub2' patch should resolve" assert_one_abs_path "cd sub2 inside ./sub2" "$out" "$expected" + out=$(PATH="$nofzf_path" "$GO_BIN" cd 2>/dev/null) \ + || fail "cd without a path inside ./sub2 should auto-detect from CWD" + assert_one_abs_path "cd (CWD auto-detect) inside ./sub2" "$out" "$expected" popd >/dev/null log_header "023: explicit './' path arguments resolve (Go)" From 9aa6fd72090ed3a70d6b6210e7ff22c3433469f7 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 19:23:27 +0100 Subject: [PATCH 05/22] fix(just): apply cd/wt resolution ladder delta (CWD auto-detect) lost in merge --- Justfile.cross | 82 ++++++++++++++++++++++++++++++++++---------------- 1 file changed, 56 insertions(+), 26 deletions(-) diff --git a/Justfile.cross b/Justfile.cross index c8fd92f67..dd4fe98c9 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -897,45 +897,75 @@ worktree path="": [no-cd] wt path="": #!/usr/bin/env fish - if test -n "{{path}}" - set -l ctx (just cross _resolve_context2 "{{path}}" 2>/dev/null) + set -l resolved_path "{{path}}" + # Explicit path: make absolute and ./-prefixed paths repo-relative first + if test -n "$resolved_path" + if test -e "$resolved_path" + set -l dir "$resolved_path" + test -d "$dir"; or set dir (dirname "$dir") + # git -C: avoid fish's `cd` in a command substitution changing our cwd + set resolved_path (git -C "$dir" rev-parse --show-prefix 2>/dev/null | sed 's,/$,,') + else + set resolved_path (string replace -r '^\./' '' -- "$resolved_path") + end + end + # Resolution ladder: path/CWD auto-detect -> fzf selection -> rows + exit 1 + set -l ctx (just cross _resolve_context2 "$resolved_path" 2>/dev/null) + if test (count $ctx) -eq 0 + if test -z "$resolved_path" + if not command -v fzf >/dev/null 2>&1 + just cross _list_patches "fzf is not installed, cd manually. Destinations, columns local_path TAB worktree" >&2 + exit 1 + end + set -l sel (just cross _select_patch patch) + test -z "$sel"; and exit 0 + set resolved_path "$sel" + set ctx (just cross _resolve_context2 "$sel" 2>/dev/null) + end if test (count $ctx) -eq 0 - just cross _list_patches "No patch detected, available patches, columns local_path TAB worktree" + just cross _list_patches "No patch detected, available patches, columns local_path TAB worktree" >&2 exit 1 end - printf '%s\n' $ctx | source - echo "{{REPO_DIR}}/$worktree" - else if not command -v fzf >/dev/null 2>&1 - just cross _list_patches "fzf is not installed, cd manually. Destinations, columns local_path TAB worktree" - exit 1 - else - set -l row (just cross _list_patches | fzf --height 40% --select-1 --exit-0 --prompt "Select patch (wt)> ") - test -z "$row"; and exit 0 - set -l cols (string split \t -- $row) - echo "{{REPO_DIR}}/$cols[2]" end + printf '%s\n' $ctx | source + echo "{{REPO_DIR}}/$worktree" # Print a patch local_path to cd into (use: cd (just cross cd [path])) [no-cd] cd path="": #!/usr/bin/env fish - if test -n "{{path}}" - set -l ctx (just cross _resolve_context2 "{{path}}" 2>/dev/null) + set -l resolved_path "{{path}}" + # Explicit path: make absolute and ./-prefixed paths repo-relative first + if test -n "$resolved_path" + if test -e "$resolved_path" + set -l dir "$resolved_path" + test -d "$dir"; or set dir (dirname "$dir") + # git -C: avoid fish's `cd` in a command substitution changing our cwd + set resolved_path (git -C "$dir" rev-parse --show-prefix 2>/dev/null | sed 's,/$,,') + else + set resolved_path (string replace -r '^\./' '' -- "$resolved_path") + end + end + # Resolution ladder: path/CWD auto-detect -> fzf selection -> rows + exit 1 + set -l ctx (just cross _resolve_context2 "$resolved_path" 2>/dev/null) + if test (count $ctx) -eq 0 + if test -z "$resolved_path" + if not command -v fzf >/dev/null 2>&1 + just cross _list_patches "fzf is not installed, cd manually. Destinations, columns local_path TAB worktree" >&2 + exit 1 + end + set -l sel (just cross _select_patch patch) + test -z "$sel"; and exit 0 + set resolved_path "$sel" + set ctx (just cross _resolve_context2 "$sel" 2>/dev/null) + end if test (count $ctx) -eq 0 - just cross _list_patches "No patch detected, available patches, columns local_path TAB worktree" + just cross _list_patches "No patch detected, available patches, columns local_path TAB worktree" >&2 exit 1 end - printf '%s\n' $ctx | source - echo "{{REPO_DIR}}/$local_path" - else if not command -v fzf >/dev/null 2>&1 - just cross _list_patches "fzf is not installed, cd manually. Destinations, columns local_path TAB worktree" - exit 1 - else - set -l row (just cross _list_patches | fzf --height 40% --select-1 --exit-0 --prompt "Select patch (cd)> ") - test -z "$row"; and exit 0 - set -l cols (string split \t -- $row) - echo "{{REPO_DIR}}/$cols[1]" end + printf '%s\n' $ctx | source + echo "{{REPO_DIR}}/$local_path" # AICONTEXT: "status" shows status of current local_path patch vs. WT, and WT upstream. Input argument is local_path (or understand user stand in the under git-cross'ed local_path and call this comand). It shall be called to get status of local_path from "list" command. Either the status of remote WT upstream (as resource consuming, shall be optional or only ocasional) From b9ec4ee122dbf2cde426c4c6f975c1999fe8a8ce Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 19:23:53 +0100 Subject: [PATCH 06/22] =?UTF-8?q?test:=20fix=20pre-existing=20harness=20de?= =?UTF-8?q?fects=20=E2=80=94=20real=20smoke=20repo=20for=20016=20Go=20gate?= =?UTF-8?q?,=20pin=20REPO=5FROOT=20in=20setup=5Fsandbox?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/016_diff_context.sh | 6 +++++- test/common.sh | 7 ++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/test/016_diff_context.sh b/test/016_diff_context.sh index 34077f970..9f97da3b5 100755 --- a/test/016_diff_context.sh +++ b/test/016_diff_context.sh @@ -108,7 +108,11 @@ fi _go_ok=false _smoke_dir=$(mktemp -d) git init -q "$_smoke_dir" -"$GO_BIN" use _smoke file:///dev/null >/dev/null 2>&1 && _go_ok=true +printf 'smoke\n' > "$_smoke_dir/file.txt" +git -C "$_smoke_dir" add file.txt +git -C "$_smoke_dir" -c user.email=test@example.com -c user.name=test commit -qm init +"$GO_BIN" use _smoke "file://$_smoke_dir" >/dev/null 2>&1 && _go_ok=true +rm -rf "$_smoke_dir" if [ "$_go_ok" = false ]; then log_warn "Go binary not working on this platform, skipping Go-specific diff context tests" else diff --git a/test/common.sh b/test/common.sh index 0e320307a..6a18fd431 100644 --- a/test/common.sh +++ b/test/common.sh @@ -79,9 +79,10 @@ setup_sandbox() { mkdir -p "$SANDBOX" # Copy Justfiles to sandbox - # We assume we are running from the repo root or test/ directory - # The run-all.sh runs from repo root. - REPO_ROOT=$(pwd) + # We assume we are running from the repo root or test/ directory. + # Pin REPO_ROOT on first use: repeated setup_sandbox calls happen after + # `cd "$SANDBOX"`, so re-deriving it from $(pwd) would drift to a deleted dir. + : "${REPO_ROOT:=$(pwd)}" export REPO_ROOT cp "$REPO_ROOT/Justfile" "$SANDBOX/" From 60a1d2c35568ce5cfee01b605cf19dbb1328e263 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 19:29:48 +0100 Subject: [PATCH 07/22] change opencode type --- opencode.jsonc | 53 +------------------------------------------------- 1 file changed, 1 insertion(+), 52 deletions(-) mode change 100644 => 120000 opencode.jsonc diff --git a/opencode.jsonc b/opencode.jsonc deleted file mode 100644 index eb000890d..000000000 --- a/opencode.jsonc +++ /dev/null @@ -1,52 +0,0 @@ -// V2-compatible copy of opencode.jsonc. -// sbx-init-template: ~/.config/opencode/opencode2-requesty.jsonc -{ - "$schema": "https://opencode.ai/config.json", - "default_agent": "plan", - "share": "disabled", - "instructions": [ - "AGENTS.md", - "CLAUDE.md", - "GEMINI.md" - ], - "lsp": true, - "update": "disable", - "permissions": [ - // Don't let the agent push to git. - { "action": "shell", "resource": "git push *", "effect": "deny" }, - // Never decrypt SOPS secrets. - { "action": "shell", "resource": "*sops -d*", "effect": "deny" }, - // Destructive recursive deletion is unnecessary in this sandbox setup. - { "action": "shell", "resource": "rm -rf *", "effect": "deny" }, - { "action": "external_directory", "resource": "~/.local/share/opencode/worktree/*", "effect": "allow" } - ], - // These local plugins require an image that bundles them under /etc/opencode/plugins/. - "plugins": [ - //"@hueyexe/opencode-ensemble@0.18.0", - "@dylanrussell/agent-router@latest" - //"github:regolo-ai/brick" - ], - "providers": { - "requesty": { - "name": "Requesty", - "env": ["REQUESTY_API_KEY"], - "package": "@opencode/ai/providers/openai-compatible", - "settings": { - "baseURL": "https://router.requesty.ai/v1", - "setCacheKey": true, - "timeout": 600000, - "headerTimeout": 300000, - "chunkTimeout": 180000 - }, - "models": { - "openai/gpt-6-luna:flex": { - "name": "GPT-6 Luna Flex (Global)" - }, - "azure/gpt-6-luna@westeurope": { - "name": "GPT-6 Luna (Azure West Europe)" - } - } - } - }, - "model": "requesty/openai/gpt-6-luna:flex" -} diff --git a/opencode.jsonc b/opencode.jsonc new file mode 120000 index 000000000..b33ec83e5 --- /dev/null +++ b/opencode.jsonc @@ -0,0 +1 @@ +.opencode/opencode2-melious.jsonc \ No newline at end of file From ff0a887b678957a6aaa3de5eadcef0558d2f4529 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 19:35:55 +0100 Subject: [PATCH 08/22] feat(cli): bare 'git cross' drops hint line and aligns columns on TTY Piped output keeps the TAB-separated local_path/worktree contract for scripts (cut -f1); interactive output space-pads the first column so the worktree column lines up. --- AGENTS.md | 2 +- README.md | 15 +++++++------ src-go/main.go | 27 +++++++++++++++++++++++- test/019_whole_repo_patch_and_listing.sh | 4 ++++ 4 files changed, 40 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d7566f1b6..fdbd1c1fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +49,7 @@ test/001-023_*.sh # Individual test files (see coverage matrix below) | `cd` | `[path]` | Print absolute local_path to stdout (wrap with `cd "$(git cross cd)"`) | | `wt` | `[path]` | Print absolute worktree path to stdout | -Bare `git cross` prints one `local_pathworktree` row per patch to stdout (hint to stderr); `-h` prints the grouped help. Help grouping is Go-only CLI presentation — Just/Fish exposes the same behavior through recipes, not through a grouped help renderer. +Bare `git cross` prints one `local_pathworktree` row per patch to stdout (no hint line; TTY output is space-padded, piped output stays TAB-separated); `-h` prints the grouped help. Help grouping is Go-only CLI presentation — Just/Fish exposes the same behavior through recipes, not through a grouped help renderer. ## Implementation Comparison diff --git a/README.md b/README.md index d5563a3b0..88591a0c0 100644 --- a/README.md +++ b/README.md @@ -196,17 +196,20 @@ Patch Lifecycle: `compare` also answers to the short alias `git cross cmp`. Running `git cross` with no subcommand does not print help. It prints one row -per configured patch to stdout, `local_pathworktree`, and a hint to stderr: +per configured patch to stdout: ```text $ git cross -Patches (local_path worktree). See: git cross --help -vendor/app .cross/worktrees/app_1a2b3c4d +vendor/app .cross/worktrees/app_1a2b3c4d +vendor/lib .cross/worktrees/lib_5e6f7a8b ``` -Rows are the machine-readable listing used throughout the tool: hints and -warnings go to stderr, so `git cross 2>/dev/null | cut -f1` yields local paths. -Use `git cross -h` or `git cross --help` for the grouped help shown above. +The listing is the machine-readable row format used throughout the tool: +when stdout is a terminal the first column is space-padded for readability; +when piped, rows stay `local_pathworktree` so +`git cross 2>/dev/null | cut -f1` yields local paths. Warnings and error +hints go to stderr. Use `git cross -h` or `git cross --help` for the grouped +help shown above. ### `use` diff --git a/src-go/main.go b/src-go/main.go index d04b2974e..b2addb2dd 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -12,6 +12,7 @@ import ( "path/filepath" "sort" "strings" + "unicode/utf8" "github.com/fatih/color" "github.com/gogs/git-module" @@ -325,6 +326,8 @@ func logError(msg string) { // printPatchRows prints one row per patch: local_path worktree. // Rows go to stdout (parseable via cut -f1); hint goes to stderr, so // `git cross compare 2>/dev/null | cut -f1` yields local paths. +// When stdout is a terminal the first column is space-padded so the +// worktree column lines up; piped output stays pure TAB-separated. func printPatchRows(hint string) error { meta, err := loadMetadata() if err != nil { @@ -337,12 +340,34 @@ func printPatchRows(hint string) error { if hint != "" { fmt.Fprintln(os.Stderr, hint) } + if stdoutIsTerminal() { + width := 0 + for _, p := range meta.Patches { + if n := utf8.RuneCountInString(p.LocalPath); n > width { + width = n + } + } + for _, p := range meta.Patches { + fmt.Printf("%-*s %s\n", width, p.LocalPath, p.Worktree) + } + return nil + } for _, p := range meta.Patches { fmt.Printf("%s\t%s\n", p.LocalPath, p.Worktree) } return nil } +// stdoutIsTerminal reports whether stdout is attached to a TTY (interactive +// output may be padded for readability; pipes keep the TAB contract). +func stdoutIsTerminal() bool { + info, err := os.Stdout.Stat() + if err != nil { + return false + } + return info.Mode()&os.ModeCharDevice != 0 +} + // errPatchNotFound is returned after rows were already printed; commands // that use it set SilenceErrors+SilenceUsage so nothing extra is printed. var errPatchNotFound = errors.New("patch not found") @@ -836,7 +861,7 @@ func main() { Short: "Manage vendored cross-repo patches (worktree + rsync)", SilenceUsage: true, // no Usage dump on errors RunE: func(cmd *cobra.Command, args []string) error { - return printPatchRows("Patches (local_path worktree). See: git cross --help") + return printPatchRows("") }, CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true}, } diff --git a/test/019_whole_repo_patch_and_listing.sh b/test/019_whole_repo_patch_and_listing.sh index 9523150c9..eb4434cd6 100755 --- a/test/019_whole_repo_patch_and_listing.sh +++ b/test/019_whole_repo_patch_and_listing.sh @@ -85,6 +85,10 @@ if [ -n "$GO_BIN" ]; then echo "$bare_stdout" [ "$bare_rc" -eq 0 ] || fail "bare 'git-cross' should exit 0, got $bare_rc" assert_not_contains "$bare_stdout" "Usage:" "bare 'git-cross' should not print a Usage dump" + assert_not_contains "$bare_stdout" "Patches (" "bare 'git-cross' should not print a hint line" + if ! printf '%s\n' "$bare_stdout" | grep -q "$(printf '\t')"; then + fail "piped bare listing must stay TAB-separated" + fi printf '%s\n' "$bare_stdout" | cut -f1 | grep -qx "sub" \ || fail "bare listing missing local_path 'sub' in the first column" printf '%s\n' "$bare_stdout" | cut -f2 | grep -q '^\.cross/worktrees/up_' \ From 028cf3982683222fa096e10451dc9c9ebc506641 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 19:41:38 +0100 Subject: [PATCH 09/22] fix(cli): portable diff/.git exclusion, working vim DirDiff command, help order, aligned raw output - diff: drop ':(exclude).git' pathspec (rejected by older git with a usage error); diff a .git-free mirror of the worktree instead (Go + Just) - compare: default tool is now two vim +cmd args 'vim "+let g:DirDiffExcludes=.git" "+DirDiff {left} {right}"'; DirDiffIgnore=... was never a vim command (E492) - help: use/patch first (Patch Lifecycle group first), authored order kept - list --raw and bare listing: TTY-aligned columns; piped output stays TSV - tests: default TESTDIR so NNN.sh can run standalone (014/015 chain-source 001) --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- Justfile.cross | 89 ++++++++++++++++++++++++++++++------------ README.md | 44 +++++++++++---------- src-go/main.go | 103 +++++++++++++++++++++++++++++++++++++++++-------- test/common.sh | 5 +++ 6 files changed, 183 insertions(+), 62 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fdbd1c1fa..27847c84a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 - **`.git` exclusion**: a worktree root contains a `.git` pointer file that never exists in the local copy (rsync uses `--exclude .git`). Boolean tree comparisons use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff uses `git diff --no-index -- ':(exclude).git' ':(glob)**'`. Without both exclusions, whole-repo patches always look modified. - **Sparse checkout**: `git sparse-checkout init --no-cone` + `git sparse-checkout set /` + `git read-tree -mu HEAD`. The trailing `/` on the pattern is required for reliable directory matching in `--no-cone` mode on newer Git versions (2.43+). `read-tree -mu HEAD` explicitly materializes the worktree (bare `git checkout` can no-op after `--no-checkout`). - **Rsync**: `rsync -av --delete --exclude .git` for worktree-to-local sync. `--delete` removes files locally that were deleted upstream. -- **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `vim "+DirDiffIgnore='.git' DirDiff {left} {right}"`. Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). +- **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `vim "+let g:DirDiffExcludes='.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). - **Patch rows**: bare `git cross`, and path-miss cases in `compare`/`diff`/`remove`/`cd`/`wt`, print `local_pathworktree` rows to stdout; hints go to stderr and the command exits 1 where nothing was resolved. - **`list --raw` schema**: remotes first (`REMOTE_NAMEREMOTE_URL`), then patches (`REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`); no banners, no borders, deterministic remote order. - **Crossfile format**: Lines like `cross use ` or `cross patch :: `. `update` interprets only these declarative commands; arbitrary shell commands are not executed. diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c4ac2728..6ada68272 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **BREAKING: `cd` / `wt` print a path instead of opening a shell** - Both commands print the absolute destination path to stdout (hints to stderr). They no longer start a subshell and no longer copy anything to the clipboard. Use `cd "$(git cross cd)"`, `cd "$(git cross wt)"`, or the documented `crosscd`/`crosswt` wrappers for bash/zsh/fish. Without an argument `fzf` selects the patch; if `fzf` is missing, rows plus a hint are printed and the command exits 1. - **Behavior change: interactive `diff` selection** - With no path, `diff` now resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. - **`compare` selection ladder** - With no path, `compare` uses the same CWD auto-detect → `fzf` → rows + hint + exit 1 ladder and always operates on exactly one patch. -- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is now `vim "+DirDiffIgnore='.git' DirDiff {left} {right}"`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. +- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is now `vim "+let g:DirDiffExcludes='.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). The legacy append form (for example `vim "+DirDiff"`) is deprecated. - **Concise `update` warning** - Local edits now produce one relative, actionable line: `'' differs from upstream; local copy preserved. Compare with: git cross diff `. The `cross.diffTool` configuration hint and the broken DirDiff invocation are gone. #### Fixed diff --git a/Justfile.cross b/Justfile.cross index dd4fe98c9..e8d9d9727 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -227,6 +227,25 @@ _log level +message: echo "==> {{message}}" end +# Internal: print TSV rows aligned on a terminal, unchanged (TAB) when piped. +[no-cd] +_print_rows: + #!/usr/bin/env fish + if not test -t 1 + cat + return + end + awk -F'\t' ' + { for (i = 1; i <= NF; i++) if (length($i) > w[i]) w[i] = length($i); rows[NR] = $0 } + END { + for (r = 1; r <= NR; r++) { + n = split(rows[r], a, "\t"); line = "" + for (i = 1; i <= n; i++) + line = line (i < n ? sprintf("%-*s ", w[i], a[i]) : a[i]) + print line + } + }' + # Print one row per patch: local_pathworktree (machine-parseable). # hint is variadic because the Justfile wrapper word-splits arguments. [no-cd] @@ -732,9 +751,24 @@ diff path="": check-initialized if test -d $worktree set overrides (just cross _crossignore_overrides "{{REPO_DIR}}/$local_path") if test -z "$overrides[1]" - # Exclude .git (worktree pointer file has no local counterpart) while - # keeping real content diffs and the difference exit status. - git diff --no-index $worktree/$remote_path $local_path -- ':(exclude).git' ':(glob)**' || true + # Worktree roots contain a `.git` pointer file with no local + # counterpart. Pathspec excludes are not portable across git + # versions, so diff against a .git-free mirror when needed. + set -l left $worktree/$remote_path + set -l tmp "" + if test -e "$left/.git" + set tmp (mktemp -d) + if rsync -a --exclude=.git --link-dest=(realpath "$left")/ "$left/" "$tmp/" >/dev/null 2>&1 + set left $tmp + else + rm -rf "$tmp" + set tmp "" + end + end + git diff --no-index "$left" "$local_path" || true + if test -n "$tmp" + rm -rf "$tmp" + end else for override in $overrides printf 'git diff --no-index "%s" "%s"\n' "{{REPO_DIR}}/$worktree/$remote_path/$override" "{{REPO_DIR}}/$local_path/$override" @@ -772,8 +806,11 @@ compare path="": check-initialized printf '%s\n' $ctx | source set tool (git config --get cross.diffTool 2>/dev/null) - test -n "$tool"; or set tool "vim \"+DirDiffIgnore='.git' DirDiff {left} {right}\"" + test -n "$tool"; or set tool "vim \"+let g:DirDiffExcludes='.git'\" \"+DirDiff {left} {right}\"" set left "$worktree/$remote_path" + if test "$remote_path" = "." + set left "$worktree" + end set right "$local_path" if string match -q "*{left}*" -- $tool; or string match -q "*{right}*" -- $tool set cmd (string replace -a '{right}' "$right" "$tool") @@ -816,9 +853,10 @@ list raw="" no_header="": check-deps set used_remotes (jq -r '.patches[].remote' .cross/metadata.json | sort -u) if test (count $used_remotes) -gt 0 + set -l remote_rows if $show_raw if $show_header - printf 'REMOTE_NAME\tREMOTE_URL\n' + set -a remote_rows (string join \t -- REMOTE_NAME REMOTE_URL) end else just cross _log info "Configured Remotes:" @@ -836,14 +874,18 @@ list raw="" no_header="": check-deps end for url in $urls if $show_raw - printf '%s\t%s\n' $name $url + set -a remote_rows (string join \t -- $name $url) else printf "%-20s %s\n" $name $url end end end - if not $show_raw + if $show_raw + if test (count $remote_rows) -gt 0 + printf '%s\n' $remote_rows | just cross _print_rows + end + else echo "" end end @@ -859,24 +901,23 @@ list raw="" no_header="": check-deps exit 0 end - if $show_raw - if $show_header - printf 'REMOTE\tREMOTE_PATH\tLOCAL_PATH\tWORKTREE\tBRANCH\n' - end - else - just cross _log info "Configured Patches:" - if $show_header - printf "%-20s %-30s %-20s %-26s %-15s\n" "REMOTE" "REMOTE PATH" "LOCAL PATH" "WORKTREE" "BRANCH" - printf "%s\n" (string repeat -n 70 "-") - end - end - + set -l patch_rows if test -f .cross/metadata.json - set -l patch_rows (jq -r '.patches[] | [.remote, .remote_path, .local_path, .worktree, .branch] | @tsv' .cross/metadata.json | sort) - for row in $patch_rows - if $show_raw - printf '%s\n' $row - else + set patch_rows (jq -r '.patches[] | [.remote, .remote_path, .local_path, .worktree, .branch] | @tsv' .cross/metadata.json | sort) + if $show_raw + if $show_header + set patch_rows (string join \t -- REMOTE REMOTE_PATH LOCAL_PATH WORKTREE BRANCH) $patch_rows + end + if test (count $patch_rows) -gt 0 + printf '%s\n' $patch_rows | just cross _print_rows + end + else + just cross _log info "Configured Patches:" + if $show_header + printf "%-20s %-30s %-20s %-26s %-15s\n" "REMOTE" "REMOTE PATH" "LOCAL PATH" "WORKTREE" "BRANCH" + printf "%s\n" (string repeat -n 70 "-") + end + for row in $patch_rows set -l cols (string split \t -- $row) printf "%-20s %-30s %-20s %-26s %-15s\n" $cols[1] $cols[2] $cols[3] $cols[4] $cols[5] end diff --git a/README.md b/README.md index 88591a0c0..2bf6c3527 100644 --- a/README.md +++ b/README.md @@ -171,26 +171,27 @@ This lets your main repo keep its local opinionated result while the upstream co ## Commands -`git cross --help` groups commands by intent: +`git cross --help` groups commands by intent, starting with the two you need +first — `use`, then `patch`: ```text +Patch Lifecycle: + use Add a remote repository + patch Create a patch from a remote path + remove Remove a patch + prune Remove a remote and all its patches + Repository: - compare Open the configured directory comparison tool for a patch init Create an empty Crossfile list Show all configured patches and remotes status Show patch status update Update patches from Crossfile declarations + compare Open the configured directory comparison tool for a patch Inspect & Navigate: cd Print a patch local_path to cd into diff Show changes between local and upstream wt Print a patch worktree to cd into - -Patch Lifecycle: - patch Create a patch from a remote path - prune Remove a remote and all its patches - remove Remove a patch - use Add a remote repository ``` `compare` also answers to the short alias `git cross cmp`. @@ -295,20 +296,21 @@ Show configured remotes and patches. Default output is a table with `Configured Remotes:` / `Configured Patches:` banners and descriptive column headers. -`--raw` switches to machine-readable output: tab-separated rows, no table -borders, and no banners. `--no-header` omits the header line in both table and -raw mode. In raw mode the section order is fixed — all remotes first, then all -patches: +`--raw` switches to machine-readable output: no table borders and no banners. +When stdout is a terminal, columns are space-padded so they line up; when +piped, rows are plain `TAB`-separated values. `--no-header` omits the header +line in both table and raw mode. In raw mode the section order is fixed — all +remotes first, then all patches: ```text -REMOTE_NAME REMOTE_URL -REMOTE REMOTE_PATH LOCAL_PATH WORKTREE BRANCH +REMOTE_NAME REMOTE_URL +REMOTE REMOTE_PATH LOCAL_PATH WORKTREE BRANCH ``` Each remote with a different fetch and push URL produces one row per URL; both rows stay in the two-column schema, so the URL field is never decorated with -`(fetch)` / `(push)` suffixes. Remote rows are sorted by name. Header rows are -themselves tab-separated, so use `--no-header` in pipelines. +`(fetch)` / `(push)` suffixes. Remote rows are sorted by name. In pipes, header +rows are themselves tab-separated, so use `--no-header` in pipelines. Parsing examples: @@ -427,19 +429,21 @@ repository root as its working directory. The default, used when `cross.diffTool` is unset, is: ```text -vim "+DirDiffIgnore='.git' DirDiff {left} {right}" +vim "+let g:DirDiffExcludes='.git'" "+DirDiff {left} {right}" ``` -To make it explicit: +Note the two separate `+cmd` arguments: `DirDiffIgnore=` is not a vim command, +so the exclusion is set with `let` first, then `DirDiff` runs. To make it +explicit: ```bash -git config --global cross.diffTool "vim \"+DirDiffIgnore='.git' DirDiff {left} {right}\"" +git config --global cross.diffTool "vim \"+let g:DirDiffExcludes='.git'\" \"+DirDiff {left} {right}\"" ``` A custom ignore list passes DirDiff a comma-separated list of names to skip: ```bash -git config --global cross.diffTool "nvim \"+DirDiffIgnore='ves.io,f5fed.com,volterra.us' DirDiff {left} {right}\"" +git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes='.git,ves.io,f5fed.com,volterra.us'\" \"+DirDiff {left} {right}\"" ``` In this form the paths are part of the vim `+` command string, which is where diff --git a/src-go/main.go b/src-go/main.go index b2addb2dd..2ec9cc114 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -275,7 +275,7 @@ func logWarn(msg string) { fmt.Println(msg) } -const defaultDiffTool = `vim "+DirDiffIgnore='.git' DirDiff {left} {right}"` +const defaultDiffTool = `vim "+let g:DirDiffExcludes='.git'" "+DirDiff {left} {right}"` func diffTool() string { if out, err := exec.Command("git", "config", "--get", "cross.diffTool").Output(); err == nil { @@ -358,6 +358,46 @@ func printPatchRows(hint string) error { return nil } +// printRawRows writes rows as TAB-separated values when piped, or as +// space-aligned columns when stdout is a terminal (readable interactively +// without breaking the TAB contract for scripts). +func printRawRows(rows [][]string) { + if len(rows) == 0 { + return + } + if !stdoutIsTerminal() { + for _, row := range rows { + fmt.Println(strings.Join(row, "\t")) + } + return + } + var widths []int + for _, row := range rows { + for i, col := range row { + if i >= len(widths) { + widths = append(widths, 0) + } + if n := utf8.RuneCountInString(col); n > widths[i] { + widths[i] = n + } + } + } + for _, row := range rows { + var b strings.Builder + for i, col := range row { + if i > 0 { + b.WriteString(" ") + } + if i < len(row)-1 { + fmt.Fprintf(&b, "%-*s", widths[i], col) + } else { + b.WriteString(col) + } + } + fmt.Println(b.String()) + } +} + // stdoutIsTerminal reports whether stdout is attached to a TTY (interactive // output may be padded for readability; pipes keep the TAB contract). func stdoutIsTerminal() bool { @@ -853,7 +893,40 @@ func selectPatchInteractive(meta *Metadata) (*Patch, error) { return nil, fmt.Errorf("selected patch not found: %s", localPath) } +// runNoIndexDiff prints a unified diff between the upstream worktree directory +// and the local copy. A worktree root contains a `.git` pointer file that the +// local copy never has; pathspec excludes are not portable across git versions +// (older gits reject them with a usage error), so when `.git` is present we +// diff against a temporary mirror that omits it. +func runNoIndexDiff(upstreamPath, localPath string) { + left := upstreamPath + cleanup := func() {} + if _, err := os.Stat(filepath.Join(upstreamPath, ".git")); err == nil { + if tmp, terr := os.MkdirTemp("", "cross-diff-"); terr == nil { + // --link-dest hardlinks unchanged files, so the mirror is cheap. + cmd := exec.Command("rsync", "-a", "--exclude=.git", + "--link-dest="+upstreamPath+string(os.PathSeparator), + upstreamPath+string(os.PathSeparator), tmp+string(os.PathSeparator)) + if _, rerr := cmd.CombinedOutput(); rerr == nil { + left = tmp + cleanup = func() { os.RemoveAll(tmp) } + } else { + os.RemoveAll(tmp) + } + } + } + defer cleanup() + + c := exec.Command("git", "diff", "--no-index", left, localPath) + c.Stdout = os.Stdout + c.Stderr = os.Stderr + // git diff --no-index returns 1 when differences exist; that is not an error. + _ = c.Run() +} + func main() { + // Keep authored order in --help: use/patch must come first. + cobra.EnableCommandSorting = false var dry string rootCmd := &cobra.Command{ Use: "git-cross", @@ -866,9 +939,9 @@ func main() { CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true}, } rootCmd.AddGroup( + &cobra.Group{ID: "patches", Title: "Patch Lifecycle:"}, &cobra.Group{ID: "repo", Title: "Repository:"}, &cobra.Group{ID: "inspect", Title: "Inspect & Navigate:"}, - &cobra.Group{ID: "patches", Title: "Patch Lifecycle:"}, ) // Group the builtin help command so no ungrouped visible command remains // (Cobra otherwise renders it under "Additional Commands:"). @@ -1639,32 +1712,36 @@ func main() { sort.Strings(remoteNames) if raw { - // Machine-readable: tab-separated rows, no banners, no borders. + // Machine-readable rows; aligned on a TTY, TAB-separated when piped. + var rows [][]string if len(remoteNames) > 0 { if !noHeader { - fmt.Printf("REMOTE_NAME\tREMOTE_URL\n") + rows = append(rows, []string{"REMOTE_NAME", "REMOTE_URL"}) } for _, name := range remoteNames { info := remoteMap[name] if info.fetch == "" { continue } - fmt.Printf("%s\t%s\n", name, info.fetch) + rows = append(rows, []string{name, info.fetch}) if info.push != "" && info.push != info.fetch { - fmt.Printf("%s\t%s\n", name, info.push) + rows = append(rows, []string{name, info.push}) } } + printRawRows(rows) } if len(meta.Patches) == 0 { fmt.Fprintln(os.Stderr, "No patches configured.") return nil } + rows = nil if !noHeader { - fmt.Printf("REMOTE\tREMOTE_PATH\tLOCAL_PATH\tWORKTREE\tBRANCH\n") + rows = append(rows, []string{"REMOTE", "REMOTE_PATH", "LOCAL_PATH", "WORKTREE", "BRANCH"}) } for _, p := range meta.Patches { - fmt.Printf("%s\t%s\t%s\t%s\t%s\n", p.Remote, p.RemotePath, p.LocalPath, p.Worktree, p.Branch) + rows = append(rows, []string{p.Remote, p.RemotePath, p.LocalPath, p.Worktree, p.Branch}) } + printRawRows(rows) return nil } @@ -1865,13 +1942,7 @@ if fzf is unavailable it prints the available patches.`, fmt.Printf("git diff --no-index %q %q\n", filepath.Join(upstreamPath, override), filepath.Join(localPath, override)) } } else { - c := exec.Command("git", "diff", "--no-index", - upstreamPath, localPath, - "--", ":(exclude).git", ":(glob)**") - c.Stdout = os.Stdout - c.Stderr = os.Stderr - // git diff --no-index returns 1 if there are differences, which cobra might treat as error - _ = c.Run() + runNoIndexDiff(upstreamPath, localPath) } } if !found { @@ -2206,7 +2277,7 @@ if fzf is unavailable it prints the available patches.`, // Retain superseded implementations in source as internal reference, but do // not expose them as supported commands. _, _, _, _ = syncCmd, replayCmd, pushCmd, execCmd - rootCmd.AddCommand(useCmd, patchCmd, updateCmd, compareCmd, removeCmd, pruneCmd, cdCmd, wtCmd, listCmd, statusCmd, diffCmd, initCmd) + rootCmd.AddCommand(useCmd, patchCmd, removeCmd, pruneCmd, initCmd, listCmd, statusCmd, updateCmd, compareCmd, cdCmd, wtCmd, diffCmd) if err := rootCmd.Execute(); err != nil { os.Exit(1) } diff --git a/test/common.sh b/test/common.sh index 6a18fd431..37ea60d50 100644 --- a/test/common.sh +++ b/test/common.sh @@ -2,6 +2,11 @@ # Common test helpers +# Direct `bash test/NNN.sh` runs may chain-source earlier tests that reference +# $TESTDIR; run-all.sh exports it, so provide a temp default otherwise. +: "${TESTDIR:=$(mktemp -d)}" +export TESTDIR + log_header() { # Bold Blue if [ -t 1 ]; then From b2d33d3141720bf74e2227f4811ec80a4a6b1723 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 19:42:59 +0100 Subject: [PATCH 10/22] docs(agents): .git exclusion via .git-free mirror (no pathspec) --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 27847c84a..659e6adcc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -188,7 +188,7 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 ## Implementation Details - **Hidden worktrees**: `.cross/worktrees/_` (verified in `src-go/main.go`; Justfile.cross uses the same path). A stale `AICONTEXT` comment in `Justfile.cross` (line 697) still says `.git/cross/worktrees/` and should be corrected by the Just owner. -- **`.git` exclusion**: a worktree root contains a `.git` pointer file that never exists in the local copy (rsync uses `--exclude .git`). Boolean tree comparisons use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff uses `git diff --no-index -- ':(exclude).git' ':(glob)**'`. Without both exclusions, whole-repo patches always look modified. +- **`.git` exclusion**: a worktree root contains a `.git` pointer file that never exists in the local copy (rsync uses `--exclude .git`). Boolean tree comparisons use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff (`git diff --no-index`) is run against a temporary `.git`-free mirror of the worktree, because pathspec excludes like `:(exclude).git` are rejected by older git versions with a usage error. Without both exclusions, whole-repo patches always look modified. - **Sparse checkout**: `git sparse-checkout init --no-cone` + `git sparse-checkout set /` + `git read-tree -mu HEAD`. The trailing `/` on the pattern is required for reliable directory matching in `--no-cone` mode on newer Git versions (2.43+). `read-tree -mu HEAD` explicitly materializes the worktree (bare `git checkout` can no-op after `--no-checkout`). - **Rsync**: `rsync -av --delete --exclude .git` for worktree-to-local sync. `--delete` removes files locally that were deleted upstream. - **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `vim "+let g:DirDiffExcludes='.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). From dbda066aa0d3df22aea37a766f1f450eb0ff62be Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 19:56:27 +0100 Subject: [PATCH 11/22] feat(cli): nvim-first DirDiff default, help setup guidance, editor tests - default cross.diffTool: nvim when installed, else vim, invoked as "+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}" - git cross --help documents how to reset to the built-in default (--unset) and how to pin nvim/vim explicitly with the correct syntax - tests: 020 asserts the guidance; 021 asserts nvim preference and vim fallback - docs: README, CHANGELOG, docs/overview.md, AGENTS.md updated --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- Justfile.cross | 8 ++++++- README.md | 19 ++++++++------- docs/overview.md | 2 +- src-go/main.go | 27 +++++++++++++++++++-- test/020_help_groups.sh | 10 ++++++++ test/021_fzf_diff_compare.sh | 46 ++++++++++++++++++++++++++++++++++++ test/common.sh | 10 ++++++-- 9 files changed, 110 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 659e6adcc..cd2bfc5eb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 - **`.git` exclusion**: a worktree root contains a `.git` pointer file that never exists in the local copy (rsync uses `--exclude .git`). Boolean tree comparisons use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff (`git diff --no-index`) is run against a temporary `.git`-free mirror of the worktree, because pathspec excludes like `:(exclude).git` are rejected by older git versions with a usage error. Without both exclusions, whole-repo patches always look modified. - **Sparse checkout**: `git sparse-checkout init --no-cone` + `git sparse-checkout set /` + `git read-tree -mu HEAD`. The trailing `/` on the pattern is required for reliable directory matching in `--no-cone` mode on newer Git versions (2.43+). `read-tree -mu HEAD` explicitly materializes the worktree (bare `git checkout` can no-op after `--no-checkout`). - **Rsync**: `rsync -av --delete --exclude .git` for worktree-to-local sync. `--delete` removes files locally that were deleted upstream. -- **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `vim "+let g:DirDiffExcludes='.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). +- **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `nvim` when installed, else `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). - **Patch rows**: bare `git cross`, and path-miss cases in `compare`/`diff`/`remove`/`cd`/`wt`, print `local_pathworktree` rows to stdout; hints go to stderr and the command exits 1 where nothing was resolved. - **`list --raw` schema**: remotes first (`REMOTE_NAMEREMOTE_URL`), then patches (`REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`); no banners, no borders, deterministic remote order. - **Crossfile format**: Lines like `cross use ` or `cross patch :: `. `update` interprets only these declarative commands; arbitrary shell commands are not executed. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ada68272..039e2461b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **BREAKING: `cd` / `wt` print a path instead of opening a shell** - Both commands print the absolute destination path to stdout (hints to stderr). They no longer start a subshell and no longer copy anything to the clipboard. Use `cd "$(git cross cd)"`, `cd "$(git cross wt)"`, or the documented `crosscd`/`crosswt` wrappers for bash/zsh/fish. Without an argument `fzf` selects the patch; if `fzf` is missing, rows plus a hint are printed and the command exits 1. - **Behavior change: interactive `diff` selection** - With no path, `diff` now resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. - **`compare` selection ladder** - With no path, `compare` uses the same CWD auto-detect → `fzf` → rows + hint + exit 1 ladder and always operates on exactly one patch. -- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is now `vim "+let g:DirDiffExcludes='.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). The legacy append form (for example `vim "+DirDiff"`) is deprecated. +- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). The legacy append form (for example `vim "+DirDiff"`) is deprecated. - **Concise `update` warning** - Local edits now produce one relative, actionable line: `'' differs from upstream; local copy preserved. Compare with: git cross diff `. The `cross.diffTool` configuration hint and the broken DirDiff invocation are gone. #### Fixed diff --git a/Justfile.cross b/Justfile.cross index e8d9d9727..1a2a0b354 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -806,7 +806,13 @@ compare path="": check-initialized printf '%s\n' $ctx | source set tool (git config --get cross.diffTool 2>/dev/null) - test -n "$tool"; or set tool "vim \"+let g:DirDiffExcludes='.git'\" \"+DirDiff {left} {right}\"" + if test -z "$tool" + set -l editor vim + if command -v nvim >/dev/null 2>&1 + set editor nvim + end + set tool "$editor \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" + end set left "$worktree/$remote_path" if test "$remote_path" = "." set left "$worktree" diff --git a/README.md b/README.md index 2bf6c3527..f4103d97e 100644 --- a/README.md +++ b/README.md @@ -425,25 +425,28 @@ before the command is run: - `{right}` — the patch's local copy The substituted paths are **repo-relative**, and the command runs with the -repository root as its working directory. The default, used when -`cross.diffTool` is unset, is: +repository root as its working directory. When `cross.diffTool` is unset the +built-in default is used — `nvim` if it is installed, otherwise `vim`: ```text -vim "+let g:DirDiffExcludes='.git'" "+DirDiff {left} {right}" +nvim "+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}" +vim "+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}" ``` -Note the two separate `+cmd` arguments: `DirDiffIgnore=` is not a vim command, -so the exclusion is set with `let` first, then `DirDiff` runs. To make it -explicit: +Note the two separate `+cmd` arguments: `DirDiffIgnore=...` is not a vim +command, so the exclusion is set with `let` first, then `DirDiff` runs with the +directories as arguments. To pin a specific editor, set it explicitly: ```bash -git config --global cross.diffTool "vim \"+let g:DirDiffExcludes='.git'\" \"+DirDiff {left} {right}\"" +git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" +# strictly vim: +git config --global cross.diffTool "vim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" ``` A custom ignore list passes DirDiff a comma-separated list of names to skip: ```bash -git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes='.git,ves.io,f5fed.com,volterra.us'\" \"+DirDiff {left} {right}\"" +git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes = '.git,ves.io,f5fed.com,volterra.us'\" \"+DirDiff {left} {right}\"" ``` In this form the paths are part of the vim `+` command string, which is where diff --git a/docs/overview.md b/docs/overview.md index 2284c5d66..72cf47e83 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -68,7 +68,7 @@ Reads `Crossfile`, fetches each upstream, and fast-forwards its sparse worktree. ### `compare` -Opens the configured directory diff tool for the local path and its sparse worktree. Configure it with `git config --global cross.diffTool 'vim "+DirDiff"'`. +Opens the configured directory diff tool for the local path and its sparse worktree. Default: `nvim` when installed else `vim`, invoked as `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"`. Override with `git config --global cross.diffTool ' {left} {right}'`. ### `diff` diff --git a/src-go/main.go b/src-go/main.go index 2ec9cc114..439883564 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -275,7 +275,16 @@ func logWarn(msg string) { fmt.Println(msg) } -const defaultDiffTool = `vim "+let g:DirDiffExcludes='.git'" "+DirDiff {left} {right}"` +// defaultDiffTool returns the built-in diff tool command: nvim when available, +// otherwise vim. Two separate +cmd arguments: set the exclusion list first, +// then run DirDiff on the given directories. +func defaultDiffTool() string { + editor := "vim" + if _, err := exec.LookPath("nvim"); err == nil { + editor = "nvim" + } + return editor + ` "+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` +} func diffTool() string { if out, err := exec.Command("git", "config", "--get", "cross.diffTool").Output(); err == nil { @@ -283,7 +292,7 @@ func diffTool() string { return tool } } - return defaultDiffTool + return defaultDiffTool() } // runDiffTool executes the configured diff tool. If the tool string contains @@ -933,6 +942,20 @@ func main() { Version: "0.3.0", Short: "Manage vendored cross-repo patches (worktree + rsync)", SilenceUsage: true, // no Usage dump on errors + Long: `Manage vendored cross-repo patches (worktree + rsync). + +Directory diff tool (compare / cmp): when cross.diffTool is unset, nvim is used +if installed, otherwise vim, with .git ignored. To use the built-in default: + + git config --global --unset cross.diffTool + +To pin it explicitly (recommended): + + git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" + +Strictly vim: + + git config --global cross.diffTool "vim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\""`, RunE: func(cmd *cobra.Command, args []string) error { return printPatchRows("") }, diff --git a/test/020_help_groups.sh b/test/020_help_groups.sh index 38ad049af..188e272a6 100755 --- a/test/020_help_groups.sh +++ b/test/020_help_groups.sh @@ -79,4 +79,14 @@ assert_contains "$short_help" "Inspect & Navigate:" assert_contains "$short_help" "Patch Lifecycle:" log_success "-h works" +log_header "020: help suggests the cross.diffTool setup" +assert_contains "$help_output" "cross.diffTool" "help should mention cross.diffTool setup" +assert_contains "$help_output" "--unset cross.diffTool" "help should show how to reset to the built-in default" +assert_contains "$help_output" "let g:DirDiffExcludes = '.git'" "help should show the correct DirDiff exclusion syntax" +assert_contains "$help_output" "DirDiff {left} {right}" "help should show the placeholder form" +if printf '%s\n' "$help_output" | grep -q "DirDiffIgnore="; then + fail "help must not suggest the invalid 'DirDiffIgnore=' command" +fi +log_success "diffTool setup guidance present" + echo "Test 020 passed!" diff --git a/test/021_fzf_diff_compare.sh b/test/021_fzf_diff_compare.sh index 3f2c6a829..946d25894 100755 --- a/test/021_fzf_diff_compare.sh +++ b/test/021_fzf_diff_compare.sh @@ -109,6 +109,39 @@ if [ -n "$GO_BIN" ]; then git config --unset cross.diffTool || true log_success "fzf selection drives diff/compare" + # --- default diff tool: nvim preferred, vim fallback + log_header "021: default diffTool prefers nvim, falls back to vim" + git config --unset cross.diffTool || true + both_shims="$SANDBOX/editor-shims" + vim_shims="$SANDBOX/vim-shims" + mkdir -p "$both_shims" "$vim_shims" + for ed in nvim vim; do + cat > "$both_shims/$ed" < "$vim_shims/vim" <<'SH' +#!/bin/sh +printf 'EDITOR:vim\n' +printf 'ARG:%s\n' "$@" +SH + chmod +x "$vim_shims/vim" + + out=$(PATH="$both_shims:$PATH" "$GO_BIN" compare vendor/alpha 2>/dev/null) + echo "$out" + assert_contains "$out" "EDITOR:nvim" "default tool should prefer nvim when installed" + assert_contains "$out" "let g:DirDiffExcludes = '.git'" "default tool should set DirDiffExcludes for .git" + assert_contains "$out" "DirDiff .cross/worktrees/" "both paths should be inside the DirDiff command" + + no_nvim_path=$(make_path_without "$SANDBOX/no-nvim-bin" nvim) + out=$(PATH="$vim_shims:$no_nvim_path" "$GO_BIN" compare vendor/alpha 2>/dev/null) + echo "$out" + assert_contains "$out" "EDITOR:vim" "default tool should fall back to vim when nvim is absent" + log_success "editor selection verified (nvim preferred, vim fallback)" + # --- inside a patched dir: CWD auto-detect, no fzf needed log_header "021: CWD auto-detect still wins inside a patch directory" pushd vendor/alpha >/dev/null @@ -183,6 +216,19 @@ if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command - assert_contains "$out" "TOOL .cross/worktrees/upstream_" "Just compare should run the tool on the selected worktree" git config --unset cross.diffTool || true + log_header "021: Just default diffTool prefers nvim" + just_shims="$SANDBOX/editor-shims-just" + mkdir -p "$just_shims" + for ed in nvim vim; do + printf '#!/bin/sh\nprintf "EDITOR:%s\\n"\nprintf "ARG:%%s\\n" "$@"\n' "$ed" > "$just_shims/$ed" + chmod +x "$just_shims/$ed" + done + out=$(PATH="$just_shims:$PATH" just cross compare vendor/alpha 2>/dev/null) + echo "$out" + assert_contains "$out" "EDITOR:nvim" "Just default tool should prefer nvim when installed" + assert_contains "$out" "let g:DirDiffExcludes = '.git'" "Just default tool should set DirDiffExcludes" + log_success "Just editor selection verified" + log_header "021: Just CWD auto-detect inside a patch directory" pushd vendor/alpha >/dev/null out=$(PATH="$nofzf_path" just cross diff 2>&1) || true diff --git a/test/common.sh b/test/common.sh index 37ea60d50..adc1bd709 100644 --- a/test/common.sh +++ b/test/common.sh @@ -213,8 +213,10 @@ ensure_go_bin() { # A symlink farm is used because a directory cannot "hide" a binary that lives # in another PATH entry. This makes the "fzf is not installed" fallbacks # testable deterministically, even on hosts/CI images that ship fzf. -make_path_without_fzf() { +make_path_without() { local farm=$1 + shift + local excludes=" $* " local IFS=: local dir entry base if [ -z "$farm" ]; then @@ -227,7 +229,7 @@ make_path_without_fzf() { for entry in "$dir"/*; do [ -f "$entry" ] && [ -x "$entry" ] || continue base=${entry##*/} - [ "$base" = "fzf" ] && continue + case "$excludes" in *" $base "*) continue;; esac [ -e "$farm/$base" ] && continue ln -s "$entry" "$farm/$base" 2>/dev/null || true done @@ -235,6 +237,10 @@ make_path_without_fzf() { printf '%s\n' "$farm" } +make_path_without_fzf() { + make_path_without "$1" fzf +} + cleanup() { if [ "${CLEANUP:-true}" = true ] && [ -n "${SANDBOX:-}" ] && [ -d "$SANDBOX" ]; then rm -rf "$SANDBOX" From 41c1d1db03e99311d39c9ce9d9f6901f4229b985 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 20:01:39 +0100 Subject: [PATCH 12/22] feat(cli): DIRDIFF_EXCLUDES / DIRDIFF_IGNORE env extras for default DirDiff When cross.diffTool is unset, the built-in tool now composes: +let g:DirDiffExcludes = '.git[,]' (.git always included) +let g:DirDiffIgnore = '\Vkw1\|kw2' (only when DIRDIFF_IGNORE is set) Unset/empty variables omit the corresponding argument. Documented in git cross --help, README, CHANGELOG and AGENTS; covered by test 021 for both Go and Just. --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- Justfile.cross | 16 ++++++++++- README.md | 20 ++++++++++++++ src-go/main.go | 53 +++++++++++++++++++++++++++++++++--- test/021_fzf_diff_compare.sh | 24 +++++++++++++++- 6 files changed, 109 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cd2bfc5eb..1510343b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 - **`.git` exclusion**: a worktree root contains a `.git` pointer file that never exists in the local copy (rsync uses `--exclude .git`). Boolean tree comparisons use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff (`git diff --no-index`) is run against a temporary `.git`-free mirror of the worktree, because pathspec excludes like `:(exclude).git` are rejected by older git versions with a usage error. Without both exclusions, whole-repo patches always look modified. - **Sparse checkout**: `git sparse-checkout init --no-cone` + `git sparse-checkout set /` + `git read-tree -mu HEAD`. The trailing `/` on the pattern is required for reliable directory matching in `--no-cone` mode on newer Git versions (2.43+). `read-tree -mu HEAD` explicitly materializes the worktree (bare `git checkout` can no-op after `--no-checkout`). - **Rsync**: `rsync -av --delete --exclude .git` for worktree-to-local sync. `--delete` removes files locally that were deleted upstream. -- **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `nvim` when installed, else `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). +- **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `nvim` when installed, else `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). When unset, env vars extend the default: `DIRDIFF_EXCLUDES` appends names to the exclusion list (`.git` stays permanent) and `DIRDIFF_IGNORE` adds `g:DirDiffIgnore` with a very-nomagic (`\V`) alternation of the comma-separated keywords. Empty/unset vars omit the corresponding argument. Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). - **Patch rows**: bare `git cross`, and path-miss cases in `compare`/`diff`/`remove`/`cd`/`wt`, print `local_pathworktree` rows to stdout; hints go to stderr and the command exits 1 where nothing was resolved. - **`list --raw` schema**: remotes first (`REMOTE_NAMEREMOTE_URL`), then patches (`REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`); no banners, no borders, deterministic remote order. - **Crossfile format**: Lines like `cross use ` or `cross patch :: `. `update` interprets only these declarative commands; arbitrary shell commands are not executed. diff --git a/CHANGELOG.md b/CHANGELOG.md index 039e2461b..548bc3104 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **BREAKING: `cd` / `wt` print a path instead of opening a shell** - Both commands print the absolute destination path to stdout (hints to stderr). They no longer start a subshell and no longer copy anything to the clipboard. Use `cd "$(git cross cd)"`, `cd "$(git cross wt)"`, or the documented `crosscd`/`crosswt` wrappers for bash/zsh/fish. Without an argument `fzf` selects the patch; if `fzf` is missing, rows plus a hint are printed and the command exits 1. - **Behavior change: interactive `diff` selection** - With no path, `diff` now resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. - **`compare` selection ladder** - With no path, `compare` uses the same CWD auto-detect → `fzf` → rows + hint + exit 1 ladder and always operates on exactly one patch. -- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). The legacy append form (for example `vim "+DirDiff"`) is deprecated. +- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). Unset vars keep the minimal form. `DIRDIFF_EXCLUDES` appends extra file/dir names to the exclusion list (`.git` is always ignored) and `DIRDIFF_IGNORE` ignores comma-separated keywords in diff content (converted to a very-nomagic `\V` regexp), e.g. `DIRDIFF_IGNORE=github.com,gitlab.com`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. - **Concise `update` warning** - Local edits now produce one relative, actionable line: `'' differs from upstream; local copy preserved. Compare with: git cross diff `. The `cross.diffTool` configuration hint and the broken DirDiff invocation are gone. #### Fixed diff --git a/Justfile.cross b/Justfile.cross index 1a2a0b354..4fb960bf2 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -811,7 +811,21 @@ compare path="": check-initialized if command -v nvim >/dev/null 2>&1 set editor nvim end - set tool "$editor \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" + # .git is permanently excluded; DIRDIFF_EXCLUDES appends more names. + set -l excludes .git + if set -q DIRDIFF_EXCLUDES; and test -n "$DIRDIFF_EXCLUDES" + set excludes "$excludes,$DIRDIFF_EXCLUDES" + end + set -l cmd $editor + set -a cmd "\"+let g:DirDiffExcludes = '$excludes'\"" + # DIRDIFF_IGNORE: comma-separated keywords ignored in diff content. + if set -q DIRDIFF_IGNORE; and test -n "$DIRDIFF_IGNORE" + set -l items (string split , -- $DIRDIFF_IGNORE) + set -l re "\\V"(string join '\\|' $items) + set -a cmd "\"+let g:DirDiffIgnore = '$re'\"" + end + set -a cmd "\"+DirDiff {left} {right}\"" + set tool (string join ' ' $cmd) end set left "$worktree/$remote_path" if test "$remote_path" = "." diff --git a/README.md b/README.md index f4103d97e..0f2f66e3b 100644 --- a/README.md +++ b/README.md @@ -449,6 +449,26 @@ A custom ignore list passes DirDiff a comma-separated list of names to skip: git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes = '.git,ves.io,f5fed.com,volterra.us'\" \"+DirDiff {left} {right}\"" ``` +### Environment variables (when `cross.diffTool` is unset) + +Two optional variables feed the built-in default; both are comma-separated: + +| Variable | Effect | +|---|---| +| `DIRDIFF_EXCLUDES` | Extra file/dir names to hide. `.git` is **always** excluded (permanent prefix). | +| `DIRDIFF_IGNORE` | Keywords ignored inside the diff content — useful when the upstream is e.g. `github.com` and your copy is `gitlab.com`. | + +```bash +export DIRDIFF_EXCLUDES='vendor,node_modules,dist' +export DIRDIFF_IGNORE='github.com,gitlab.com' +git cross compare app # -> nvim "+let g:DirDiffExcludes = '.git,vendor,node_modules,dist'" + # "+let g:DirDiffIgnore = '\Vgithub.com\|gitlab.com'" "+DirDiff ..." +``` + +`DIRDIFF_IGNORE` is converted to a vim **very-nomagic** regexp (`\V`), so dots +and other characters match literally; items are joined with `\|` (alternation). +Unset or empty variables simply omit the corresponding `+let` argument. + In this form the paths are part of the vim `+` command string, which is where DirDiff reads them. The repository default already ignores `.git`, so the worktree's `.git` pointer file never appears in the comparison. diff --git a/src-go/main.go b/src-go/main.go index 439883564..08f7e21fb 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -275,15 +275,56 @@ func logWarn(msg string) { fmt.Println(msg) } +// envList splits a comma-separated environment variable into trimmed items. +func envList(name string) []string { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + return nil + } + var items []string + for _, part := range strings.Split(raw, ",") { + if p := strings.TrimSpace(part); p != "" { + items = append(items, p) + } + } + return items +} + +// vimValue makes a value safe to embed in a vim single-quoted string and in +// the double-quoted bash argument that carries the +cmd. +func vimValue(s string) string { + s = strings.ReplaceAll(s, "\n", " ") + s = strings.ReplaceAll(s, `"`, "") + return strings.ReplaceAll(s, "'", "''") +} + +// vimIgnoreRegexp turns comma-separated keywords into a vim regexp. +// \V (very nomagic) makes every character literal, so dots etc. need no +// escaping; \| remains alternation. +func vimIgnoreRegexp(keywords []string) string { + escaped := make([]string, 0, len(keywords)) + for _, k := range keywords { + escaped = append(escaped, strings.ReplaceAll(k, `\`, `\\`)) + } + return `\V` + strings.Join(escaped, `\|`) +} + // defaultDiffTool returns the built-in diff tool command: nvim when available, -// otherwise vim. Two separate +cmd arguments: set the exclusion list first, -// then run DirDiff on the given directories. +// otherwise vim. Separate +cmd arguments set the exclusions and, when +// DIRDIFF_IGNORE is set, the diff-content keywords to ignore; then DirDiff runs +// on the given directories. .git is always excluded. func defaultDiffTool() string { editor := "vim" if _, err := exec.LookPath("nvim"); err == nil { editor = "nvim" } - return editor + ` "+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` + excludes := append([]string{".git"}, envList("DIRDIFF_EXCLUDES")...) + args := []string{fmt.Sprintf(`"+let g:DirDiffExcludes = '%s'"`, vimValue(strings.Join(excludes, ",")))} + if keywords := envList("DIRDIFF_IGNORE"); len(keywords) > 0 { + args = append(args, fmt.Sprintf(`"+let g:DirDiffIgnore = '%s'"`, vimValue(vimIgnoreRegexp(keywords)))) + } + args = append(args, `"+DirDiff {left} {right}"`) + return editor + " " + strings.Join(args, " ") } func diffTool() string { @@ -955,7 +996,11 @@ To pin it explicitly (recommended): Strictly vim: - git config --global cross.diffTool "vim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\""`, + git config --global cross.diffTool "vim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" + +Environment variables (used only when cross.diffTool is unset): + DIRDIFF_EXCLUDES extra comma-separated file/dir names to hide; .git is always ignored + DIRDIFF_IGNORE comma-separated keywords ignored in diff content (e.g. github.com,gitlab.com)`, RunE: func(cmd *cobra.Command, args []string) error { return printPatchRows("") }, diff --git a/test/021_fzf_diff_compare.sh b/test/021_fzf_diff_compare.sh index 946d25894..f03537932 100755 --- a/test/021_fzf_diff_compare.sh +++ b/test/021_fzf_diff_compare.sh @@ -140,7 +140,25 @@ SH out=$(PATH="$vim_shims:$no_nvim_path" "$GO_BIN" compare vendor/alpha 2>/dev/null) echo "$out" assert_contains "$out" "EDITOR:vim" "default tool should fall back to vim when nvim is absent" - log_success "editor selection verified (nvim preferred, vim fallback)" + + # environment-driven extras (only when cross.diffTool is unset) + out=$(env -u DIRDIFF_IGNORE -u DIRDIFF_EXCLUDES PATH="$both_shims:$PATH" "$GO_BIN" compare vendor/alpha 2>/dev/null) + assert_contains "$out" "let g:DirDiffExcludes = '.git'" "minimal default keeps .git excluded" + assert_not_contains "$out" "DirDiffIgnore" "no ignore argument should be emitted without DIRDIFF_IGNORE" + + out=$(env -u DIRDIFF_IGNORE DIRDIFF_EXCLUDES="vendor,node_modules" PATH="$both_shims:$PATH" "$GO_BIN" compare vendor/alpha 2>/dev/null) + echo "$out" + assert_contains "$out" "let g:DirDiffExcludes = '.git,vendor,node_modules'" "DIRDIFF_EXCLUDES should append to the permanent .git" + + out=$(env -u DIRDIFF_EXCLUDES DIRDIFF_IGNORE="github.com,gitlab.com" PATH="$both_shims:$PATH" "$GO_BIN" compare vendor/alpha 2>/dev/null) + echo "$out" + assert_contains "$out" "let g:DirDiffIgnore" "DIRDIFF_IGNORE should add an ignore argument" + assert_contains "$out" "github.com" "ignore regexp should include the first keyword" + assert_contains "$out" "gitlab.com" "ignore regexp should include the second keyword" + if ! printf '%s\n' "$out" | grep -qF '\V'; then + fail "DIRDIFF_IGNORE should use a very-nomagic \\V regexp" + fi + log_success "editor selection + env extras verified (nvim preferred, vim fallback)" # --- inside a patched dir: CWD auto-detect, no fzf needed log_header "021: CWD auto-detect still wins inside a patch directory" @@ -227,6 +245,10 @@ if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command - echo "$out" assert_contains "$out" "EDITOR:nvim" "Just default tool should prefer nvim when installed" assert_contains "$out" "let g:DirDiffExcludes = '.git'" "Just default tool should set DirDiffExcludes" + out=$(env -u DIRDIFF_EXCLUDES DIRDIFF_IGNORE="github.com,gitlab.com" PATH="$just_shims:$PATH" just cross compare vendor/alpha 2>/dev/null) + echo "$out" + assert_contains "$out" "let g:DirDiffIgnore" "Just DIRDIFF_IGNORE should add an ignore argument" + assert_contains "$out" "github.com" "Just ignore regexp should include the keyword" log_success "Just editor selection verified" log_header "021: Just CWD auto-detect inside a patch directory" From bb7845c0a621a5b0e4549fb6c0af8165d586e11a Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 20:18:26 +0100 Subject: [PATCH 13/22] feat(cli): shell-init + --clip; keep cd/wt adjacent in help - shell-init [bash|zsh|fish] prints crosscd/crosswt wrappers so a real cd happens in the caller's shell (a child process cannot change its cwd) - cd/wt accept --clip (Go) / clip token (Just) to also copy the printed path; stdout stays path-only, confirmation on stderr - help: authored order keeps cd and wt adjacent (regression assertion in 020) - docs: README quick setup, AGENTS command table, CHANGELOG --- AGENTS.md | 5 ++- CHANGELOG.md | 1 + Justfile.cross | 59 ++++++++++++++++++++++++++- README.md | 40 +++++++++--------- src-go/main.go | 89 +++++++++++++++++++++++++++++++++++++++-- test/017_cd_wt_fix.sh | 52 ++++++++++++++++++++++++ test/020_help_groups.sh | 12 ++++-- 7 files changed, 229 insertions(+), 29 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1510343b3..8acb96fe5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,8 +46,9 @@ test/001-023_*.sh # Individual test files (see coverage matrix below) | `remove` | `` | Delete patch, clean Crossfile and metadata | | `prune` | `[remote]` | Remove remote and all its patches, prune stale worktrees | | `init` | | Create empty Crossfile | -| `cd` | `[path]` | Print absolute local_path to stdout (wrap with `cd "$(git cross cd)"`) | -| `wt` | `[path]` | Print absolute worktree path to stdout | +| `cd` | `[path] [--clip]` | Print absolute local_path to stdout; shell integration via `shell-init` (`crosscd`) | +| `wt` | `[path] [--clip]` | Print absolute worktree path to stdout; `crosswt` wrapper | +| `shell-init` | `[bash\|zsh\|fish]` | Print shell functions that `cd` into patches/worktrees (child processes cannot) | Bare `git cross` prints one `local_pathworktree` row per patch to stdout (no hint line; TTY output is space-padded, piped output stays TAB-separated); `-h` prints the grouped help. Help grouping is Go-only CLI presentation — Just/Fish exposes the same behavior through recipes, not through a grouped help renderer. diff --git a/CHANGELOG.md b/CHANGELOG.md index 548bc3104..4445da999 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Behavior change: interactive `diff` selection** - With no path, `diff` now resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. - **`compare` selection ladder** - With no path, `compare` uses the same CWD auto-detect → `fzf` → rows + hint + exit 1 ladder and always operates on exactly one patch. - **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). Unset vars keep the minimal form. `DIRDIFF_EXCLUDES` appends extra file/dir names to the exclusion list (`.git` is always ignored) and `DIRDIFF_IGNORE` ignores comma-separated keywords in diff content (converted to a very-nomagic `\V` regexp), e.g. `DIRDIFF_IGNORE=github.com,gitlab.com`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. +- **`shell-init` + `--clip`** - `git cross shell-init [bash|zsh|fish]` prints `crosscd`/`crosswt` functions so a real `cd` happens in the caller's shell (a child process cannot change it); `cd`/`wt` keep printing a path and accept `--clip` to also copy it to the clipboard. - **Concise `update` warning** - Local edits now produce one relative, actionable line: `'' differs from upstream; local copy preserved. Compare with: git cross diff `. The `cross.diffTool` configuration hint and the broken DirDiff invocation are gone. #### Fixed diff --git a/Justfile.cross b/Justfile.cross index 4fb960bf2..b1f385381 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -956,7 +956,7 @@ worktree path="": # Print a patch worktree to cd into (use: cd (just cross wt [path])) [no-cd] -wt path="": +wt path="" clip="": #!/usr/bin/env fish set -l resolved_path "{{path}}" # Explicit path: make absolute and ./-prefixed paths repo-relative first @@ -990,10 +990,60 @@ wt path="": end printf '%s\n' $ctx | source echo "{{REPO_DIR}}/$worktree" + if test -n "{{clip}}" + printf '%s' "{{REPO_DIR}}/$worktree" | just cross _clip + or exit 1 + echo "Path copied to clipboard." >&2 + end + +# Internal: copy stdin to the clipboard (pbcopy/xclip/xsel). +[no-cd] +_clip: + #!/usr/bin/env bash + if command -v pbcopy >/dev/null 2>&1; then + pbcopy + elif command -v xclip >/dev/null 2>&1; then + xclip -selection clipboard + elif command -v xsel >/dev/null 2>&1; then + xsel --clipboard --input + else + echo "no clipboard tool found (pbcopy/xclip/xsel)" >&2 + exit 1 + fi + +# Print shell functions that cd into patches/worktrees (a child process cannot). +# Usage: eval "$(git cross shell-init)" (bash/zsh) or eval (git cross shell-init fish) +[no-cd] +shell-init shell="": + #!/usr/bin/env fish + set -l sh "{{shell}}" + if test -z "$sh" + set sh (basename $SHELL 2>/dev/null; or echo bash) + end + if test "$sh" = fish + printf '%s\n' '# git-cross shell integration' \ + 'function crosscd' \ + ' set -l p (git cross cd $argv)' \ + ' or return' \ + ' test -n "$p"; and cd $p' \ + 'end' \ + 'function crosswt' \ + ' set -l p (git cross wt $argv)' \ + ' or return' \ + ' test -n "$p"; and cd $p' \ + 'end' + else if contains -- bash zsh "$sh"; or test -z "$sh" + printf '%s\n' '# git-cross shell integration' \ + 'crosscd() { local p; p="$(git cross cd "$@")" || return; [ -n "$p" ] && cd "$p"; }' \ + 'crosswt() { local p; p="$(git cross wt "$@")" || return; [ -n "$p" ] && cd "$p"; }' + else + echo "unsupported shell: $sh (use bash, zsh or fish)" >&2 + exit 1 + end # Print a patch local_path to cd into (use: cd (just cross cd [path])) [no-cd] -cd path="": +cd path="" clip="": #!/usr/bin/env fish set -l resolved_path "{{path}}" # Explicit path: make absolute and ./-prefixed paths repo-relative first @@ -1027,6 +1077,11 @@ cd path="": end printf '%s\n' $ctx | source echo "{{REPO_DIR}}/$local_path" + if test -n "{{clip}}" + printf '%s' "{{REPO_DIR}}/$local_path" | just cross _clip + or exit 1 + echo "Path copied to clipboard." >&2 + end # AICONTEXT: "status" shows status of current local_path patch vs. WT, and WT upstream. Input argument is local_path (or understand user stand in the under git-cross'ed local_path and call this comand). It shall be called to get status of local_path from "list" command. Either the status of remote WT upstream (as resource consuming, shall be optional or only ocasional) diff --git a/README.md b/README.md index 0f2f66e3b..2742edeee 100644 --- a/README.md +++ b/README.md @@ -190,8 +190,8 @@ Repository: Inspect & Navigate: cd Print a patch local_path to cd into - diff Show changes between local and upstream wt Print a patch worktree to cd into + diff Show changes between local and upstream ``` `compare` also answers to the short alias `git cross cmp`. @@ -373,35 +373,37 @@ Print the absolute destination path for one patch: `cd` targets the local copy (`local_path`), `wt` targets the hidden sparse worktree. The path is the only thing written to stdout; hints and errors go to stderr. -These commands do not start a subshell and do not copy anything to the -clipboard; they print a path for your shell to `cd` into: +These commands do not start a subshell. For a real directory change, add the +shell integration once: ```bash -cd "$(git cross cd vendor/app)" # local copy -cd "$(git cross wt vendor/app)" # sparse worktree -``` +# bash / zsh (~/.bashrc, ~/.zshrc) +eval "$(git cross shell-init)" -For convenience, add wrappers to your shell configuration. - -bash / zsh: - -```bash -crosscd() { cd "$(git cross cd "$@")"; } -crosswt() { cd "$(git cross wt "$@")"; } +# fish (~/.config/fish/config.fish) +eval (git cross shell-init fish) ``` -fish: +That defines `crosscd` and `crosswt`, which `cd` into the path printed by the +tool (or keep using the direct form): -```fish -function crosscd; cd (git cross cd $argv); end -function crosswt; cd (git cross wt $argv); end +```bash +crosscd vendor/app # cd into the local copy (fzf if omitted) +crosswt vendor/app # cd into the sparse worktree +cd "$(git cross cd vendor/app)" ``` A child process cannot change the working directory of the shell that started it, so the tool cannot `cd` for you. The wrapper does the `cd` in your shell using the path the tool prints. Keeping stdout path-only also makes the output -composable in scripts (`dir=$(git cross cd vendor/app)`) and editor -integrations. +composable in scripts (`dir=$(git cross cd vendor/app)`). + +If you prefer the old clipboard workflow, add `--clip` to copy the printed path +as well (stdout stays path-only; the confirmation goes to stderr): + +```bash +git cross wt --clip vendor/app +``` With an explicit path the patch is resolved directly. Without one, `fzf` is used to select a patch. If `fzf` is not installed, the command prints the diff --git a/src-go/main.go b/src-go/main.go index 08f7e21fb..def928b12 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -974,6 +974,47 @@ func runNoIndexDiff(upstreamPath, localPath string) { _ = c.Run() } +const posixShellInit = `# git-cross shell integration (add to ~/.bashrc or ~/.zshrc): +# eval "$(git cross shell-init)" +crosscd() { local p; p="$(git cross cd "$@")" || return; [ -n "$p" ] && cd "$p"; } +crosswt() { local p; p="$(git cross wt "$@")" || return; [ -n "$p" ] && cd "$p"; } +` + +const fishShellInit = `# git-cross shell integration (add to ~/.config/fish/config.fish): +# eval (git cross shell-init fish) +function crosscd --description 'cd into a git-cross patch' + set -l p (git cross cd $argv) + or return + test -n "$p"; and cd $p +end +function crosswt --description 'cd into a git-cross worktree' + set -l p (git cross wt $argv) + or return + test -n "$p"; and cd $p +end +` + +// copyToClipboard copies text using the first available platform tool. +func copyToClipboard(text string) error { + candidates := [][]string{ + {"pbcopy"}, + {"xclip", "-selection", "clipboard"}, + {"xsel", "--clipboard", "--input"}, + } + for _, cand := range candidates { + if _, err := exec.LookPath(cand[0]); err != nil { + continue + } + c := exec.Command(cand[0], cand[1:]...) + c.Stdin = strings.NewReader(text) + if err := c.Run(); err != nil { + return fmt.Errorf("%s failed: %w", cand[0], err) + } + return nil + } + return errors.New("no clipboard tool found (pbcopy/xclip/xsel)") +} + func main() { // Keep authored order in --help: use/patch must come first. cobra.EnableCommandSorting = false @@ -1705,6 +1746,12 @@ Environment variables (used only when cross.diffTool is unset): return nil } fmt.Println(abs) // stdout contract: path only + if clip, _ := cmd.Flags().GetBool("clip"); clip { + if cerr := copyToClipboard(abs); cerr != nil { + return cerr + } + fmt.Fprintln(os.Stderr, "Path copied to clipboard.") + } return nil }, } @@ -1712,14 +1759,50 @@ Environment variables (used only when cross.diffTool is unset): cdCmd := makeDirCmd("cd [path]", "Print a patch local_path to cd into (use: cd \"$(git cross cd)\")", - "Print the absolute path of a patch local_path to stdout (use: cd \"$(git cross cd)\").\n\nWith path: prints the specified local_path.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.", + "Print the absolute path of a patch local_path to stdout (use: cd \"$(git cross cd)\").\n\nWith path: prints the specified local_path.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.\n\nUse --clip to also copy the path to the clipboard.\nFor real directory changes add shell integration:\n eval \"$(git cross shell-init)\" # then: crosscd [path]", "local_path") wtCmd := makeDirCmd("wt [path]", "Print a patch worktree to cd into (use: cd \"$(git cross wt)\")", - "Print the absolute path of a patch worktree to stdout (use: cd \"$(git cross wt)\").\n\nWith path: prints the specified worktree.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.", + "Print the absolute path of a patch worktree to stdout (use: cd \"$(git cross wt)\").\n\nWith path: prints the specified worktree.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.\n\nUse --clip to also copy the path to the clipboard.\nFor real directory changes add shell integration:\n eval \"$(git cross shell-init)\" # then: crosswt [path]", "worktree") + cdCmd.Flags().Bool("clip", false, "also copy the printed path to the clipboard") + wtCmd.Flags().Bool("clip", false, "also copy the printed path to the clipboard") + + shellInitCmd := &cobra.Command{ + Use: "shell-init [bash|zsh|fish]", + Short: "Print shell functions that cd into patches and worktrees", + GroupID: "repo", + Args: cobra.MaximumNArgs(1), + Long: `Print shell functions to evaluate in your shell profile. They wrap +'git cross cd' / 'git cross wt' with cd, because a child process cannot change +the caller's working directory by itself. + + bash/zsh: eval "$(git cross shell-init)" + fish: eval (git cross shell-init fish) + +After that, 'crosscd' and 'crosswt' change directory directly, with the same +optional path argument and fzf selection as the git-cross commands.`, + RunE: func(cmd *cobra.Command, args []string) error { + shell := "" + if len(args) > 0 { + shell = strings.ToLower(strings.TrimSpace(args[0])) + } else { + shell = filepath.Base(os.Getenv("SHELL")) + } + switch shell { + case "fish": + fmt.Print(fishShellInit) + case "bash", "zsh", "": + fmt.Print(posixShellInit) + default: + return fmt.Errorf("unsupported shell %q (use bash, zsh or fish)", shell) + } + return nil + }, + } + listCmd := &cobra.Command{ Use: "list", Short: "Show all configured patches and remotes", @@ -2345,7 +2428,7 @@ if fzf is unavailable it prints the available patches.`, // Retain superseded implementations in source as internal reference, but do // not expose them as supported commands. _, _, _, _ = syncCmd, replayCmd, pushCmd, execCmd - rootCmd.AddCommand(useCmd, patchCmd, removeCmd, pruneCmd, initCmd, listCmd, statusCmd, updateCmd, compareCmd, cdCmd, wtCmd, diffCmd) + rootCmd.AddCommand(useCmd, patchCmd, removeCmd, pruneCmd, initCmd, listCmd, statusCmd, updateCmd, compareCmd, shellInitCmd, cdCmd, wtCmd, diffCmd) if err := rootCmd.Execute(); err != nil { os.Exit(1) } diff --git a/test/017_cd_wt_fix.sh b/test/017_cd_wt_fix.sh index 08ad8f29d..f709884d7 100755 --- a/test/017_cd_wt_fix.sh +++ b/test/017_cd_wt_fix.sh @@ -98,6 +98,36 @@ if [ -n "$GO_BIN" ]; then || fail "Go wt without a path inside a patch should auto-detect" assert_one_abs_path "Go wt (CWD auto-detect)" "$out" "$wt_abs" popd >/dev/null + + log_header "017: Go --clip copies the path and keeps stdout clean" + clip_dir="$SANDBOX/clip-shims" + mkdir -p "$clip_dir" + cat > "$clip_dir/pbcopy" <<'SH' +#!/bin/sh +cat > "$CLIP_FILE" +SH + chmod +x "$clip_dir/pbcopy" + out=$(CLIP_FILE="$SANDBOX/clipped.txt" PATH="$clip_dir:$PATH" \ + "$GO_BIN" cd vendor/src --clip 2>"$SANDBOX/clip.err") \ + || fail "Go cd --clip should succeed with a clipboard tool" + assert_one_abs_path "Go cd --clip stdout" "$out" "$local_abs" + [ "$(cat "$SANDBOX/clipped.txt")" = "$local_abs" ] \ + || fail "Go cd --clip should copy the absolute path" + assert_contains "$(cat "$SANDBOX/clip.err")" "copied to clipboard" \ + "clipboard confirmation belongs on stderr" + log_success "Go --clip verified" + + log_header "017: Go shell-init prints cd wrappers" + init_bash=$("$GO_BIN" shell-init bash 2>&1) || fail "shell-init bash should exit 0" + assert_contains "$init_bash" "crosscd()" "bash init should define crosscd" + assert_contains "$init_bash" "crosswt()" "bash init should define crosswt" + printf '%s\n' "$init_bash" | bash -n || fail "bash init must be valid bash" + init_fish=$("$GO_BIN" shell-init fish 2>&1) || fail "shell-init fish should exit 0" + assert_contains "$init_fish" "function crosscd" "fish init should define crosscd" + init_rc=0 + "$GO_BIN" shell-init powershell >/dev/null 2>&1 || init_rc=$? + [ "$init_rc" -eq 1 ] || fail "unsupported shell should exit 1, got $init_rc" + log_success "Go shell-init verified" log_success "Go CWD auto-detect verified" log_header "017: Go fzf selection prints the selected path" @@ -155,6 +185,28 @@ if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command - [ "$wt_rc" -eq 1 ] || fail "Just wt without fzf should exit 1, got $wt_rc" assert_contains "$wt_out" "fzf is not installed" "Just wt fallback should say fzf is missing" log_success "Just fzf-missing fallback verified" + + log_header "017: Just clip + shell-init" + clip_dir="$SANDBOX/clip-shims" + mkdir -p "$clip_dir" + cat > "$clip_dir/pbcopy" <<'SH' +#!/bin/sh +cat > "$CLIP_FILE" +SH + chmod +x "$clip_dir/pbcopy" + out=$(CLIP_FILE="$SANDBOX/clipped-just.txt" PATH="$clip_dir:$PATH" \ + just cross cd vendor/src 1 2>"$SANDBOX/clip-just.err") \ + || fail "Just cd with clip should succeed with a clipboard tool" + assert_one_abs_path "Just cd clip stdout" "$out" "$local_abs" + [ "$(cat "$SANDBOX/clipped-just.txt")" = "$local_abs" ] \ + || fail "Just cd clip should copy the absolute path" + assert_contains "$(cat "$SANDBOX/clip-just.err")" "copied to clipboard" \ + "Just clipboard confirmation belongs on stderr" + + init_bash=$(just cross shell-init bash 2>&1) || fail "Just shell-init bash should exit 0" + assert_contains "$init_bash" "crosscd()" "Just bash init should define crosscd" + printf '%s\n' "$init_bash" | bash -n || fail "Just bash init must be valid bash" + log_success "Just clip + shell-init verified" else echo "SKIP: fish and/or jq/just unavailable; skipping Just cd/wt assertions" fi diff --git a/test/020_help_groups.sh b/test/020_help_groups.sh index 188e272a6..1ae2b45d0 100755 --- a/test/020_help_groups.sh +++ b/test/020_help_groups.sh @@ -39,7 +39,7 @@ repo_section=$(section_body "Repository:") inspect_section=$(section_body "Inspect & Navigate:") patches_section=$(section_body "Patch Lifecycle:") -for cmd in compare init list status update; do +for cmd in compare init list status update shell-init; do printf '%s\n' "$repo_section" | grep -Eq "^ ${cmd}([[:space:]]|$)" \ || fail "'$cmd' should be listed under 'Repository:'" done @@ -53,8 +53,14 @@ for cmd in use patch remove prune; do done log_success "commands grouped correctly" +log_header "020: cd and wt stay adjacent" +inspect_order=$(printf '%s\n' "$inspect_section" | awk '/^ [a-z]/{print $1}') +adjacent=$(printf '%s\n' "$inspect_order" | awk 'prev=="cd" && $0=="wt" {found=1} {prev=$0} END{print found?"yes":"no"}') +[ "$adjacent" = "yes" ] || fail "cd and wt must be listed next to each other (got: $(printf '%s ' $inspect_order))" +log_success "cd/wt adjacency verified" + log_header "020: every visible command appears exactly once" -for cmd in compare init list status update cd wt diff use patch remove prune; do +for cmd in compare init list status update shell-init cd wt diff use patch remove prune; do count=$(printf '%s\n' "$help_output" | grep -cE "^ ${cmd}([[:space:]]|$)") [ "$count" -eq 1 ] || fail "command '$cmd' should appear exactly once in help (found $count)" done @@ -62,7 +68,7 @@ done # command under "Additional Commands:". Tolerate those built-ins, but no # documented command may end up ungrouped there. additional_section=$(section_body "Additional Commands:") -for cmd in compare init list status update cd wt diff use patch remove prune; do +for cmd in compare init list status update shell-init cd wt diff use patch remove prune; do if printf '%s\n' "$additional_section" | grep -Eq "^ ${cmd}([[:space:]]|$)"; then fail "'$cmd' must not fall into 'Additional Commands:' (missing GroupID)" fi From 498f7d93c47b525c49ee29b93923504b73007e44 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 20:21:04 +0100 Subject: [PATCH 14/22] refactor(cli): park clipboard helper as dead code; correct worktree path docs - cd/wt no longer accept --clip: shell-init (crosscd/crosswt) provides the real cd, making the clipboard workflow obsolete - copyToClipboard (Go) / _clip (Just) kept isolated and unused for possible reuse - docs: worktrees are documented only as .cross/worktrees/_; stale .git/cross/worktrees references fixed in constitution.md and TODO.md; no .git/modules or $GIT_DIR layout is documented - README: concrete on-disk layout diagram for .cross/, Crossfile, local copy --- .specify/memory/constitution.md | 2 +- AGENTS.md | 7 +++--- CHANGELOG.md | 2 +- Justfile.cross | 16 ++++---------- README.md | 23 ++++++++++++++------ TODO.md | 2 +- src-go/main.go | 19 ++++++----------- test/017_cd_wt_fix.sh | 38 ++------------------------------- 8 files changed, 36 insertions(+), 73 deletions(-) diff --git a/.specify/memory/constitution.md b/.specify/memory/constitution.md index 08d5a342a..174144499 100644 --- a/.specify/memory/constitution.md +++ b/.specify/memory/constitution.md @@ -25,7 +25,7 @@ This constitutional document establishes the core principles governing the desig **git-cross SHALL protect worktree cleanliness and prevent data loss.** -- Hidden worktrees (`.git/cross/worktrees/`) store upstream state +- Hidden worktrees (`.cross/worktrees/_`) store upstream state - Automatic stashing before pulls preserves local modifications in worktrees - Commands abort on dirty state when modifications could be lost - Explicit confirmation required for destructive operations diff --git a/AGENTS.md b/AGENTS.md index 8acb96fe5..5bdf6f6a2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,8 +46,8 @@ test/001-023_*.sh # Individual test files (see coverage matrix below) | `remove` | `` | Delete patch, clean Crossfile and metadata | | `prune` | `[remote]` | Remove remote and all its patches, prune stale worktrees | | `init` | | Create empty Crossfile | -| `cd` | `[path] [--clip]` | Print absolute local_path to stdout; shell integration via `shell-init` (`crosscd`) | -| `wt` | `[path] [--clip]` | Print absolute worktree path to stdout; `crosswt` wrapper | +| `cd` | `[path]` | Print absolute local_path to stdout; shell integration via `shell-init` (`crosscd`) | +| `wt` | `[path]` | Print absolute worktree path to stdout; `crosswt` wrapper | | `shell-init` | `[bash\|zsh\|fish]` | Print shell functions that `cd` into patches/worktrees (child processes cannot) | Bare `git cross` prints one `local_pathworktree` row per patch to stdout (no hint line; TTY output is space-padded, piped output stays TAB-separated); `-h` prints the grouped help. Help grouping is Go-only CLI presentation — Just/Fish exposes the same behavior through recipes, not through a grouped help renderer. @@ -188,11 +188,12 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 ## Implementation Details -- **Hidden worktrees**: `.cross/worktrees/_` (verified in `src-go/main.go`; Justfile.cross uses the same path). A stale `AICONTEXT` comment in `Justfile.cross` (line 697) still says `.git/cross/worktrees/` and should be corrected by the Just owner. +- **Hidden worktrees**: `.cross/worktrees/_` (verified in `src-go/main.go`; Justfile.cross uses the same path). - **`.git` exclusion**: a worktree root contains a `.git` pointer file that never exists in the local copy (rsync uses `--exclude .git`). Boolean tree comparisons use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff (`git diff --no-index`) is run against a temporary `.git`-free mirror of the worktree, because pathspec excludes like `:(exclude).git` are rejected by older git versions with a usage error. Without both exclusions, whole-repo patches always look modified. - **Sparse checkout**: `git sparse-checkout init --no-cone` + `git sparse-checkout set /` + `git read-tree -mu HEAD`. The trailing `/` on the pattern is required for reliable directory matching in `--no-cone` mode on newer Git versions (2.43+). `read-tree -mu HEAD` explicitly materializes the worktree (bare `git checkout` can no-op after `--no-checkout`). - **Rsync**: `rsync -av --delete --exclude .git` for worktree-to-local sync. `--delete` removes files locally that were deleted upstream. - **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `nvim` when installed, else `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). When unset, env vars extend the default: `DIRDIFF_EXCLUDES` appends names to the exclusion list (`.git` stays permanent) and `DIRDIFF_IGNORE` adds `g:DirDiffIgnore` with a very-nomagic (`\V`) alternation of the comma-separated keywords. Empty/unset vars omit the corresponding argument. Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). +- **Clipboard helper (parked)**: `copyToClipboard` (Go) / `_clip` (Just) remain implemented but are intentionally unused — `cd`/`wt` print a path and `shell-init` provides the real `cd`, which made the clipboard workflow obsolete. Reuse rather than reimplement if a clipboard feature returns. - **Patch rows**: bare `git cross`, and path-miss cases in `compare`/`diff`/`remove`/`cd`/`wt`, print `local_pathworktree` rows to stdout; hints go to stderr and the command exits 1 where nothing was resolved. - **`list --raw` schema**: remotes first (`REMOTE_NAMEREMOTE_URL`), then patches (`REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`); no banners, no borders, deterministic remote order. - **Crossfile format**: Lines like `cross use ` or `cross patch :: `. `update` interprets only these declarative commands; arbitrary shell commands are not executed. diff --git a/CHANGELOG.md b/CHANGELOG.md index 4445da999..c25664ae7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Behavior change: interactive `diff` selection** - With no path, `diff` now resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. - **`compare` selection ladder** - With no path, `compare` uses the same CWD auto-detect → `fzf` → rows + hint + exit 1 ladder and always operates on exactly one patch. - **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). Unset vars keep the minimal form. `DIRDIFF_EXCLUDES` appends extra file/dir names to the exclusion list (`.git` is always ignored) and `DIRDIFF_IGNORE` ignores comma-separated keywords in diff content (converted to a very-nomagic `\V` regexp), e.g. `DIRDIFF_IGNORE=github.com,gitlab.com`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. -- **`shell-init` + `--clip`** - `git cross shell-init [bash|zsh|fish]` prints `crosscd`/`crosswt` functions so a real `cd` happens in the caller's shell (a child process cannot change it); `cd`/`wt` keep printing a path and accept `--clip` to also copy it to the clipboard. +- **`shell-init`** - `git cross shell-init [bash|zsh|fish]` prints `crosscd`/`crosswt` functions so a real `cd` happens in the caller's shell (a child process cannot change it). The clipboard fallback is no longer wired into `cd`/`wt`; its helper is kept isolated (unused) for possible reuse. - **Concise `update` warning** - Local edits now produce one relative, actionable line: `'' differs from upstream; local copy preserved. Compare with: git cross diff `. The `cross.diffTool` configuration hint and the broken DirDiff invocation are gone. #### Fixed diff --git a/Justfile.cross b/Justfile.cross index b1f385381..91a9efa75 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -956,7 +956,7 @@ worktree path="": # Print a patch worktree to cd into (use: cd (just cross wt [path])) [no-cd] -wt path="" clip="": +wt path="": #!/usr/bin/env fish set -l resolved_path "{{path}}" # Explicit path: make absolute and ./-prefixed paths repo-relative first @@ -990,13 +990,10 @@ wt path="" clip="": end printf '%s\n' $ctx | source echo "{{REPO_DIR}}/$worktree" - if test -n "{{clip}}" - printf '%s' "{{REPO_DIR}}/$worktree" | just cross _clip - or exit 1 - echo "Path copied to clipboard." >&2 - end # Internal: copy stdin to the clipboard (pbcopy/xclip/xsel). +# Currently unused: cd/wt print a path and shell-init provides the real cd. +# Kept isolated for possible reuse. [no-cd] _clip: #!/usr/bin/env bash @@ -1043,7 +1040,7 @@ shell-init shell="": # Print a patch local_path to cd into (use: cd (just cross cd [path])) [no-cd] -cd path="" clip="": +cd path="": #!/usr/bin/env fish set -l resolved_path "{{path}}" # Explicit path: make absolute and ./-prefixed paths repo-relative first @@ -1077,11 +1074,6 @@ cd path="" clip="": end printf '%s\n' $ctx | source echo "{{REPO_DIR}}/$local_path" - if test -n "{{clip}}" - printf '%s' "{{REPO_DIR}}/$local_path" | just cross _clip - or exit 1 - echo "Path copied to clipboard." >&2 - end # AICONTEXT: "status" shows status of current local_path patch vs. WT, and WT upstream. Input argument is local_path (or understand user stand in the under git-cross'ed local_path and call this comand). It shall be called to get status of local_path from "list" command. Either the status of remote WT upstream (as resource consuming, shall be optional or only ocasional) diff --git a/README.md b/README.md index 2742edeee..013c41e6a 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,22 @@ git cross update vendor/docs 3. A local physical directory such as `vendor/docs` 4. A `Crossfile` that records how to rebuild the setup +On disk: + +```text +your-repo/ +├── Crossfile # declarative use/patch records +├── .cross/ +│ ├── metadata.json # patch registry (worktree, branch, paths) +│ └── worktrees/ +│ └── _/ # sparse git worktree; contains a .git pointer FILE +│ └── / # checked-out upstream subtree +└── vendor/docs/ # rsynced files; no .git at all +``` + +Worktrees live in the repository tree under `.cross/` (gitignored), and the +local directory holds plain rsynced files with no `.git` of its own. + In practice: - your editor sees normal files @@ -398,13 +414,6 @@ it, so the tool cannot `cd` for you. The wrapper does the `cd` in your shell using the path the tool prints. Keeping stdout path-only also makes the output composable in scripts (`dir=$(git cross cd vendor/app)`). -If you prefer the old clipboard workflow, add `--clip` to copy the printed path -as well (stdout stays path-only; the confirmation goes to stderr): - -```bash -git cross wt --clip vendor/app -``` - With an explicit path the patch is resolved directly. Without one, `fzf` is used to select a patch. If `fzf` is not installed, the command prints the available patch rows plus a hint to `cd` manually, and exits 1. diff --git a/TODO.md b/TODO.md index dd5f15cb5..90bc47e1b 100644 --- a/TODO.md +++ b/TODO.md @@ -65,7 +65,7 @@ - [x] **Fix `cross cd` and `cross wt` commands** - Correct behavior for navigation - **Issue:** Commands needed proper separation of concerns and clipboard functionality - **Design Intent:** - - `cross wt [path]` → Navigate to WORKTREE (`.git/cross/worktrees/`) - for git history operations + - `cross wt [path]` → Navigate to WORKTREE (`.cross/worktrees/_`) - for git history operations - `cross cd [path]` → Navigate to LOCAL_PATH (patched directory) - for editing files - With explicit path: Open subshell in target directory - Without path (fzf): Copy selected path to clipboard for flexibility diff --git a/src-go/main.go b/src-go/main.go index def928b12..fc3fe13b2 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -994,7 +994,11 @@ function crosswt --description 'cd into a git-cross worktree' end ` -// copyToClipboard copies text using the first available platform tool. +// copyToClipboard copies text using the first available platform tool +// (pbcopy/xclip/xsel). +// +// Currently unused: cd/wt print a path and shell-init provides the real cd, so +// the clipboard workflow is obsolete. Kept isolated for possible reuse. func copyToClipboard(text string) error { candidates := [][]string{ {"pbcopy"}, @@ -1746,12 +1750,6 @@ Environment variables (used only when cross.diffTool is unset): return nil } fmt.Println(abs) // stdout contract: path only - if clip, _ := cmd.Flags().GetBool("clip"); clip { - if cerr := copyToClipboard(abs); cerr != nil { - return cerr - } - fmt.Fprintln(os.Stderr, "Path copied to clipboard.") - } return nil }, } @@ -1759,17 +1757,14 @@ Environment variables (used only when cross.diffTool is unset): cdCmd := makeDirCmd("cd [path]", "Print a patch local_path to cd into (use: cd \"$(git cross cd)\")", - "Print the absolute path of a patch local_path to stdout (use: cd \"$(git cross cd)\").\n\nWith path: prints the specified local_path.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.\n\nUse --clip to also copy the path to the clipboard.\nFor real directory changes add shell integration:\n eval \"$(git cross shell-init)\" # then: crosscd [path]", + "Print the absolute path of a patch local_path to stdout (use: cd \"$(git cross cd)\").\n\nWith path: prints the specified local_path.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.\n\nFor real directory changes add shell integration:\n eval \"$(git cross shell-init)\" # then: crosscd [path]", "local_path") wtCmd := makeDirCmd("wt [path]", "Print a patch worktree to cd into (use: cd \"$(git cross wt)\")", - "Print the absolute path of a patch worktree to stdout (use: cd \"$(git cross wt)\").\n\nWith path: prints the specified worktree.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.\n\nUse --clip to also copy the path to the clipboard.\nFor real directory changes add shell integration:\n eval \"$(git cross shell-init)\" # then: crosswt [path]", + "Print the absolute path of a patch worktree to stdout (use: cd \"$(git cross wt)\").\n\nWith path: prints the specified worktree.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.\n\nFor real directory changes add shell integration:\n eval \"$(git cross shell-init)\" # then: crosswt [path]", "worktree") - cdCmd.Flags().Bool("clip", false, "also copy the printed path to the clipboard") - wtCmd.Flags().Bool("clip", false, "also copy the printed path to the clipboard") - shellInitCmd := &cobra.Command{ Use: "shell-init [bash|zsh|fish]", Short: "Print shell functions that cd into patches and worktrees", diff --git a/test/017_cd_wt_fix.sh b/test/017_cd_wt_fix.sh index f709884d7..067a3a11f 100755 --- a/test/017_cd_wt_fix.sh +++ b/test/017_cd_wt_fix.sh @@ -99,24 +99,6 @@ if [ -n "$GO_BIN" ]; then assert_one_abs_path "Go wt (CWD auto-detect)" "$out" "$wt_abs" popd >/dev/null - log_header "017: Go --clip copies the path and keeps stdout clean" - clip_dir="$SANDBOX/clip-shims" - mkdir -p "$clip_dir" - cat > "$clip_dir/pbcopy" <<'SH' -#!/bin/sh -cat > "$CLIP_FILE" -SH - chmod +x "$clip_dir/pbcopy" - out=$(CLIP_FILE="$SANDBOX/clipped.txt" PATH="$clip_dir:$PATH" \ - "$GO_BIN" cd vendor/src --clip 2>"$SANDBOX/clip.err") \ - || fail "Go cd --clip should succeed with a clipboard tool" - assert_one_abs_path "Go cd --clip stdout" "$out" "$local_abs" - [ "$(cat "$SANDBOX/clipped.txt")" = "$local_abs" ] \ - || fail "Go cd --clip should copy the absolute path" - assert_contains "$(cat "$SANDBOX/clip.err")" "copied to clipboard" \ - "clipboard confirmation belongs on stderr" - log_success "Go --clip verified" - log_header "017: Go shell-init prints cd wrappers" init_bash=$("$GO_BIN" shell-init bash 2>&1) || fail "shell-init bash should exit 0" assert_contains "$init_bash" "crosscd()" "bash init should define crosscd" @@ -186,27 +168,11 @@ if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command - assert_contains "$wt_out" "fzf is not installed" "Just wt fallback should say fzf is missing" log_success "Just fzf-missing fallback verified" - log_header "017: Just clip + shell-init" - clip_dir="$SANDBOX/clip-shims" - mkdir -p "$clip_dir" - cat > "$clip_dir/pbcopy" <<'SH' -#!/bin/sh -cat > "$CLIP_FILE" -SH - chmod +x "$clip_dir/pbcopy" - out=$(CLIP_FILE="$SANDBOX/clipped-just.txt" PATH="$clip_dir:$PATH" \ - just cross cd vendor/src 1 2>"$SANDBOX/clip-just.err") \ - || fail "Just cd with clip should succeed with a clipboard tool" - assert_one_abs_path "Just cd clip stdout" "$out" "$local_abs" - [ "$(cat "$SANDBOX/clipped-just.txt")" = "$local_abs" ] \ - || fail "Just cd clip should copy the absolute path" - assert_contains "$(cat "$SANDBOX/clip-just.err")" "copied to clipboard" \ - "Just clipboard confirmation belongs on stderr" - + log_header "017: Just shell-init prints cd wrappers" init_bash=$(just cross shell-init bash 2>&1) || fail "Just shell-init bash should exit 0" assert_contains "$init_bash" "crosscd()" "Just bash init should define crosscd" printf '%s\n' "$init_bash" | bash -n || fail "Just bash init must be valid bash" - log_success "Just clip + shell-init verified" + log_success "Just shell-init verified" else echo "SKIP: fish and/or jq/just unavailable; skipping Just cd/wt assertions" fi From 4620aa921d7ee82f487d620b6394f49311dfe172 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 20:24:32 +0100 Subject: [PATCH 15/22] release: 0.4.0 - VERSION, Go binary --version, README badge, CICD tag example -> 0.4.0 - CHANGELOG: consolidate [Unreleased] into [0.4.0] - 2026-11-11 with deduplicated Added/Changed/Fixed/Documentation sections; correct the .git-exclusion note (mirror, not pathspec); add shell-init, help ordering, TTY-aligned listings, root Justfile arg forwarding, harness fixes --- .github/CICD.md | 4 +-- CHANGELOG.md | 77 +++++++++++++++++++++++-------------------------- README.md | 2 +- VERSION | 2 +- src-go/main.go | 2 +- 5 files changed, 41 insertions(+), 46 deletions(-) diff --git a/.github/CICD.md b/.github/CICD.md index 10a95d5f7..259ecd139 100644 --- a/.github/CICD.md +++ b/.github/CICD.md @@ -59,8 +59,8 @@ Added to README.md header: ### Creating a Release ```bash # Tag and push -git tag v0.2.1 -git push origin v0.2.1 +git tag v0.4.0 +git push origin v0.4.0 # GitHub Actions will automatically: # 1. Create a release diff --git a/CHANGELOG.md b/CHANGELOG.md index c25664ae7..6a3347750 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,61 +7,56 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### UX Refresh — navigation, selection, listing, diff tool +## [0.4.0] - 2026-11-11 + +### UX refresh — navigation, selection, listing, diff tool #### Added - **`git cross cmp`** - Short alias for `compare`; the canonical name is unchanged. -- **Grouped `--help` output** - Commands are now listed under `Repository:`, `Inspect & Navigate:`, and `Patch Lifecycle:` instead of one flat list. `git cross -h` still prints full help. -- **`list --raw` and `list --no-header`** - `--raw` emits tab-separated rows with no table borders and no `==>` banners; `--no-header` omits the header line. Raw column order is documented and fixed: `REMOTE_NAMEREMOTE_URL` first, then `REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`. Remote rows are sorted deterministically, remotes with distinct fetch/push URLs produce one row per URL without `(fetch)`/`(push)` suffixes, and the empty-state message goes to stderr in raw mode. -- **Patch row listings** - Bare `git cross` prints one `local_pathworktree` row per patch to stdout (hint to stderr) instead of Cobra help. Unresolved `compare` / `diff` / `remove` / `cd` / `wt` invocations print the same rows and exit 1 instead of dumping a usage block. -- **Tests 019, 020, 021, 023** - Cover whole-repo patches plus row listings, grouped help, fzf-driven `diff`/`compare`, and `local_path` normalization. +- **Grouped `--help` output** - Commands are listed under `Patch Lifecycle:`, `Repository:`, and `Inspect & Navigate:` instead of one flat list. `use` and `patch` appear first (in that order), and `cd`/`wt` stay adjacent. `git cross -h` still prints full help, and the help text documents `cross.diffTool` setup. +- **`shell-init`** - `git cross shell-init [bash|zsh|fish]` prints `crosscd`/`crosswt` functions that perform a real `cd` in the caller's shell (a child process cannot change it). The clipboard fallback is no longer wired into `cd`/`wt`; its helper is kept isolated (unused) for possible reuse. +- **`list --raw` and `list --no-header`** - `--raw` emits tab-separated rows with no table borders and no `==>` banners; `--no-header` omits the header line. Raw column order is documented and fixed: `REMOTE_NAMEREMOTE_URL` first, then `REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`. Remote rows are sorted deterministically, remotes with distinct fetch/push URLs produce one row per URL without `(fetch)`/`(push)` suffixes, and the empty-state message goes to stderr in raw mode. On a terminal the columns are space-padded for readability; piped output stays TAB-separated. +- **Patch row listings** - Bare `git cross` prints one `local_pathworktree` row per patch to stdout instead of Cobra help (rows are aligned on a TTY, TAB-separated when piped; no hint line). Unresolved `compare` / `diff` / `remove` / `cd` / `wt` invocations print the same rows and exit 1 instead of dumping a usage block. +- **Tests 019, 020, 021, 023** - Cover whole-repo patches plus row listings, grouped help and ordering, fzf-driven `diff`/`compare`, editor selection, and `local_path` normalization. #### Changed -- **BREAKING: `cd` / `wt` print a path instead of opening a shell** - Both commands print the absolute destination path to stdout (hints to stderr). They no longer start a subshell and no longer copy anything to the clipboard. Use `cd "$(git cross cd)"`, `cd "$(git cross wt)"`, or the documented `crosscd`/`crosswt` wrappers for bash/zsh/fish. Without an argument `fzf` selects the patch; if `fzf` is missing, rows plus a hint are printed and the command exits 1. -- **Behavior change: interactive `diff` selection** - With no path, `diff` now resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. +- **BREAKING: `cd` / `wt` print a path instead of opening a shell** - Both commands print the absolute destination path to stdout (hints to stderr). They no longer start a subshell and no longer copy anything to the clipboard. Use `cd "$(git cross cd)"`, `cd "$(git cross wt)"`, or the `crosscd`/`crosswt` functions from `git cross shell-init`. Without an argument they auto-detect the current patch, then use `fzf`; if `fzf` is missing, rows plus a hint are printed and the command exits 1. +- **Behavior change: interactive `diff` selection** - With no path, `diff` resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. - **`compare` selection ladder** - With no path, `compare` uses the same CWD auto-detect → `fzf` → rows + hint + exit 1 ladder and always operates on exactly one patch. -- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). Unset vars keep the minimal form. `DIRDIFF_EXCLUDES` appends extra file/dir names to the exclusion list (`.git` is always ignored) and `DIRDIFF_IGNORE` ignores comma-separated keywords in diff content (converted to a very-nomagic `\V` regexp), e.g. `DIRDIFF_IGNORE=github.com,gitlab.com`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. -- **`shell-init`** - `git cross shell-init [bash|zsh|fish]` prints `crosscd`/`crosswt` functions so a real `cd` happens in the caller's shell (a child process cannot change it). The clipboard fallback is no longer wired into `cd`/`wt`; its helper is kept isolated (unused) for possible reuse. +- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). `DIRDIFF_EXCLUDES` appends extra file/dir names to the exclusion list (`.git` is always ignored) and `DIRDIFF_IGNORE` ignores comma-separated keywords in diff content (converted to a very-nomagic `\V` regexp), e.g. `DIRDIFF_IGNORE=github.com,gitlab.com`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. - **Concise `update` warning** - Local edits now produce one relative, actionable line: `'' differs from upstream; local copy preserved. Compare with: git cross diff `. The `cross.diffTool` configuration hint and the broken DirDiff invocation are gone. - -#### Fixed -- **DirDiff invocation** - `compare` passed the two paths as vim file arguments, where DirDiff never saw them. Paths now go inside the vim `+` command string. -- **`.git` false positives in comparisons** - The worktree's `.git` pointer file (never present in the local copy) counted as a local deletion. Boolean checks now use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff excludes `.git` with the `:(exclude).git` pathspec. As a result, whole-repo patches (`remote:.`) no longer always report `Modified` in `status` or always warn in `update`; clean whole-repo patches now update. -- **`local_path` normalization** - A local path such as `./mxc2` was stored verbatim and broke CWD auto-detection (`compare`, `diff`, `cd`/`wt`, `remove`). Paths are normalized on ingestion, normalized defensively during matching, and self-healed on metadata load; the `Crossfile` keeps the user's original spelling. -- **Deterministic `list` ordering** - Remotes are sorted instead of following Go map iteration order. - -### Changed -- **Simplified upstream workflow** - Added `git cross update [path]` to read declarative `use`/`patch` entries from `Crossfile`, fetch upstream, fast-forward sparse worktrees, and install only when the local copy has no edits. Local edits are preserved while the worktree advances for manual comparison. +- **Simplified upstream workflow** - `git cross update [path]` reads declarative `use`/`patch` entries from `Crossfile`, fetches upstream, fast-forwards sparse worktrees, and installs only when the local copy has no edits. Local edits are preserved while the worktree advances for manual comparison. - **Manual contribution workflow** - Retired `push`; use `wt`, `compare`, and ordinary Git commands to manually copy and commit desired changes in the sparse worktree. The comparison tool is configured with `cross.diffTool` (see the Directory Diff Tool section in `README.md`). - **Retired replay and arbitrary Crossfile commands** - `update` interprets only `use` and `patch`; hooks and shell commands are no longer run from Crossfile. - **Supported implementations** - Go remains primary and Just/Fish the reference. Rust source is retained but no longer maintained; release artifacts are Go-only. - **Retired sync workflow** - The prior stash/copy/rebase logic is removed from the supported CLI and Just recipes. +- **`.crossignore` entry syntax** - Override review behavior uses plain non-comment `.crossignore` lines: basename entries such as `.env`, basename globs such as `*.env`, and directory entries such as `config/`. Full `.gitignore` semantics are still not supported. +- **README workflow guidance** - The current `.crossignore` behavior is documented as a review-oriented workflow for local overlay files layered on top of upstream-managed content. -### Added -- **User documentation refresh** - Added a clearer top-level README, a user-facing architecture overview, and a tutorial for local overlays, publishing to your own origin, and sending changes back upstream. -- **Repo-local `sbx` starter kit** - Added `sbx-kits/opencode` plus `sbx-kits/README.md` so users can try `git-cross` in a versioned sandbox setup instead of relying on a home-directory kit path. -- **AI skill documentation pointers** - Expanded the repo docs to point users and agent tools at `.agents/`, `.claude/`, and `.opencode/skills/`. -- **Whole-upstream tutorial** - Added a second tutorial showing how to vendor an entire upstream repository into a local directory with `remote:.` or `remote:/`. -- **Claude sandbox starter** - Added `sbx-kits/claude` so repo-local sandbox examples now cover both OpenCode and Claude. -- **Private fork migration tutorial** - Added a guarded tutorial for migrating an existing private fork or derivative repo to a repo-root `git-cross` patch with explicit backup and override review steps. -- **Repo split tutorial** - Added `docs/tutorials/split-repo-into-upstream-and-private.md`, a concise walkthrough for splitting one original repo into a clean secret-free upstream plus a private `git-cross`-managed fork. Uses a single shared rule: one `.crossignore` and one `git ls-files --ignored --exclude-from=.crossignore` selection piped to `git rm` (remove from upstream) or `rsync` (back up and keep), so the upstream and the fork can never disagree about what is private. The selection command is documented as a repeatable preview (refine `.crossignore` in a loop until it lists exactly the private files) and clarified as non-destructive — the seed removal only strips the throwaway upstream copy while private files stay in the fork as git-cross overlays. The upstream-seed removal deletes the tracked-only selection (`--cached`, without `--others`) with `rm -rf` followed by `git add -A`, instead of `git rm`: `git rm` aborts the whole batch on untracked/gitignored pathspecs (`node_modules/`, `.envrc.local`) and on submodule/embedded-repo gitlinks (`could not lookup name for submodule ...`), whereas working-tree deletion + restage handles files, directories, and gitlinks uniformly. Documented that `rm` has no `--dry-run` (preview via `xargs … echo` or confirm via `rm -rI`/`-ri` with `xargs -o`), and that `test/` matches a `test` directory at any depth while `*/test/*` does not. The backup keeps `--others` so untracked private files are still copied. Each step is labelled with the repo it runs in. - -### Changed -- **`.crossignore` entry syntax** - Override review behavior now uses plain non-comment `.crossignore` lines. Supported forms include basename entries such as `.env` anywhere under the patch, basename globs such as `*.env`, and directory entries such as `config/`. Full `.gitignore` semantics are still not supported. -- **README workflow guidance** - Documented the current `.crossignore` behavior as a review-oriented workflow for local overlay files layered on top of upstream-managed content. - -### Fixed -- **Migration tutorial backup command** - Removed the broken recommendation to call the internal Just `_crossignore_overrides` recipe during private-fork migration. The backup step now expands `.crossignore` (which is a gitignore-style *pattern* prescription, not a literal file list) against the real working tree with `git ls-files --ignored --exclude-from=.crossignore` piped into `rsync`, so globs and not-yet-present paths no longer cause `rsync --files-from` "No such file or directory" failures. Documented the safer "clean upstream seed repo first, then patch into the private repo" workflow. +#### Fixed +- **DirDiff invocation** - `compare` passed the two paths as vim file arguments, where DirDiff never saw them. Paths now go inside the vim `+` command string. +- **`.git` false positives in comparisons** - The worktree's `.git` pointer file (never present in the local copy) counted as a local deletion. Boolean checks now use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff runs `git diff --no-index` against a temporary `.git`-free mirror (pathspec excludes are rejected by older git versions). As a result, whole-repo patches (`remote:.`) no longer always report `Modified` in `status` or always warn in `update`; clean whole-repo patches now update. +- **`local_path` normalization** - A local path such as `./mxc2` was stored verbatim and broke CWD auto-detection (`compare`, `diff`, `cd`/`wt`, `remove`). Paths are normalized on ingestion, normalized defensively during matching, and self-healed on metadata load; the `Crossfile` keeps the user's original spelling. +- **Deterministic `list` ordering** - Remotes are sorted instead of following Go map iteration order. +- **Root `Justfile` argument forwarding** - `just cross …` passed arguments through the shell unquoted, so values containing `;`, `(`, `)`, `<`, `>`, or `|` broke. Arguments are now forwarded with `"$@"` and `[positional-arguments]`. +- **Migration tutorial backup command** - Removed the broken recommendation to call the internal Just `_crossignore_overrides` recipe during private-fork migration. The backup step expands `.crossignore` against the real working tree with `git ls-files --ignored --exclude-from=.crossignore` piped into `rsync`, so globs and not-yet-present paths no longer cause `rsync --files-from` failures. - **Rust override diff build failure** - Renamed a Rust loop variable that used the reserved keyword `override`, restoring Rust CLI builds and regression execution on current toolchains. - **Just override warning output** - Removed a shell-breaking semicolon from the override review warning so `just cross diff` prints the manual review commands correctly. -- **P0: Sparse checkout broken on newer Git versions** - `git sparse-checkout set ` in `--no-cone` mode no longer reliably checks out directories without trailing `/`. Fixed across all three implementations (Go, Rust, Justfile.cross) by appending `/` to sparse-checkout patterns and using `git read-tree -mu HEAD` instead of bare `git checkout` (which can no-op after `--no-checkout`). -- **P0: Go build "inconsistent vendoring" in CI** - Tests that build the Go binary now remove stale `vendor/` directory and pass `-mod=mod` as a direct flag. Added `src-go/vendor/` to `.gitignore` to prevent accidental commits. -- **Whole-repo patching (`:/` and `:.`)** - `cross patch remote:/` and `cross patch remote:.` now correctly patch the entire upstream repo. Previously `/` was rejected as invalid, and `.` produced an empty worktree because sparse-checkout pattern `./` matched nothing. Fix: `/` is normalized to `.`, and `.` skips sparse-checkout entirely (full checkout). -- **Prune leaves orphaned `.cross/worktrees/` directories** - `cross prune` now scans `.cross/worktrees/` and removes directories not referenced in `metadata.json`. Previously only `git worktree prune` was called, which cleans git's internal registry but not the actual cross-managed directories. -- **test/014_remove.sh robustness** - Go binary is now reused if already built; gracefully skips Go tests when Go toolchain is unavailable. - -### Added -- **AI-assisted coding / sandbox workflow documentation** - New README section explaining how git-cross integrates with AI coding tools and container-based development sandboxes (`sbx`, Docker sandbox). Covers subfolder scoping, `Crossfile` reproducibility, and bidirectional sync. +- **P0: Sparse checkout broken on newer Git versions** - `git sparse-checkout set ` in `--no-cone` mode no longer reliably checks out directories without a trailing `/`. Fixed across all implementations by appending `/` to sparse-checkout patterns and using `git read-tree -mu HEAD` instead of bare `git checkout`. +- **P0: Go build "inconsistent vendoring" in CI** - Tests that build the Go binary now remove a stale `vendor/` directory and pass `-mod=mod` as a direct flag. `src-go/vendor/` is gitignored. +- **Whole-repo patching (`:/` and `:.`)** - `cross patch remote:/` and `cross patch remote:.` now correctly patch the entire upstream repo. `/` is normalized to `.`, and `.` skips sparse-checkout entirely (full checkout). +- **Prune leaves orphaned `.cross/worktrees/` directories** - `cross prune` scans `.cross/worktrees/` and removes directories not referenced in `metadata.json`, not just git's internal worktree registry. +- **test/014_remove.sh robustness** - The Go binary is reused if already built, and Go tests skip gracefully when the toolchain is unavailable. +- **Test harness defects** - `setup_sandbox` pins `REPO_ROOT` (no drift on repeated calls), `TESTDIR` defaults for standalone runs, and test 016's Go smoke gate uses a real repository. + +#### Documentation +- **User documentation refresh** - Clearer top-level README, a user-facing architecture overview, and tutorials for local overlays, publishing to your own origin, and sending changes back upstream. +- **Repo-local `sbx` starter kits** - `sbx-kits/opencode` and `sbx-kits/claude` plus `sbx-kits/README.md`, so `git-cross` can be tried in a versioned sandbox setup. +- **AI skill documentation pointers** - Docs point users and agent tools at `.agents/`, `.claude/`, and `.opencode/skills/`. +- **Whole-upstream tutorial** - Second tutorial showing how to vendor an entire upstream repository with `remote:.` or `remote:/`. +- **Private fork migration tutorial** - Guarded tutorial for migrating an existing private fork or derivative repo to a repo-root `git-cross` patch, with explicit backup and override review steps. +- **Repo split tutorial** - `docs/tutorials/split-repo-into-upstream-and-private.md`, walking through splitting one original repo into a clean secret-free upstream plus a private `git-cross`-managed fork using one shared `.crossignore` selection for both directions. +- **AI-assisted coding / sandbox workflow documentation** - README section covering subfolder scoping, `Crossfile` reproducibility, bidirectional sync, and container-based development sandboxes (`sbx`, Docker sandbox). - **test/018_sbx_sandbox.sh** - End-to-end test for the AI sandbox workflow: vendor setup, sandbox isolation (no `.git`), AI file modifications, diff review, upstream push, Crossfile replay, and sync. ## [0.3.0] - 2026-03-28 diff --git a/README.md b/README.md index 013c41e6a..d0452b697 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![CI](https://github.com/epcim/git-cross/workflows/CI/badge.svg)](https://github.com/epcim/git-cross/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Version](https://img.shields.io/badge/version-0.3.0-blue.svg)](https://github.com/epcim/git-cross/blob/main/CHANGELOG.md) +[![Version](https://img.shields.io/badge/version-0.4.0-blue.svg)](https://github.com/epcim/git-cross/blob/main/CHANGELOG.md) `git-cross` is a small tool for pulling part of one Git repository into another with `git worktree` plus `rsync`. diff --git a/VERSION b/VERSION index 0c62199f1..1d0ba9ea1 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.2.1 +0.4.0 diff --git a/src-go/main.go b/src-go/main.go index fc3fe13b2..22fe82933 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -1025,7 +1025,7 @@ func main() { var dry string rootCmd := &cobra.Command{ Use: "git-cross", - Version: "0.3.0", + Version: "0.4.0", Short: "Manage vendored cross-repo patches (worktree + rsync)", SilenceUsage: true, // no Usage dump on errors Long: `Manage vendored cross-repo patches (worktree + rsync). From c12064d0c49ef6542bd0c160914e0fea0a886ac5 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Wed, 11 Nov 2026 20:36:25 +0100 Subject: [PATCH 16/22] feat(cli): enable rerere so conflict resolutions are reused on later updates - init enables rerere.enabled in the shared repo config and reports it (second run says 'already enabled'); patch enables it silently; update re-enables it when missing so pre-existing repos self-heal - Just init resolves the repo root explicitly, so it never writes global config - rerere.autoUpdate stays unset (opt-in); replays apply to the worktree only - README: 'Conflict Resolution Memory (rerere)' section explaining that this solves repeated update/conflict resolution; AGENTS implementation note and coverage matrix; CHANGELOG folded into 0.4.0 - test/024_rerere.sh: config assertions for Go and Just/Fish plus a real resolve-then-replay conflict scenario inside a cross worktree --- AGENTS.md | 8 ++- CHANGELOG.md | 3 +- Justfile.cross | 19 +++++- README.md | 39 +++++++++++ src-go/main.go | 30 ++++++++ test/024_rerere.sh | 166 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 260 insertions(+), 5 deletions(-) create mode 100755 test/024_rerere.sh diff --git a/AGENTS.md b/AGENTS.md index 5bdf6f6a2..914f8a3b7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,7 +92,7 @@ Bare `git cross` prints one `local_pathworktree` row per patch to stdout (n ### Test Structure -Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 exercises Go. Rust, push, and replay legacy tests are excluded from the default runner. Tests 010-023 are focused feature tests; 019-023 cover the UX refresh (row listings and whole-repo patches, grouped help, fzf selection, `local_path` normalization). +Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 exercises Go. Rust, push, and replay legacy tests are excluded from the default runner. Tests 010-024 are focused feature tests; 019-023 cover the UX refresh (row listings and whole-repo patches, grouped help, fzf selection, `local_path` normalization) and 024 covers `rerere` conflict-resolution memory. ### Coverage Matrix @@ -112,12 +112,13 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 | `remove` | 014 | 014, 023 | | `prune` | 015 | 009 | | `cd`/`wt` (print path) | 017 | 017, 023 | -| `init` | -- | 009 | +| `init` | 024 | 009, 024 | | `sparse checkout` | 012 | 012 | | `sbx/update workflow` | -- | 018 | | whole-repo patch (`.git` exclusion) | 019‡ | 019 | | grouped `--help` | n/a | 020 | | `local_path` normalization | 023‡ | 023 | +| `rerere` (config + resolution reuse) | 024 | 024 | `*` = partial/basic assertions only. `--` = not tested. `‡` = variant guarded by Fish availability (skips gracefully when `fish` is absent). @@ -125,7 +126,7 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 - **Just update behavior**: requires Fish to be installed; run `test/004_update.sh` in an environment with Fish. - **Just `list` output**: no dedicated test; `test/019` exercises patch row listings when Fish is available. -- **Just variants**: `test/019`, `test/021`, `test/023`, and `test/017` include Fish-guarded variants that skip when `fish` is absent; `test/020` is Go-only (grouped help is a Go CLI rendering concern). CI should keep Fish present to avoid silent gaps. +- **Just variants**: `test/019`, `test/021`, `test/023`, `test/024`, and `test/017` include Fish-guarded variants that skip when `fish` is absent; `test/020` is Go-only (grouped help is a Go CLI rendering concern). CI should keep Fish present to avoid silent gaps. ## Agent Workflow @@ -196,6 +197,7 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 - **Clipboard helper (parked)**: `copyToClipboard` (Go) / `_clip` (Just) remain implemented but are intentionally unused — `cd`/`wt` print a path and `shell-init` provides the real `cd`, which made the clipboard workflow obsolete. Reuse rather than reimplement if a clipboard feature returns. - **Patch rows**: bare `git cross`, and path-miss cases in `compare`/`diff`/`remove`/`cd`/`wt`, print `local_pathworktree` rows to stdout; hints go to stderr and the command exits 1 where nothing was resolved. - **`list --raw` schema**: remotes first (`REMOTE_NAMEREMOTE_URL`), then patches (`REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`); no banners, no borders, deterministic remote order. +- **`rerere` (conflict resolution memory)**: `ensureRerere` (Go) / an inline `git config rerere.enabled true` (Just) runs in `init` (announces, and says "already enabled" on repeat), `patch` (silent), and `update` (announces only when it newly enables it, which self-heals older repos). The key is written to the shared repository config, so the main repo and every cross worktree see it; each worktree records resolutions in its own `rr-cache`. `rerere.autoUpdate` is intentionally left unset (opt-in, users enable it themselves). Just's `init` resolves the repo root explicitly so it never writes global config. - **Crossfile format**: Lines like `cross use ` or `cross patch :: `. `update` interprets only these declarative commands; arbitrary shell commands are not executed. - **.crossignore**: Located in the root of each local_path, uses gitignore-style patterns to exclude files from status and diff comparisons. Implemented by filtering directory trees using git add and git clean to remove ignored files before comparison. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a3347750..fbc9f877f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`git cross cmp`** - Short alias for `compare`; the canonical name is unchanged. - **Grouped `--help` output** - Commands are listed under `Patch Lifecycle:`, `Repository:`, and `Inspect & Navigate:` instead of one flat list. `use` and `patch` appear first (in that order), and `cd`/`wt` stay adjacent. `git cross -h` still prints full help, and the help text documents `cross.diffTool` setup. - **`shell-init`** - `git cross shell-init [bash|zsh|fish]` prints `crosscd`/`crosswt` functions that perform a real `cd` in the caller's shell (a child process cannot change it). The clipboard fallback is no longer wired into `cd`/`wt`; its helper is kept isolated (unused) for possible reuse. -- **`list --raw` and `list --no-header`** - `--raw` emits tab-separated rows with no table borders and no `==>` banners; `--no-header` omits the header line. Raw column order is documented and fixed: `REMOTE_NAMEREMOTE_URL` first, then `REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`. Remote rows are sorted deterministically, remotes with distinct fetch/push URLs produce one row per URL without `(fetch)`/`(push)` suffixes, and the empty-state message goes to stderr in raw mode. On a terminal the columns are space-padded for readability; piped output stays TAB-separated. +- **Conflict resolution memory (`rerere`)** - `init`, `patch`, and `update` enable Git's `rerere.enabled` in the shared repository config, so a conflict resolved once in a cross worktree is replayed automatically when the same conflict reappears on a later update. `init` announces the setting (and reports when it is already on), `patch` is silent, and `update` re-enables it for repositories set up before this change. `rerere.autoUpdate` is intentionally left unset (opt-in). Documented in README as "Conflict Resolution Memory (`rerere`)" and covered by `test/024_rerere.sh`, including a real resolve-then-replay scenario. + `--no-header` omits the header line. Raw column order is documented and fixed: `REMOTE_NAMEREMOTE_URL` first, then `REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`. Remote rows are sorted deterministically, remotes with distinct fetch/push URLs produce one row per URL without `(fetch)`/`(push)` suffixes, and the empty-state message goes to stderr in raw mode. On a terminal the columns are space-padded for readability; piped output stays TAB-separated. - **Patch row listings** - Bare `git cross` prints one `local_pathworktree` row per patch to stdout instead of Cobra help (rows are aligned on a TTY, TAB-separated when piped; no hint line). Unresolved `compare` / `diff` / `remove` / `cd` / `wt` invocations print the same rows and exit 1 instead of dumping a usage block. - **Tests 019, 020, 021, 023** - Cover whole-repo patches plus row listings, grouped help and ordering, fzf-driven `diff`/`compare`, editor selection, and `local_path` normalization. diff --git a/Justfile.cross b/Justfile.cross index 91a9efa75..2e49e77ff 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -279,6 +279,17 @@ _select_patch *prompt="patch": [no-cd] init: #!/usr/bin/env fish + # Remember conflict resolutions for later updates (repo config, not global). + set -l repo (git rev-parse --show-toplevel 2>/dev/null) + if test -n "$repo" + set -l rerere (git -C $repo config --get rerere.enabled 2>/dev/null | string trim) + if test "$rerere" = true + just cross _log info "rerere already enabled: conflict resolutions are reused." + else + git -C $repo config rerere.enabled true + and just cross _log info "Enabled rerere: conflict resolutions are remembered for later updates." + end + end if test -f "{{CROSSFILE}}" just cross _log info "Crossfile already exists." else @@ -483,7 +494,8 @@ patch remote_spec local_path="": check-deps set l_path (path normalize "$l_path") pushd "{{REPO_DIR}}" - + git config rerere.enabled true 2>/dev/null + # validate remote if not git remote show $remote |grep -vq "^$remote\$" just cross _log error "Error: Remote $remote not found. Run: just cross use $remote URL" @@ -645,6 +657,11 @@ update path="": check-deps exit 1 end pushd "{{REPO_DIR}}" >/dev/null + set -l rerere (git config --get rerere.enabled 2>/dev/null | string trim) + if test "$rerere" != true + git config rerere.enabled true + and just cross _log info "Enabled rerere: conflict resolutions are remembered for later updates." + end set updates 0 while read -l line set fields (string split -n ' ' -- (string trim -- "$line")) diff --git a/README.md b/README.md index d0452b697..7a7da778c 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,43 @@ In practice: - upstream history stays in the hidden worktree - `Crossfile` records the `use` and `patch` declarations; `git cross update` reads them to refresh patches +## Conflict Resolution Memory (`rerere`) + +`git-cross` enables Git's **rerere** ("reuse recorded resolution") so that +conflict resolutions survive across updates. This is what solves resolving the +same update conflict twice: + +- `git cross init` turns `rerere.enabled` on and tells you so. +- `git cross patch` enables it silently. +- `git cross update` re-enables it when it was turned off, so repositories + created before this feature self-heal. + +When upstream changes collide with your local copy, resolve the conflict once — +typically inside the sparse worktree, after entering it with +`git cross wt ` and merging or rebasing there. Git records that +resolution, and every later update that hits the same conflict replays the +recorded resolution instead of asking you again: the next merge or rebase over +the same upstream hunk is resolved without a second manual edit. + +Notes: + +- The setting lives in the repository's shared Git config, so it applies to the + main repository and to every `git-cross` worktree. +- Recorded resolutions are local to each worktree (its `rr-cache`), so every + patch keeps its own conflict memory. +- `rerere.autoUpdate` is deliberately **not** enabled. Replayed resolutions are + applied to the working tree but not staged, so a merge still stops and waits + for `git add` + `git commit` (without `rerere.autoUpdate`). To let Git stage + what it resolved for you, opt in: + + ```bash + git config rerere.autoUpdate true + ``` + +- `git cross update` itself uses `--ff-only` and therefore never conflicts; the + recorded resolutions matter in the manual workflow where you merge or rebase + upstream inside the worktree. + ## Local Custom Files On Top Of Upstream One common pattern is to keep local-only files next to upstream-managed files. @@ -260,6 +297,8 @@ If the local copy still matches the previously installed upstream content, `upda Review the differences and merge manually. Whole-repository patches (`remote:.` and `remote:/`) take part in this check correctly: the worktree's `.git` pointer file is not counted as a local edit, so a clean whole-repo patch is updated instead of warned about. +Resolutions you record manually are remembered for later updates — see [Conflict Resolution Memory (`rerere`)](#conflict-resolution-memory-rerere). + ### `compare` ```bash diff --git a/src-go/main.go b/src-go/main.go index 22fe82933..85c45463e 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -994,6 +994,23 @@ function crosswt --description 'cd into a git-cross worktree' end ` +// ensureRerere enables reuse-recorded-resolution in the shared repo config, so +// conflict resolutions recorded in any cross worktree (merge/rebase) are +// replayed automatically when the same conflict reappears on later updates. +// Returns true when the setting was newly enabled. +func ensureRerere(root string) bool { + if out, err := exec.Command("git", "-C", root, "config", "--get", "rerere.enabled").Output(); err == nil { + if strings.TrimSpace(string(out)) == "true" { + return false + } + } + if err := exec.Command("git", "-C", root, "config", "rerere.enabled", "true").Run(); err != nil { + logWarn(fmt.Sprintf("could not enable rerere: %v", err)) + return false + } + return true +} + // copyToClipboard copies text using the first available platform tool // (pbcopy/xclip/xsel). // @@ -1166,6 +1183,9 @@ Environment variables (used only when cross.diffTool is unset): return fmt.Errorf("remote %s not found", spec.Remote) } + // Remember conflict resolutions so later updates can reuse them. + ensureRerere(repo.Path()) + canonical := canonicalSpec(spec) logInfo(fmt.Sprintf("Patching %s to %s", canonical, localPath)) @@ -1430,6 +1450,9 @@ Environment variables (used only when cross.diffTool is unset): if err != nil { return err } + if ensureRerere(root) { + logInfo("Enabled rerere: conflict resolutions are remembered for later updates.") + } cwd, err := os.Getwd() if err != nil { return err @@ -2248,6 +2271,13 @@ if fzf is unavailable it prints the available patches.`, Short: "Initialize a new project with Crossfile", GroupID: "repo", RunE: func(cmd *cobra.Command, args []string) error { + if root, rerr := getRepoRoot(); rerr == nil { + if ensureRerere(root) { + logInfo("Enabled rerere: conflict resolutions are remembered for later updates.") + } else { + logInfo("rerere already enabled: conflict resolutions are reused.") + } + } path := "Crossfile" if _, err := os.Stat(path); err == nil { logInfo("Crossfile already exists.") diff --git a/test/024_rerere.sh b/test/024_rerere.sh new file mode 100755 index 000000000..0380f6f29 --- /dev/null +++ b/test/024_rerere.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash +# Test 024: rerere (reuse recorded resolution) — conflict resolution memory. +# +# Covers: +# - `init` enables rerere.enabled and reports it (and says "already enabled" +# on a second run) +# - `patch` enables it silently in the shared repo config, so the setting is +# also visible from inside every cross worktree +# - `update` re-enables it (self-heal for repositories patched before the +# feature existed) +# - functionally: a conflict resolved once inside a cross worktree is +# replayed automatically when the same conflict reappears +source "$(dirname "$0")/common.sh" + +PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +GO_BIN="$(ensure_go_bin "$PROJECT_ROOT")" + +if [ -z "$GO_BIN" ]; then + echo "SKIP: Go CLI unavailable; skipping rerere Go assertions" +fi + +has_fish() { command -v fish >/dev/null 2>&1; } + +# Enable rerere straight from a repo/worktree and print the effective value. +rerere_value() { + git -C "$1" config --get rerere.enabled 2>/dev/null || true +} + +# ---------------------------------------------------------------- Go section +if [ -n "$GO_BIN" ]; then + cd "$PROJECT_ROOT" + setup_sandbox + cd "$SANDBOX" + + log_header "024: init enables rerere (Go)" + init_out=$("$GO_BIN" init 2>&1) + assert_contains "$init_out" "Enabled rerere" "init should announce rerere" + test "$(rerere_value "$SANDBOX")" = true || fail "rerere.enabled not set after init" + + log_header "024: second init reports rerere already enabled (Go)" + init_out=$("$GO_BIN" init 2>&1) + assert_contains "$init_out" "rerere already enabled" "second init should say already enabled" + + log_header "024: patch enables rerere for worktrees (Go)" + upstream_path=$(create_upstream "rerere-go") + pushd "$upstream_path" >/dev/null + mkdir -p docs + printf 'line one\n' > docs/a.md + git add docs/a.md + git commit -m "Add docs" -q + popd >/dev/null + upstream_url="file://$upstream_path" + + git config --unset rerere.enabled || true + "$GO_BIN" use up "$upstream_url" >/dev/null 2>&1 || fail "git-cross use failed" + "$GO_BIN" patch up:main:docs docs >/dev/null 2>&1 || fail "git-cross patch failed" + + test "$(rerere_value "$SANDBOX")" = true || fail "patch did not enable rerere in the shared config" + wt=$(find .cross/worktrees -maxdepth 1 -mindepth 1 -type d | head -1) + [ -n "$wt" ] || fail "no worktree under .cross/worktrees" + test "$(rerere_value "$wt")" = true || fail "rerere.enabled not visible from inside the worktree" + + log_header "024: update self-heals rerere (Go)" + git config --unset rerere.enabled || true + update_out=$("$GO_BIN" update 2>&1) + assert_contains "$update_out" "Enabled rerere" "update should re-enable a missing rerere setting" + test "$(rerere_value "$SANDBOX")" = true || fail "update did not restore rerere.enabled" + + # ------------------------------------------------- functional rerere --- + log_header "024: a recorded conflict resolution is reused (Go worktree)" + wt_abs="$SANDBOX/$wt" + + # Local divergence inside the worktree (this is the "local overlay" edit). + printf 'line one\nlocal change\n' > "$wt_abs/docs/a.md" + git -C "$wt_abs" add docs/a.md + git -C "$wt_abs" commit -m "local edit" -q || fail "could not commit local edit in worktree" + + # Same hunk diverges upstream. + pushd "$upstream_path" >/dev/null + printf 'line one\nupstream change\n' > docs/a.md + git add docs/a.md + git commit -m "upstream edit" -q + popd >/dev/null + + git -C "$wt_abs" fetch up main -q || fail "could not fetch upstream into worktree" + pre_merge=$(git -C "$wt_abs" rev-parse HEAD) + + set +e + git -C "$wt_abs" merge up/main >/dev/null 2>&1 + merge_rc=$? + set -e + [ "$merge_rc" -ne 0 ] || fail "expected a conflict on the first merge" + + rr_cache=$(git -C "$wt_abs" rev-parse --git-path rr-cache) + [ -d "$rr_cache" ] || fail "rerere cache not created at $rr_cache" + + # Resolve manually: this is the step rerere must remember. + printf 'line one\nresolved line\n' > "$wt_abs/docs/a.md" + git -C "$wt_abs" add docs/a.md + git -C "$wt_abs" commit -m "merge upstream with resolution" -q || fail "could not commit resolution" + preimage_present=$(find "$rr_cache" -type f -name preimage 2>/dev/null | head -1) + [ -n "$preimage_present" ] || fail "rerere preimage was not recorded" + + # Replay the identical conflict; rerere must reapply the resolution. + git -C "$wt_abs" reset --hard "$pre_merge" -q || fail "could not reset to pre-merge state" + set +e + replay_out=$(git -C "$wt_abs" merge up/main 2>&1) + replay_rc=$? + set -e + # Without rerere.autoUpdate the merge still stops and the index stays + # unmerged; what matters is the working-tree file being pre-resolved. + [ "$replay_rc" -ne 0 ] || fail "merge should still require a commit without rerere.autoUpdate" + assert_contains "$replay_out" "Resolved 'docs/a.md' using previous resolution" \ + "rerere should reuse the recorded resolution on replay" + + if grep -q '^<<<<<<<' "$wt_abs/docs/a.md"; then + fail "rerere did not reuse the recorded resolution (conflict markers remain)" + fi + grep -qx 'resolved line' "$wt_abs/docs/a.md" || fail "rerere did not reapply the recorded resolution" + + git -C "$wt_abs" add docs/a.md + git -C "$wt_abs" commit -m "second merge with reused resolution" -q || fail "could not commit replayed merge" +fi + +# -------------------------------------------------------------- Just section +if has_fish; then + cd "$PROJECT_ROOT" + setup_sandbox + cd "$SANDBOX" + + log_header "024: init enables rerere (Just/Fish)" + init_out=$(just cross init 2>&1) + assert_contains "$init_out" "Enabled rerere" "Just init should announce rerere" + test "$(rerere_value "$SANDBOX")" = true || fail "Just init did not set rerere.enabled" + + init_out=$(just cross init 2>&1) + assert_contains "$init_out" "rerere already enabled" "second Just init should say already enabled" + + log_header "024: patch enables rerere (Just/Fish)" + upstream_path=$(create_upstream "rerere-just") + pushd "$upstream_path" >/dev/null + mkdir -p docs + printf 'just line\n' > docs/a.md + git add docs/a.md + git commit -m "Add docs" -q + popd >/dev/null + + git config --unset rerere.enabled || true + just cross use up "file://$upstream_path" >/dev/null 2>&1 || fail "just cross use failed" + just cross patch up:main:docs docs >/dev/null 2>&1 || fail "just cross patch failed" + + test "$(rerere_value "$SANDBOX")" = true || fail "Just patch did not enable rerere" + wt=$(find .cross/worktrees -maxdepth 1 -mindepth 1 -type d | head -1) + [ -n "$wt" ] || fail "no worktree after Just patch" + test "$(rerere_value "$wt")" = true || fail "Just patch: rerere not visible from the worktree" + + log_header "024: update self-heals rerere (Just/Fish)" + git config --unset rerere.enabled || true + update_out=$(just cross update 2>&1) + assert_contains "$update_out" "Enabled rerere" "Just update should re-enable rerere" + test "$(rerere_value "$SANDBOX")" = true || fail "Just update did not restore rerere.enabled" +else + echo "SKIP: fish unavailable; skipping Just/Fish rerere assertions" +fi + +log_success "024: rerere configuration and resolution reuse verified" From 405858047354c104cfbfddfd9f881ea3b3244cae Mon Sep 17 00:00:00 2001 From: docs-impl Date: Thu, 12 Nov 2026 08:09:03 +0100 Subject: [PATCH 17/22] feat(cli): restore completion command and ship cd wrappers with it - completion [fish|bash|zsh|powershell] prints the completion script plus the crosscd/crosswt functions; shell defaults to the basename of $SHELL and an unknown/undetectable shell exits 1 instead of guessing (fish listed first) - fish uses 'git cross completion fish | source' (fish 4 executes $(...) and joins eval args, so the POSIX eval form does not work there) - shell-init is now hidden but still functional (wrappers only), keeping the visible surface to one command; init prints the shell-appropriate one-liner from both Go and Just - cd/wt help no longer advertises the raw 'cd "$(git cross cd)"' form: they only print a path, and without a wrapper the cd happens in a throwaway sub-shell. Headlines now point at crosscd/crosswt and custom aliases - README: shell integration section (fish first), copy-paste generic wrappers and alias examples (gccd/gcwt); docs/AGENTS/CHANGELOG updated - tests 017/020: completion scripts + wrappers, $SHELL detection, hidden shell-init, init hints, help grouping --- AGENTS.md | 10 +++- CHANGELOG.md | 8 +-- Justfile.cross | 71 ++++++++++++++++++---- README.md | 78 +++++++++++++++++++----- src-go/main.go | 130 ++++++++++++++++++++++++++++++++-------- test/017_cd_wt_fix.sh | 88 +++++++++++++++++++++++---- test/020_help_groups.sh | 14 +++-- 7 files changed, 322 insertions(+), 77 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 914f8a3b7..64267d86d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,9 +46,10 @@ test/001-023_*.sh # Individual test files (see coverage matrix below) | `remove` | `` | Delete patch, clean Crossfile and metadata | | `prune` | `[remote]` | Remove remote and all its patches, prune stale worktrees | | `init` | | Create empty Crossfile | -| `cd` | `[path]` | Print absolute local_path to stdout; shell integration via `shell-init` (`crosscd`) | +| `cd` | `[path]` | Print absolute local_path to stdout; real `cd` via `completion` wrappers (`crosscd`) | | `wt` | `[path]` | Print absolute worktree path to stdout; `crosswt` wrapper | -| `shell-init` | `[bash\|zsh\|fish]` | Print shell functions that `cd` into patches/worktrees (child processes cannot) | +| `completion` | `[fish\|bash\|zsh\|powershell]` | Print completions + `crosscd`/`crosswt` wrappers; shell defaults from `$SHELL` | +| `shell-init` | `[fish\|bash\|zsh]` | Hidden (kept for compatibility): prints the wrappers without completions | Bare `git cross` prints one `local_pathworktree` row per patch to stdout (no hint line; TTY output is space-padded, piped output stays TAB-separated); `-h` prints the grouped help. Help grouping is Go-only CLI presentation — Just/Fish exposes the same behavior through recipes, not through a grouped help renderer. @@ -112,6 +113,8 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 | `remove` | 014 | 014, 023 | | `prune` | 015 | 009 | | `cd`/`wt` (print path) | 017 | 017, 023 | +| `completion` (scripts + wrappers, `$SHELL`) | 017‡ | 017, 020 | +| `shell-init` (hidden) | 017 | 017 | | `init` | 024 | 009, 024 | | `sparse checkout` | 012 | 012 | | `sbx/update workflow` | -- | 018 | @@ -194,7 +197,8 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 - **Sparse checkout**: `git sparse-checkout init --no-cone` + `git sparse-checkout set /` + `git read-tree -mu HEAD`. The trailing `/` on the pattern is required for reliable directory matching in `--no-cone` mode on newer Git versions (2.43+). `read-tree -mu HEAD` explicitly materializes the worktree (bare `git checkout` can no-op after `--no-checkout`). - **Rsync**: `rsync -av --delete --exclude .git` for worktree-to-local sync. `--delete` removes files locally that were deleted upstream. - **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `nvim` when installed, else `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). When unset, env vars extend the default: `DIRDIFF_EXCLUDES` appends names to the exclusion list (`.git` stays permanent) and `DIRDIFF_IGNORE` adds `g:DirDiffIgnore` with a very-nomagic (`\V`) alternation of the comma-separated keywords. Empty/unset vars omit the corresponding argument. Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). -- **Clipboard helper (parked)**: `copyToClipboard` (Go) / `_clip` (Just) remain implemented but are intentionally unused — `cd`/`wt` print a path and `shell-init` provides the real `cd`, which made the clipboard workflow obsolete. Reuse rather than reimplement if a clipboard feature returns. +- **Clipboard helper (parked)**: `copyToClipboard` (Go) / `_clip` (Just) remain implemented but are intentionally unused — `cd`/`wt` print a path and `completion` provides the real `cd`, which made the clipboard workflow obsolete. Reuse rather than reimplement if a clipboard feature returns. +- **Shell integration**: `cd`/`wt` print only the path to stdout (hints/rows go to stderr), so a parent-shell wrapper can capture it. `git cross completion [fish|bash|zsh|powershell]` emits the Cobra completion script plus the `crosscd`/`crosswt` functions (fish first in usage/errors); the shell defaults to the basename of `$SHELL`, and an unknown/undetectable shell exits 1 instead of guessing. fish must use `git cross completion fish | source` because fish joins multi-line command substitution with spaces (`eval (...)` breaks); `init` prints the shell-appropriate one-liner. `shell-init` is hidden but kept for compatibility and emits only the wrappers. powershell gets completions only. Just emits the wrappers only (Cobra scripts are a Go CLI concern). - **Patch rows**: bare `git cross`, and path-miss cases in `compare`/`diff`/`remove`/`cd`/`wt`, print `local_pathworktree` rows to stdout; hints go to stderr and the command exits 1 where nothing was resolved. - **`list --raw` schema**: remotes first (`REMOTE_NAMEREMOTE_URL`), then patches (`REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`); no banners, no borders, deterministic remote order. - **`rerere` (conflict resolution memory)**: `ensureRerere` (Go) / an inline `git config rerere.enabled true` (Just) runs in `init` (announces, and says "already enabled" on repeat), `patch` (silent), and `update` (announces only when it newly enables it, which self-heals older repos). The key is written to the shared repository config, so the main repo and every cross worktree see it; each worktree records resolutions in its own `rr-cache`. `rerere.autoUpdate` is intentionally left unset (opt-in, users enable it themselves). Just's `init` resolves the repo root explicitly so it never writes global config. diff --git a/CHANGELOG.md b/CHANGELOG.md index fbc9f877f..aff70cae8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,14 +14,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 #### Added - **`git cross cmp`** - Short alias for `compare`; the canonical name is unchanged. - **Grouped `--help` output** - Commands are listed under `Patch Lifecycle:`, `Repository:`, and `Inspect & Navigate:` instead of one flat list. `use` and `patch` appear first (in that order), and `cd`/`wt` stay adjacent. `git cross -h` still prints full help, and the help text documents `cross.diffTool` setup. -- **`shell-init`** - `git cross shell-init [bash|zsh|fish]` prints `crosscd`/`crosswt` functions that perform a real `cd` in the caller's shell (a child process cannot change it). The clipboard fallback is no longer wired into `cd`/`wt`; its helper is kept isolated (unused) for possible reuse. +- **`completion`** - `git cross completion [fish|bash|zsh|powershell]` prints the shell completion script **plus** `crosscd`/`crosswt` functions that perform a real `cd` in the caller's shell (a child process cannot change it). The shell defaults to the basename of `$SHELL`; an unknown or undetectable shell exits 1 instead of guessing. fish uses `git cross completion fish | source` (multi-line `eval (...)` breaks in fish); `init` prints the matching one-liner for the caller's shell. `shell-init` is now hidden (kept for compatibility, wrappers only), and the clipboard fallback is no longer wired into `cd`/`wt`; its helper is kept isolated (unused) for possible reuse. - **Conflict resolution memory (`rerere`)** - `init`, `patch`, and `update` enable Git's `rerere.enabled` in the shared repository config, so a conflict resolved once in a cross worktree is replayed automatically when the same conflict reappears on a later update. `init` announces the setting (and reports when it is already on), `patch` is silent, and `update` re-enables it for repositories set up before this change. `rerere.autoUpdate` is intentionally left unset (opt-in). Documented in README as "Conflict Resolution Memory (`rerere`)" and covered by `test/024_rerere.sh`, including a real resolve-then-replay scenario. - `--no-header` omits the header line. Raw column order is documented and fixed: `REMOTE_NAMEREMOTE_URL` first, then `REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`. Remote rows are sorted deterministically, remotes with distinct fetch/push URLs produce one row per URL without `(fetch)`/`(push)` suffixes, and the empty-state message goes to stderr in raw mode. On a terminal the columns are space-padded for readability; piped output stays TAB-separated. +- **`list --raw` and `list --no-header`** - `--raw` emits tab-separated rows with no table borders and no `==>` banners; `--no-header` omits the header line. Raw column order is documented and fixed: `REMOTE_NAMEREMOTE_URL` first, then `REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`. Remote rows are sorted deterministically, remotes with distinct fetch/push URLs produce one row per URL without `(fetch)`/`(push)` suffixes, and the empty-state message goes to stderr in raw mode. On a terminal the columns are space-padded for readability; piped output stays TAB-separated. - **Patch row listings** - Bare `git cross` prints one `local_pathworktree` row per patch to stdout instead of Cobra help (rows are aligned on a TTY, TAB-separated when piped; no hint line). Unresolved `compare` / `diff` / `remove` / `cd` / `wt` invocations print the same rows and exit 1 instead of dumping a usage block. -- **Tests 019, 020, 021, 023** - Cover whole-repo patches plus row listings, grouped help and ordering, fzf-driven `diff`/`compare`, editor selection, and `local_path` normalization. +- **Tests 019, 020, 021, 023, 024** - Cover whole-repo patches plus row listings, grouped help and ordering, fzf-driven `diff`/`compare`, editor selection, `local_path` normalization, and `rerere` conflict-resolution memory. #### Changed -- **BREAKING: `cd` / `wt` print a path instead of opening a shell** - Both commands print the absolute destination path to stdout (hints to stderr). They no longer start a subshell and no longer copy anything to the clipboard. Use `cd "$(git cross cd)"`, `cd "$(git cross wt)"`, or the `crosscd`/`crosswt` functions from `git cross shell-init`. Without an argument they auto-detect the current patch, then use `fzf`; if `fzf` is missing, rows plus a hint are printed and the command exits 1. +- **BREAKING: `cd` / `wt` print a path instead of opening a shell** - Both commands print the absolute destination path to stdout (hints to stderr). They no longer start a subshell and no longer copy anything to the clipboard. Use `cd "$(git cross cd)"`, `cd "$(git cross wt)"`, or the `crosscd`/`crosswt` functions from `git cross completion`. Without an argument they auto-detect the current patch, then use `fzf`; if `fzf` is missing, rows plus a hint are printed and the command exits 1. - **Behavior change: interactive `diff` selection** - With no path, `diff` resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. - **`compare` selection ladder** - With no path, `compare` uses the same CWD auto-detect → `fzf` → rows + hint + exit 1 ladder and always operates on exactly one patch. - **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). `DIRDIFF_EXCLUDES` appends extra file/dir names to the exclusion list (`.git` is always ignored) and `DIRDIFF_IGNORE` ignores comma-separated keywords in diff content (converted to a very-nomagic `\V` regexp), e.g. `DIRDIFF_IGNORE=github.com,gitlab.com`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. diff --git a/Justfile.cross b/Justfile.cross index 2e49e77ff..2f96460e8 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -295,6 +295,11 @@ init: else echo "# git-cross configuration" > "{{CROSSFILE}}" just cross _log success "Crossfile initialized." + if test (basename $SHELL 2>/dev/null) = fish + just cross _log info "Shell integration (cd wrappers + completions): git cross completion fish | source" + else + just cross _log info 'Shell integration (cd wrappers + completions): eval \"\$(git cross completion)\"' + end end # AICONTEXT: "use" register remote git repository and update Crossfile with "use" command. Do not change implementation! @@ -971,7 +976,7 @@ list raw="" no_header="": check-deps worktree path="": just cross wt "{{path}}" -# Print a patch worktree to cd into (use: cd (just cross wt [path])) +# Print a patch worktree path (use the crosswt shell wrapper for a real cd) [no-cd] wt path="": #!/usr/bin/env fish @@ -1025,37 +1030,81 @@ _clip: exit 1 fi -# Print shell functions that cd into patches/worktrees (a child process cannot). -# Usage: eval "$(git cross shell-init)" (bash/zsh) or eval (git cross shell-init fish) +# Print the cd wrappers (a child process cannot change the parent's directory). +# These are also appended by `git cross completion`. Hidden equivalent of +# `git cross shell-init`; `completion` is the documented entry point. +# Usage (fish): git cross completion fish | source +# (posix): eval "$(git cross completion)" [no-cd] shell-init shell="": #!/usr/bin/env fish set -l sh "{{shell}}" if test -z "$sh" - set sh (basename $SHELL 2>/dev/null; or echo bash) + set sh (basename $SHELL 2>/dev/null) + end + if test -z "$sh" + echo "cannot detect shell from \$SHELL; specify one: fish, bash, zsh" >&2 + exit 1 + end + if test "$sh" = fish + printf '%s\n' '# git-cross cd wrappers (part of: git cross completion fish | source)' \ + 'function crosscd --description \'cd into a git-cross patch\'' \ + ' set -l p (git cross cd $argv)' \ + ' or return' \ + ' test -n "$p"; and cd $p' \ + 'end' \ + 'function crosswt --description \'cd into a git-cross worktree\'' \ + ' set -l p (git cross wt $argv)' \ + ' or return' \ + ' test -n "$p"; and cd $p' \ + 'end' + else if contains -- bash zsh "$sh" + printf '%s\n' '# git-cross cd wrappers (part of: eval "$(git cross completion)")' \ + 'crosscd() { local p; p="$(git cross cd "$@")" || return; [ -n "$p" ] && cd "$p"; }' \ + 'crosswt() { local p; p="$(git cross wt "$@")" || return; [ -n "$p" ] && cd "$p"; }' + else + echo "unsupported shell: $sh (supported: fish, bash, zsh)" >&2 + exit 1 + end + +# Print shell completions plus the cd wrappers to evaluate in your shell profile. +# Cobra-style completion scripts are a Go CLI concern; the Just reference emits +# the cd wrappers (the part shared by both implementations). +# Usage (fish): git cross completion fish | source +# (posix): eval "$(git cross completion)" +[no-cd] +completion shell="": + #!/usr/bin/env fish + set -l sh "{{shell}}" + if test -z "$sh" + set sh (basename $SHELL 2>/dev/null) + end + if test -z "$sh" + echo "cannot detect shell from \$SHELL; specify one: fish, bash, zsh" >&2 + exit 1 end if test "$sh" = fish - printf '%s\n' '# git-cross shell integration' \ - 'function crosscd' \ + printf '%s\n' '# git-cross cd wrappers (part of: git cross completion fish | source)' \ + 'function crosscd --description \'cd into a git-cross patch\'' \ ' set -l p (git cross cd $argv)' \ ' or return' \ ' test -n "$p"; and cd $p' \ 'end' \ - 'function crosswt' \ + 'function crosswt --description \'cd into a git-cross worktree\'' \ ' set -l p (git cross wt $argv)' \ ' or return' \ ' test -n "$p"; and cd $p' \ 'end' - else if contains -- bash zsh "$sh"; or test -z "$sh" - printf '%s\n' '# git-cross shell integration' \ + else if contains -- bash zsh "$sh" + printf '%s\n' '# git-cross cd wrappers (part of: eval "$(git cross completion)")' \ 'crosscd() { local p; p="$(git cross cd "$@")" || return; [ -n "$p" ] && cd "$p"; }' \ 'crosswt() { local p; p="$(git cross wt "$@")" || return; [ -n "$p" ] && cd "$p"; }' else - echo "unsupported shell: $sh (use bash, zsh or fish)" >&2 + echo "unsupported shell: $sh (supported: fish, bash, zsh)" >&2 exit 1 end -# Print a patch local_path to cd into (use: cd (just cross cd [path])) +# Print a patch local_path (use the crosscd shell wrapper for a real cd) [no-cd] cd path="": #!/usr/bin/env fish diff --git a/README.md b/README.md index 7a7da778c..5a94e0bc1 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ Your own repository stores the final combined result, including local overlay fi When you want to contribute upstream-managed changes back: ```bash -cd "$(git cross wt vendor/app)" # or use the crosswt wrapper +cd "$(git cross wt vendor/app)" # or: crosswt vendor/app (see shell integration) git cross compare vendor/app ``` @@ -236,6 +236,7 @@ Patch Lifecycle: Repository: init Create an empty Crossfile + completion Print shell completions and cd wrappers to evaluate list Show all configured patches and remotes status Show patch status update Update patches from Crossfile declarations @@ -428,30 +429,79 @@ Print the absolute destination path for one patch: `cd` targets the local copy (`local_path`), `wt` targets the hidden sparse worktree. The path is the only thing written to stdout; hints and errors go to stderr. -These commands do not start a subshell. For a real directory change, add the -shell integration once: +Run directly, the command only prints a path: a child process cannot change +your shell, so `cd "$(git cross cd)"` would change a throwaway sub-shell only. + +### Shell integration (real `cd`) + +A child process cannot change the working directory of the shell that started +it — no CLI can. Tools that appear to do it (yazi, zoxide, autojump) all use +the same pattern: the program prints the destination, and a small **shell +function** captures it and runs `cd` in your shell. `git cross completion` +prints that function pair together with the completion script: + +```fish +# fish (~/.config/fish/config.fish, or a file in ~/.config/fish/functions/) +git cross completion fish | source + +# shell auto-detected from $SHELL: +git cross completion | source +``` ```bash # bash / zsh (~/.bashrc, ~/.zshrc) -eval "$(git cross shell-init)" +eval "$(git cross completion)" -# fish (~/.config/fish/config.fish) -eval (git cross shell-init fish) +# or force a shell: +eval "$(git cross completion bash)" ``` -That defines `crosscd` and `crosswt`, which `cd` into the path printed by the -tool (or keep using the direct form): +That defines two functions, which take the same optional path (and `fzf` +selection) as the commands themselves: ```bash -crosscd vendor/app # cd into the local copy (fzf if omitted) +crosscd vendor/app # cd into the local copy crosswt vendor/app # cd into the sparse worktree -cd "$(git cross cd vendor/app)" +crosswt # no path: fzf selection ``` -A child process cannot change the working directory of the shell that started -it, so the tool cannot `cd` for you. The wrapper does the `cd` in your shell -using the path the tool prints. Keeping stdout path-only also makes the output -composable in scripts (`dir=$(git cross cd vendor/app)`). +`git cross init` prints the matching one-liner for your `$SHELL` when it +creates a `Crossfile`. + +Prefer to install the wrappers by hand? Copy the function into your shell's +function directory (fish) or profile (bash/zsh); they are plain wrappers, not +special builtins: + +```fish +# ~/.config/fish/functions/crosswt.fish +function crosswt --description 'cd into a git-cross worktree' + set -l p (git cross wt $argv) + or return + test -n "$p"; and cd $p +end +``` + +```bash +# ~/.bashrc / ~/.zshrc +crosswt() { local p; p="$(git cross wt "$@")" || return; [ -n "$p" ] && cd "$p"; } +crosscd() { local p; p="$(git cross cd "$@")" || return; [ -n "$p" ] && cd "$p"; } +``` + +Short aliases work as ordinary aliases; for example `gccd`/`gcwt` behave like +`cd` into the local copy/worktree: + +```fish +alias gcwt crosswt +alias gccd crosscd +``` + +```bash +alias gcwt=crosswt +alias gccd=crosscd +``` + +Keeping stdout path-only is deliberate: it makes the output composable in +scripts (`dir=$(git cross cd vendor/app)`) and safe to capture in a function. With an explicit path the patch is resolved directly. Without one, `fzf` is used to select a patch. If `fzf` is not installed, the command prints the diff --git a/src-go/main.go b/src-go/main.go index 85c45463e..79746f2b5 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -974,14 +974,12 @@ func runNoIndexDiff(upstreamPath, localPath string) { _ = c.Run() } -const posixShellInit = `# git-cross shell integration (add to ~/.bashrc or ~/.zshrc): -# eval "$(git cross shell-init)" +const posixShellInit = `# git-cross cd wrappers (part of: eval "$(git cross completion bash|zsh)") crosscd() { local p; p="$(git cross cd "$@")" || return; [ -n "$p" ] && cd "$p"; } crosswt() { local p; p="$(git cross wt "$@")" || return; [ -n "$p" ] && cd "$p"; } ` -const fishShellInit = `# git-cross shell integration (add to ~/.config/fish/config.fish): -# eval (git cross shell-init fish) +const fishShellInit = `# git-cross cd wrappers (part of: git cross completion fish | source) function crosscd --description 'cd into a git-cross patch' set -l p (git cross cd $argv) or return @@ -994,6 +992,39 @@ function crosswt --description 'cd into a git-cross worktree' end ` +// shellIntegrationHint returns the one-liner that fits the caller's $SHELL. +// fish joins multi-line command substitution with spaces, so it needs `| source`. +func shellIntegrationHint() string { + if strings.ToLower(filepath.Base(strings.TrimSpace(os.Getenv("SHELL")))) == "fish" { + return "Shell integration (cd wrappers + completions): git cross completion fish | source" + } + return `Shell integration (cd wrappers + completions): eval "$(git cross completion)"` +} + +// supportedShells is the canonical order for help and error hints. +const supportedShells = "fish, bash, zsh, powershell" + +// resolveShell picks the shell from an explicit argument, falling back to the +// basename of $SHELL. An unknown or undetectable shell is an error: guessing a +// default would emit a script the caller cannot evaluate. +func resolveShell(args []string) (string, error) { + var shell string + if len(args) > 0 { + shell = strings.ToLower(strings.TrimSpace(args[0])) + } else if env := strings.TrimSpace(os.Getenv("SHELL")); env != "" { + shell = strings.ToLower(filepath.Base(env)) + } + if shell == "" { + return "", fmt.Errorf("cannot detect shell from $SHELL; specify one: %s", supportedShells) + } + switch shell { + case "fish", "bash", "zsh", "powershell", "pwsh": + return shell, nil + default: + return "", fmt.Errorf("unsupported shell %q (supported: %s)", shell, supportedShells) + } +} + // ensureRerere enables reuse-recorded-resolution in the shared repo config, so // conflict resolutions recorded in any cross worktree (merge/rebase) are // replayed automatically when the same conflict reappears on later updates. @@ -1014,7 +1045,7 @@ func ensureRerere(root string) bool { // copyToClipboard copies text using the first available platform tool // (pbcopy/xclip/xsel). // -// Currently unused: cd/wt print a path and shell-init provides the real cd, so +// Currently unused: cd/wt print a path and completion provides the real cd, so // the clipboard workflow is obsolete. Kept isolated for possible reuse. func copyToClipboard(text string) error { candidates := [][]string{ @@ -1779,43 +1810,89 @@ Environment variables (used only when cross.diffTool is unset): } cdCmd := makeDirCmd("cd [path]", - "Print a patch local_path to cd into (use: cd \"$(git cross cd)\")", - "Print the absolute path of a patch local_path to stdout (use: cd \"$(git cross cd)\").\n\nWith path: prints the specified local_path.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.\n\nFor real directory changes add shell integration:\n eval \"$(git cross shell-init)\" # then: crosscd [path]", + "Print a patch local_path (use the crosscd wrapper for a real cd)", + "Print the absolute path of a patch local_path to stdout.\n\nRunning this directly only prints a path: a child process cannot change the caller's shell, so without a wrapper the cd happens in a throwaway sub-shell. For a real directory change use the 'crosscd' wrapper:\n eval \"$(git cross completion)\" # bash/zsh; then: crosscd [path]\n git cross completion fish | source # fish\nAdd a custom alias if you like (e.g. alias gccd=crosscd).\n\nWith path: prints the specified local_path.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.", "local_path") wtCmd := makeDirCmd("wt [path]", - "Print a patch worktree to cd into (use: cd \"$(git cross wt)\")", - "Print the absolute path of a patch worktree to stdout (use: cd \"$(git cross wt)\").\n\nWith path: prints the specified worktree.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.\n\nFor real directory changes add shell integration:\n eval \"$(git cross shell-init)\" # then: crosswt [path]", + "Print a patch worktree path (use the crosswt wrapper for a real cd)", + "Print the absolute path of a patch worktree to stdout.\n\nRunning this directly only prints a path: a child process cannot change the caller's shell, so without a wrapper the cd happens in a throwaway sub-shell. For a real directory change use the 'crosswt' wrapper:\n eval \"$(git cross completion)\" # bash/zsh; then: crosswt [path]\n git cross completion fish | source # fish\nAdd a custom alias if you like (e.g. alias gcwt=crosswt).\n\nWith path: prints the specified worktree.\nWithout path: auto-detects the current patch from the working directory, otherwise uses fzf to select one.", "worktree") + // Hidden: kept for backwards compatibility. `completion` is the visible + // entry point (it also emits the completion scripts). shellInitCmd := &cobra.Command{ - Use: "shell-init [bash|zsh|fish]", + Use: "shell-init [fish|bash|zsh]", Short: "Print shell functions that cd into patches and worktrees", GroupID: "repo", + Hidden: true, Args: cobra.MaximumNArgs(1), - Long: `Print shell functions to evaluate in your shell profile. They wrap -'git cross cd' / 'git cross wt' with cd, because a child process cannot change -the caller's working directory by itself. - - bash/zsh: eval "$(git cross shell-init)" - fish: eval (git cross shell-init fish) + Long: `Print just the shell functions (no completion scripts). Kept for +backwards compatibility; prefer 'git cross completion'. -After that, 'crosscd' and 'crosswt' change directory directly, with the same -optional path argument and fzf selection as the git-cross commands.`, + fish: git cross completion fish | source + bash/zsh: eval "$(git cross completion)"`, RunE: func(cmd *cobra.Command, args []string) error { - shell := "" - if len(args) > 0 { - shell = strings.ToLower(strings.TrimSpace(args[0])) - } else { - shell = filepath.Base(os.Getenv("SHELL")) + shell, err := resolveShell(args) + if err != nil { + return err } switch shell { case "fish": fmt.Print(fishShellInit) - case "bash", "zsh", "": + case "bash", "zsh": fmt.Print(posixShellInit) default: - return fmt.Errorf("unsupported shell %q (use bash, zsh or fish)", shell) + return fmt.Errorf("unsupported shell %q for shell functions (supported: fish, bash, zsh)", shell) + } + return nil + }, + } + + completionCmd := &cobra.Command{ + Use: "completion [fish|bash|zsh|powershell]", + Short: "Print shell completions and cd wrappers to evaluate", + GroupID: "repo", + Args: cobra.MaximumNArgs(1), + Long: `Print a completion script for the requested shell, followed by the +'crosscd' / 'crosswt' functions that perform a real cd. A child process cannot +change the caller's working directory by itself, so these wrappers run the +command and cd into the path it prints. + + fish: git cross completion fish | source # or just: git cross completion | source + bash/zsh: eval "$(git cross completion)" # or: git cross completion bash + +The shell defaults to the basename of $SHELL when not given. powershell gets +completions only (no cd wrappers). After that, 'crosscd [path]' cd's into the +local copy and 'crosswt [path]' into the sparse worktree, with the same +optional path argument and fzf selection as the git-cross commands.`, + RunE: func(cmd *cobra.Command, args []string) error { + shell, err := resolveShell(args) + if err != nil { + return err + } + switch shell { + case "fish": + if err := rootCmd.GenFishCompletion(os.Stdout, true); err != nil { + return err + } + fmt.Print("\n", fishShellInit) + case "bash": + if err := rootCmd.GenBashCompletionV2(os.Stdout, true); err != nil { + return err + } + fmt.Print("\n", posixShellInit) + case "zsh": + if err := rootCmd.GenZshCompletion(os.Stdout); err != nil { + return err + } + fmt.Print("\n", posixShellInit) + case "powershell", "pwsh": + if err := rootCmd.GenPowerShellCompletionWithDesc(os.Stdout); err != nil { + return err + } + default: + return fmt.Errorf("unsupported shell %q (supported: %s)", shell, supportedShells) } return nil }, @@ -2288,6 +2365,7 @@ if fzf is unavailable it prints the available patches.`, return err } logSuccess("Crossfile initialized.") + logInfo(shellIntegrationHint()) return nil }, } @@ -2453,7 +2531,7 @@ if fzf is unavailable it prints the available patches.`, // Retain superseded implementations in source as internal reference, but do // not expose them as supported commands. _, _, _, _ = syncCmd, replayCmd, pushCmd, execCmd - rootCmd.AddCommand(useCmd, patchCmd, removeCmd, pruneCmd, initCmd, listCmd, statusCmd, updateCmd, compareCmd, shellInitCmd, cdCmd, wtCmd, diffCmd) + rootCmd.AddCommand(useCmd, patchCmd, removeCmd, pruneCmd, initCmd, completionCmd, listCmd, statusCmd, updateCmd, compareCmd, shellInitCmd, cdCmd, wtCmd, diffCmd) if err := rootCmd.Execute(); err != nil { os.Exit(1) } diff --git a/test/017_cd_wt_fix.sh b/test/017_cd_wt_fix.sh index 067a3a11f..0f9d22509 100755 --- a/test/017_cd_wt_fix.sh +++ b/test/017_cd_wt_fix.sh @@ -99,17 +99,59 @@ if [ -n "$GO_BIN" ]; then assert_one_abs_path "Go wt (CWD auto-detect)" "$out" "$wt_abs" popd >/dev/null - log_header "017: Go shell-init prints cd wrappers" + log_header "017: Go completion prints scripts plus cd wrappers" + comp_bash=$("$GO_BIN" completion bash 2>&1) || fail "completion bash should exit 0" + assert_contains "$comp_bash" "crosscd()" "bash completion should define crosscd" + assert_contains "$comp_bash" "crosswt()" "bash completion should define crosswt" + assert_contains "$comp_bash" "git-cross" "bash completion should include the completion script" + printf '%s\n' "$comp_bash" | bash -n || fail "bash completion output must be valid bash" + + comp_fish=$("$GO_BIN" completion fish 2>&1) || fail "completion fish should exit 0" + assert_contains "$comp_fish" "function crosscd" "fish completion should define crosscd" + assert_contains "$comp_fish" "function crosswt" "fish completion should define crosswt" + assert_contains "$comp_fish" "complete -c git-cross" "fish completion should include the completion script" + + # $SHELL is used when the shell argument is omitted. + comp_detected=$(SHELL=/usr/bin/fish "$GO_BIN" completion 2>&1) || fail "completion should detect fish from \$SHELL" + assert_contains "$comp_detected" "function crosscd" "detected fish should emit fish wrappers" + comp_detected=$(SHELL=/bin/zsh "$GO_BIN" completion 2>&1) || fail "completion should detect zsh from \$SHELL" + assert_contains "$comp_detected" "crosscd()" "detected zsh should emit posix wrappers" + + # Undetectable/unsupported shells fail instead of guessing; fish is listed first. + comp_unset=$(env -u SHELL "$GO_BIN" completion 2>&1); comp_rc=$? + [ "$comp_rc" -eq 1 ] || fail "completion without SHELL should exit 1, got $comp_rc" + assert_contains "$comp_unset" "fish, bash, zsh, powershell" "error hint should list fish first" + comp_bad=$("$GO_BIN" completion tcsh 2>&1); comp_rc=$? + [ "$comp_rc" -eq 1 ] || fail "unsupported shell should exit 1, got $comp_rc" + assert_contains "$comp_bad" "fish, bash, zsh, powershell" "unsupported-shell hint should list fish first" + + # powershell gets completions only (no cd wrappers). + comp_pwsh=$("$GO_BIN" completion powershell 2>&1) || fail "completion powershell should exit 0" + assert_not_contains "$comp_pwsh" "crosscd" "powershell output should not define wrappers" + + # shell-init is hidden but still functional. init_bash=$("$GO_BIN" shell-init bash 2>&1) || fail "shell-init bash should exit 0" - assert_contains "$init_bash" "crosscd()" "bash init should define crosscd" - assert_contains "$init_bash" "crosswt()" "bash init should define crosswt" - printf '%s\n' "$init_bash" | bash -n || fail "bash init must be valid bash" + assert_contains "$init_bash" "crosscd()" "bash shell-init should define crosscd" + printf '%s\n' "$init_bash" | bash -n || fail "bash shell-init must be valid bash" init_fish=$("$GO_BIN" shell-init fish 2>&1) || fail "shell-init fish should exit 0" - assert_contains "$init_fish" "function crosscd" "fish init should define crosscd" - init_rc=0 - "$GO_BIN" shell-init powershell >/dev/null 2>&1 || init_rc=$? - [ "$init_rc" -eq 1 ] || fail "unsupported shell should exit 1, got $init_rc" - log_success "Go shell-init verified" + assert_contains "$init_fish" "function crosscd" "fish shell-init should define crosscd" + help_out=$("$GO_BIN" --help 2>&1) + assert_not_contains "$help_out" "shell-init" "shell-init must be hidden from help" + assert_contains "$help_out" "completion" "completion must be visible in help" + + # init advertises the integration, tailored to $SHELL. + probe="$SANDBOX/init-probe" + mkdir -p "$probe" + git -C "$probe" init -q + fish_hint=$(cd "$probe" && rm -f Crossfile && SHELL=/usr/bin/fish "$GO_BIN" init 2>&1) \ + || fail "Go init (fish hint) should exit 0" + assert_contains "$fish_hint" "git cross completion fish | source" \ + "fish init hint should use | source" + bash_hint=$(cd "$probe" && rm -f Crossfile && SHELL=/bin/bash "$GO_BIN" init 2>&1) \ + || fail "Go init (posix hint) should exit 0" + assert_contains "$bash_hint" 'eval "$(git cross completion)"' \ + "posix init hint should use eval" + log_success "Go completion + hidden shell-init verified" log_success "Go CWD auto-detect verified" log_header "017: Go fzf selection prints the selected path" @@ -168,11 +210,31 @@ if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command - assert_contains "$wt_out" "fzf is not installed" "Just wt fallback should say fzf is missing" log_success "Just fzf-missing fallback verified" - log_header "017: Just shell-init prints cd wrappers" + log_header "017: Just completion prints cd wrappers" + comp_bash=$(just cross completion bash 2>&1) || fail "Just completion bash should exit 0" + assert_contains "$comp_bash" "crosscd()" "Just bash completion should define crosscd" + printf '%s\n' "$comp_bash" | bash -n || fail "Just bash completion must be valid bash" + comp_fish=$(just cross completion fish 2>&1) || fail "Just completion fish should exit 0" + assert_contains "$comp_fish" "function crosscd" "Just fish completion should define crosscd" + comp_detected=$(SHELL=/usr/bin/fish just cross completion 2>&1) || fail "Just completion should detect fish from \$SHELL" + assert_contains "$comp_detected" "function crosscd" "Just detection should emit fish wrappers" + comp_unset=$(SHELL= just cross completion 2>&1); comp_rc=$? + [ "$comp_rc" -eq 1 ] || fail "Just completion without SHELL should exit 1, got $comp_rc" + assert_contains "$comp_unset" "fish, bash, zsh" "Just error hint should list fish first" init_bash=$(just cross shell-init bash 2>&1) || fail "Just shell-init bash should exit 0" - assert_contains "$init_bash" "crosscd()" "Just bash init should define crosscd" - printf '%s\n' "$init_bash" | bash -n || fail "Just bash init must be valid bash" - log_success "Just shell-init verified" + assert_contains "$init_bash" "crosscd()" "Just shell-init should still work" + probe="$SANDBOX/just-init-probe" + mkdir -p "$probe" + git -C "$probe" init -q + fish_hint=$(cd "$probe" && rm -f Crossfile && SHELL=/usr/bin/fish just cross init 2>&1) \ + || fail "Just init (fish hint) should exit 0" + assert_contains "$fish_hint" "git cross completion fish | source" \ + "Just fish init hint should use | source" + bash_hint=$(cd "$probe" && rm -f Crossfile && SHELL=/bin/bash just cross init 2>&1) \ + || fail "Just init (posix hint) should exit 0" + assert_contains "$bash_hint" 'eval "$(git cross completion)"' \ + "Just posix init hint should use eval" + log_success "Just completion + shell-init verified" else echo "SKIP: fish and/or jq/just unavailable; skipping Just cd/wt assertions" fi diff --git a/test/020_help_groups.sh b/test/020_help_groups.sh index 1ae2b45d0..a5aea660f 100755 --- a/test/020_help_groups.sh +++ b/test/020_help_groups.sh @@ -39,7 +39,7 @@ repo_section=$(section_body "Repository:") inspect_section=$(section_body "Inspect & Navigate:") patches_section=$(section_body "Patch Lifecycle:") -for cmd in compare init list status update shell-init; do +for cmd in compare init completion list status update; do printf '%s\n' "$repo_section" | grep -Eq "^ ${cmd}([[:space:]]|$)" \ || fail "'$cmd' should be listed under 'Repository:'" done @@ -60,15 +60,14 @@ adjacent=$(printf '%s\n' "$inspect_order" | awk 'prev=="cd" && $0=="wt" {found=1 log_success "cd/wt adjacency verified" log_header "020: every visible command appears exactly once" -for cmd in compare init list status update shell-init cd wt diff use patch remove prune; do +for cmd in compare init completion list status update cd wt diff use patch remove prune; do count=$(printf '%s\n' "$help_output" | grep -cE "^ ${cmd}([[:space:]]|$)") [ "$count" -eq 1 ] || fail "command '$cmd' should appear exactly once in help (found $count)" done -# Cobra still renders the auto-generated 'help' (and, if enabled, 'completion') -# command under "Additional Commands:". Tolerate those built-ins, but no -# documented command may end up ungrouped there. +# Cobra still renders the auto-generated 'help' command under "Additional +# Commands:". Tolerate it, but no documented command may end up ungrouped there. additional_section=$(section_body "Additional Commands:") -for cmd in compare init list status update shell-init cd wt diff use patch remove prune; do +for cmd in compare init completion list status update cd wt diff use patch remove prune; do if printf '%s\n' "$additional_section" | grep -Eq "^ ${cmd}([[:space:]]|$)"; then fail "'$cmd' must not fall into 'Additional Commands:' (missing GroupID)" fi @@ -76,6 +75,9 @@ done if printf '%s\n' "$help_output" | grep -Eq '^ cmp([[:space:]]|$)'; then fail "the 'cmp' alias must not get its own help row" fi +if printf '%s\n' "$help_output" | grep -Eq '^ shell-init([[:space:]]|$)'; then + fail "hidden 'shell-init' must not appear in help" +fi log_success "all visible commands listed once" log_header "020: -h still prints the grouped help" From dc865c6f8b590f00d3104594bc9f40acafada350 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Thu, 12 Nov 2026 08:14:03 +0100 Subject: [PATCH 18/22] docs(help): show the explicit cross.diffTool command once The root help printed the same nvim/vim config line twice. Keep a single nvim example (the default) and note that replacing nvim with vim pins vim. test/020 now enforces exactly one config line and no 'Strictly vim' repeat. --- src-go/main.go | 4 +--- test/020_help_groups.sh | 5 +++++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src-go/main.go b/src-go/main.go index 79746f2b5..ab5d45dba 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -1087,9 +1087,7 @@ To pin it explicitly (recommended): git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" -Strictly vim: - - git config --global cross.diffTool "vim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" +Replace nvim with vim to pin vim instead. Environment variables (used only when cross.diffTool is unset): DIRDIFF_EXCLUDES extra comma-separated file/dir names to hide; .git is always ignored diff --git a/test/020_help_groups.sh b/test/020_help_groups.sh index a5aea660f..c2ea3b792 100755 --- a/test/020_help_groups.sh +++ b/test/020_help_groups.sh @@ -92,6 +92,11 @@ assert_contains "$help_output" "cross.diffTool" "help should mention cross.diffT assert_contains "$help_output" "--unset cross.diffTool" "help should show how to reset to the built-in default" assert_contains "$help_output" "let g:DirDiffExcludes = '.git'" "help should show the correct DirDiff exclusion syntax" assert_contains "$help_output" "DirDiff {left} {right}" "help should show the placeholder form" +pin_lines=$(printf '%s\n' "$help_output" | grep -c 'cross.diffTool "') +[ "$pin_lines" -eq 1 ] || fail "help should show the explicit diffTool config line exactly once (found $pin_lines)" +if printf '%s\n' "$help_output" | grep -q "Strictly vim"; then + fail "help must not repeat the same config line for vim" +fi if printf '%s\n' "$help_output" | grep -q "DirDiffIgnore="; then fail "help must not suggest the invalid 'DirDiffIgnore=' command" fi From 43e58c21d5ffb4d4f6cd002e2fcacec85e258e76 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Thu, 12 Nov 2026 08:15:00 +0100 Subject: [PATCH 19/22] docs(help): show how to load completions and cd wrappers Root help now ends with the one-time profile lines: git cross completion fish | source (fish) eval "$(git cross completion)" (bash/zsh) test/020 asserts both forms are present. --- src-go/main.go | 6 +++++- test/020_help_groups.sh | 7 +++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src-go/main.go b/src-go/main.go index ab5d45dba..c18dc7029 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -1091,7 +1091,11 @@ Replace nvim with vim to pin vim instead. Environment variables (used only when cross.diffTool is unset): DIRDIFF_EXCLUDES extra comma-separated file/dir names to hide; .git is always ignored - DIRDIFF_IGNORE comma-separated keywords ignored in diff content (e.g. github.com,gitlab.com)`, + DIRDIFF_IGNORE comma-separated keywords ignored in diff content (e.g. github.com,gitlab.com) + +Shell completions + cd wrappers (crosscd / crosswt) - evaluate once in your profile: + git cross completion fish | source # fish + eval "$(git cross completion)" # bash / zsh`, RunE: func(cmd *cobra.Command, args []string) error { return printPatchRows("") }, diff --git a/test/020_help_groups.sh b/test/020_help_groups.sh index c2ea3b792..fb70068bc 100755 --- a/test/020_help_groups.sh +++ b/test/020_help_groups.sh @@ -102,4 +102,11 @@ if printf '%s\n' "$help_output" | grep -q "DirDiffIgnore="; then fi log_success "diffTool setup guidance present" +log_header "020: help shows how to eval shell completions" +assert_contains "$help_output" "git cross completion fish | source" \ + "help should show the fish completion one-liner" +assert_contains "$help_output" 'eval "$(git cross completion)"' \ + "help should show the bash/zsh completion one-liner" +log_success "completion guidance present" + echo "Test 020 passed!" From 42a0b6e4e528bf8bf63d9cca43af1952b533de06 Mon Sep 17 00:00:00 2001 From: docs-impl Date: Thu, 12 Nov 2026 08:24:59 +0100 Subject: [PATCH 20/22] fix(cli): align the fzf patch picker and put local_path first Rows were raw TAB-separated fields, so a long remote (e.g. mxc-library) ran into the next column and the header never lined up. - rows are '' with width = max(local_path)+2 clamped to 16..48 - second column is remote:remote_path, with '(branch)' when branch != main - header uses the same padding; fzf gets --delimiter \t --with-nth=1 so the key is hidden and the selection comes from the last TAB field - Go (selectPatchInteractive) and Just (_select_patch) emit the identical layout for cd/wt/diff/compare; _list_patches machine rows are unchanged - tests 017/021: new selection contract, shim stdin/args capture, alignment assertions with a long remote, branch-suffix case, padded header check - README picker example, AGENTS implementation note, CHANGELOG in 0.4.0 --- AGENTS.md | 1 + CHANGELOG.md | 1 + Justfile.cross | 23 +++++++- README.md | 18 +++++- src-go/main.go | 46 +++++++++++++-- test/017_cd_wt_fix.sh | 108 ++++++++++++++++++++++++++++++++++- test/021_fzf_diff_compare.sh | 6 +- 7 files changed, 188 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 64267d86d..ec5c2fd05 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -199,6 +199,7 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 - **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `nvim` when installed, else `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). When unset, env vars extend the default: `DIRDIFF_EXCLUDES` appends names to the exclusion list (`.git` stays permanent) and `DIRDIFF_IGNORE` adds `g:DirDiffIgnore` with a very-nomagic (`\V`) alternation of the comma-separated keywords. Empty/unset vars omit the corresponding argument. Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). - **Clipboard helper (parked)**: `copyToClipboard` (Go) / `_clip` (Just) remain implemented but are intentionally unused — `cd`/`wt` print a path and `completion` provides the real `cd`, which made the clipboard workflow obsolete. Reuse rather than reimplement if a clipboard feature returns. - **Shell integration**: `cd`/`wt` print only the path to stdout (hints/rows go to stderr), so a parent-shell wrapper can capture it. `git cross completion [fish|bash|zsh|powershell]` emits the Cobra completion script plus the `crosscd`/`crosswt` functions (fish first in usage/errors); the shell defaults to the basename of `$SHELL`, and an unknown/undetectable shell exits 1 instead of guessing. fish must use `git cross completion fish | source` because fish joins multi-line command substitution with spaces (`eval (...)` breaks); `init` prints the shell-appropriate one-liner. `shell-init` is hidden but kept for compatibility and emits only the wrappers. powershell gets completions only. Just emits the wrappers only (Cobra scripts are a Go CLI concern). +- **Interactive picker**: `selectPatchInteractive` (Go) and `_select_patch` (Just) share `cd`/`wt`/`diff`/`compare`. Rows are `` with `width = max(len(local_path)) + 2`, clamped to 16–48; the second column is `remote:remote_path` plus `(branch)` when the branch is not `main`; the header legend is padded with the same width. fzf runs with `--delimiter \t --with-nth=1` so the trailing key is hidden and the selection is parsed from the last TAB field. Just computes the padding in jq. The machine `_list_patches` rows (`local_pathworktree`) are unchanged. - **Patch rows**: bare `git cross`, and path-miss cases in `compare`/`diff`/`remove`/`cd`/`wt`, print `local_pathworktree` rows to stdout; hints go to stderr and the command exits 1 where nothing was resolved. - **`list --raw` schema**: remotes first (`REMOTE_NAMEREMOTE_URL`), then patches (`REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`); no banners, no borders, deterministic remote order. - **`rerere` (conflict resolution memory)**: `ensureRerere` (Go) / an inline `git config rerere.enabled true` (Just) runs in `init` (announces, and says "already enabled" on repeat), `patch` (silent), and `update` (announces only when it newly enables it, which self-heals older repos). The key is written to the shared repository config, so the main repo and every cross worktree see it; each worktree records resolutions in its own `rr-cache`. `rerere.autoUpdate` is intentionally left unset (opt-in, users enable it themselves). Just's `init` resolves the repo root explicitly so it never writes global config. diff --git a/CHANGELOG.md b/CHANGELOG.md index aff70cae8..43ebb2a08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **README workflow guidance** - The current `.crossignore` behavior is documented as a review-oriented workflow for local overlay files layered on top of upstream-managed content. #### Fixed +- **Aligned interactive patch picker** - The `fzf` selector used by `cd`/`wt`/`diff`/`compare` printed raw TAB-separated fields, so a long remote name (e.g. `mxc-library`) ran into the next column and the header never lined up. Rows are now space-padded with `LOCAL_PATH` first, then `REMOTE:REMOTE_PATH` (branch shown in parentheses only when it is not `main`), the header uses the same padding, and the hidden `local_path` key is the last TAB field. Go and Just emit the identical layout. - **DirDiff invocation** - `compare` passed the two paths as vim file arguments, where DirDiff never saw them. Paths now go inside the vim `+` command string. - **`.git` false positives in comparisons** - The worktree's `.git` pointer file (never present in the local copy) counted as a local deletion. Boolean checks now use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff runs `git diff --no-index` against a temporary `.git`-free mirror (pathspec excludes are rejected by older git versions). As a result, whole-repo patches (`remote:.`) no longer always report `Modified` in `status` or always warn in `update`; clean whole-repo patches now update. - **`local_path` normalization** - A local path such as `./mxc2` was stored verbatim and broke CWD auto-detection (`compare`, `diff`, `cd`/`wt`, `remove`). Paths are normalized on ingestion, normalized defensively during matching, and self-healed on metadata load; the `Crossfile` keeps the user's original spelling. diff --git a/Justfile.cross b/Justfile.cross index 2f96460e8..ee0edd4c1 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -263,6 +263,9 @@ _list_patches *hint="": # Interactive patch selection; prints the selected local_path. # Cancels silently (empty output). If fzf is missing: rows+hint to stderr, exit 1. +# Rows are space-padded (LOCAL_PATH first, then REMOTE:REMOTE_PATH, plus the +# branch when it is not "main"); TAB is only the hidden field separator, and the +# local_path is repeated as the last field so the selection is parseable. [no-cd] _select_patch *prompt="patch": #!/usr/bin/env fish @@ -270,10 +273,26 @@ _select_patch *prompt="patch": just cross _list_patches "fzf is not installed, cd into a patched directory first or pass a path. Patches, columns local_path TAB worktree" >&2 exit 1 end - set -l row (just cross _list_patches | fzf --height 40% --select-1 --exit-0 --prompt "Select {{prompt}}> ") + set -l meta "{{REPO_DIR}}/.cross/metadata.json" + set -l width (jq -r '[.patches[].local_path | length] | max // 0' "$meta") + set width (math "$width + 2") + test $width -lt 16; and set width 16 + test $width -gt 48; and set width 48 + set -l header LOCAL_PATH(string repeat -n (math $width - 10) ' ')REMOTE:REMOTE_PATH + set -l rows (jq -r --argjson w $width ' + .patches[] + | .local_path as $lp + | ($w - ($lp | length)) as $pad + | ($lp + (" " * ([0, $pad] | max))) + + .remote + ":" + .remote_path + + (if (.branch // "") != "" and .branch != "main" then " (" + .branch + ")" else "" end) + + "\t" + $lp + ' "$meta") + set -l row (printf '%s\n' $rows | fzf --delimiter \t --with-nth=1 --header "$header" --height 40% --select-1 --exit-0 --prompt "Select {{prompt}}> ") test -z "$row"; and exit 0 + # Selection is "": take the last field. set -l cols (string split \t -- $row) - echo "$cols[1]" + echo "$cols[-1]" # Initialize a new project with Crossfile [no-cd] diff --git a/README.md b/README.md index 5a94e0bc1..bb1c6c680 100644 --- a/README.md +++ b/README.md @@ -504,8 +504,22 @@ Keeping stdout path-only is deliberate: it makes the output composable in scripts (`dir=$(git cross cd vendor/app)`) and safe to capture in a function. With an explicit path the patch is resolved directly. Without one, `fzf` is -used to select a patch. If `fzf` is not installed, the command prints the -available patch rows plus a hint to `cd` manually, and exits 1. +used to select a patch. The picker puts `LOCAL_PATH` first, then +`REMOTE:REMOTE_PATH`, and appends the branch in parentheses only when it is not +`main`; columns are padded so long remote names cannot run into the next field: + +```text + vendor/mxcsrc mxc-library:src + vendor/mxcpkg mxc-library:pkg (feature) + vendor/docs-src docs:src + 3/3 +────────────────────────────────────────────── +LOCAL_PATH REMOTE:REMOTE_PATH +Select patch> +``` + +If `fzf` is not installed, the command prints the available patch rows plus a +hint to `cd` manually, and exits 1. ## Directory Diff Tool (`cross.diffTool`) diff --git a/src-go/main.go b/src-go/main.go index c18dc7029..dfa44e239 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -885,6 +885,39 @@ func resolvePathToRepoRelative(inputPath string) (string, error) { return strings.Trim(relPath, "/"), nil } +// pickerWidth is the padded width of the LOCAL_PATH column: the widest +// local_path plus a two-space gap, clamped so one long path cannot push the +// second column off screen. +func pickerWidth(meta *Metadata) int { + width := 0 + for _, p := range meta.Patches { + if n := len([]rune(p.LocalPath)); n > width { + width = n + } + } + width += 2 + if width < 16 { + width = 16 + } + if width > 48 { + width = 48 + } + return width +} + +// pickerLabel is the second picker column: remote:remote_path, with the branch +// in parentheses when it is not the usual default. +func pickerLabel(p Patch) string { + label := p.Remote + ":" + p.RemotePath + if p.Branch != "" && p.Branch != "main" { + label += " (" + p.Branch + ")" + } + return label +} + +// selectPatchInteractive lets the user pick a patch with fzf. Rows are +// space-padded for alignment (TAB is used only as the hidden field separator), +// with the local_path repeated as the last field so the selection is parseable. func selectPatchInteractive(meta *Metadata) (*Patch, error) { if _, err := exec.LookPath("fzf"); err != nil { return nil, err @@ -893,19 +926,19 @@ func selectPatchInteractive(meta *Metadata) (*Patch, error) { return nil, nil } + width := pickerWidth(meta) var b strings.Builder for _, p := range meta.Patches { - b.WriteString(fmt.Sprintf("%s\t%s\t%s\n", p.Remote, p.RemotePath, p.LocalPath)) + b.WriteString(fmt.Sprintf("%-*s%s\t%s\n", width, p.LocalPath, pickerLabel(p), p.LocalPath)) } cmd := exec.Command("fzf", - "--with-nth=1,2,3", - "--delimiter", - "\t", + "--delimiter", "\t", + "--with-nth=1", "--prompt", "Select patch> ", "--header", - "REMOTE\tREMOTE_PATH\tLOCAL_PATH", + fmt.Sprintf("%-*s%s", width, "LOCAL_PATH", "REMOTE:REMOTE_PATH"), "--height", "40%", "--border", @@ -919,9 +952,10 @@ func selectPatchInteractive(meta *Metadata) (*Patch, error) { return nil, nil // user cancelled (ESC / empty) } + // The local_path is always the last TAB-delimited field. parts := strings.Split(selection, "\t") var localPath string - if len(parts) >= 3 { + if len(parts) > 1 { localPath = strings.TrimSpace(parts[len(parts)-1]) } else { fields := strings.Fields(selection) diff --git a/test/017_cd_wt_fix.sh b/test/017_cd_wt_fix.sh index 0f9d22509..6ac3c5804 100755 --- a/test/017_cd_wt_fix.sh +++ b/test/017_cd_wt_fix.sh @@ -159,7 +159,14 @@ if [ -n "$GO_BIN" ]; then mkdir -p "$shim_dir" cat > "$shim_dir/fzf" <<'EOF' #!/usr/bin/env bash -cat >/dev/null +if [ -n "${FZF_STDIN_FILE:-}" ]; then + cat > "$FZF_STDIN_FILE" +else + cat >/dev/null +fi +if [ -n "${FZF_ARGS_FILE:-}" ]; then + printf '%s\n' "$@" > "$FZF_ARGS_FILE" +fi if [ -n "${FZF_SELECT:-}" ]; then printf '%b\n' "$FZF_SELECT" exit 0 @@ -167,7 +174,8 @@ fi exit 130 EOF chmod +x "$shim_dir/fzf" - selection="demo\tsrc\tvendor/src" + # New picker contract: "" + selection="vendor/src demo:src\tvendor/src" out=$(FZF_SELECT="$selection" PATH="$shim_dir:$PATH" "$GO_BIN" cd 2>/dev/null) \ || fail "Go cd with an fzf selection failed" @@ -176,6 +184,59 @@ EOF out=$(FZF_SELECT="$selection" PATH="$shim_dir:$PATH" "$GO_BIN" wt 2>/dev/null) \ || fail "Go wt with an fzf selection failed" assert_one_abs_path "Go wt (fzf)" "$out" "$wt_abs" + + log_header "017: Go fzf picker aligns local_path and labels" + long_upstream=$(create_upstream "mxc-library") + # Idempotent: the Go and Just sections share the sandbox. + if ! git -C "$long_upstream" rev-parse --verify feature >/dev/null 2>&1; then + pushd "$long_upstream" >/dev/null + mkdir -p src pkg + echo "src" > src/s.txt + echo "pkg" > pkg/p.txt + git add -A + git commit -m "Add src and pkg" -q + git checkout -q -b feature + echo "more" >> pkg/p.txt + git commit -qam "Feature change" -q + popd >/dev/null + fi + "$GO_BIN" use mxc-library "file://$long_upstream" >/dev/null + "$GO_BIN" patch mxc-library:main:src vendor/mxcsrc >/dev/null 2>&1 + "$GO_BIN" patch mxc-library:feature:pkg vendor/mxcpkg >/dev/null 2>&1 + + maxlen=$(jq -r '[.patches[].local_path | length] | max' .cross/metadata.json) + width=$((maxlen + 2)) + [ "$width" -lt 16 ] && width=16 + [ "$width" -gt 48 ] && width=48 + stdin_file="$SANDBOX/fzf-stdin.txt" + args_file="$SANDBOX/fzf-args.txt" + FZF_STDIN_FILE="$stdin_file" FZF_ARGS_FILE="$args_file" \ + PATH="$shim_dir:$PATH" "$GO_BIN" cd >/dev/null 2>&1 || true + [ -s "$stdin_file" ] || fail "fzf picker should receive candidate rows" + + # Every row is ""; the label must + # start at column width+1, past the two-space gap. + awk -F'\t' -v w="$width" ' + NF != 2 { bad = 1 } + substr($1, w + 1, 1) == " " { bad = 1 } + substr($1, w, 1) != " " { bad = 1 } + $2 == "" { bad = 1 } + END { exit bad ? 1 : 0 } + ' "$stdin_file" || fail "picker rows must align at column $((width + 1)) and end with a TAB key" + + awk -F'\t' '$1 ~ /mxc-library:pkg \(feature\)$/ { found = 1 } END { exit found ? 0 : 1 }' "$stdin_file" \ + || fail "picker should show the branch for non-main patches" + if awk -F'\t' '$1 ~ /mxc-library:src/ && $1 ~ /\(main\)/ { f = 1 } END { exit f ? 0 : 1 }' "$stdin_file"; then + fail "picker should not show '(main)' for the default branch" + fi + + header_val=$(awk '/^--header$/{ getline; print; exit }' "$args_file") + expected_header="LOCAL_PATH$(printf '%*s' "$((width - 10))" '')REMOTE:REMOTE_PATH" + [ "$header_val" = "$expected_header" ] \ + || fail "padded header mismatch: got '$header_val', want '$expected_header'" + assert_contains "$(cat "$args_file")" "--with-nth=1" "picker should hide the key field" + assert_contains "$(cat "$args_file")" "--delimiter" "picker should use TAB as the field delimiter" + log_success "Go fzf picker alignment verified" log_success "Go fzf selection verified" else echo "SKIP: Go CLI unavailable; skipping Go cd/wt assertions" @@ -210,6 +271,49 @@ if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command - assert_contains "$wt_out" "fzf is not installed" "Just wt fallback should say fzf is missing" log_success "Just fzf-missing fallback verified" + log_header "017: Just fzf picker aligns local_path and labels" + long_upstream=$(create_upstream "mxc-library") + # Idempotent: the Go and Just sections share the sandbox. + if ! git -C "$long_upstream" rev-parse --verify feature >/dev/null 2>&1; then + pushd "$long_upstream" >/dev/null + mkdir -p src pkg + echo "src" > src/s.txt + echo "pkg" > pkg/p.txt + git add -A + git commit -m "Add src and pkg" -q + git checkout -q -b feature + echo "more" >> pkg/p.txt + git commit -qam "Feature change" -q + popd >/dev/null + fi + just cross use mxc-library "file://$long_upstream" >/dev/null + just cross patch mxc-library:main:src vendor/mxcsrc >/dev/null 2>&1 + just cross patch mxc-library:feature:pkg vendor/mxcpkg >/dev/null 2>&1 + + maxlen=$(jq -r '[.patches[].local_path | length] | max' .cross/metadata.json) + width=$((maxlen + 2)) + [ "$width" -lt 16 ] && width=16 + [ "$width" -gt 48 ] && width=48 + stdin_file="$SANDBOX/just-fzf-stdin.txt" + args_file="$SANDBOX/just-fzf-args.txt" + FZF_STDIN_FILE="$stdin_file" FZF_ARGS_FILE="$args_file" \ + PATH="$shim_dir:$PATH" just cross cd >/dev/null 2>&1 || true + [ -s "$stdin_file" ] || fail "Just fzf picker should receive candidate rows" + awk -F'\t' -v w="$width" ' + NF != 2 { bad = 1 } + substr($1, w + 1, 1) == " " { bad = 1 } + substr($1, w, 1) != " " { bad = 1 } + $2 == "" { bad = 1 } + END { exit bad ? 1 : 0 } + ' "$stdin_file" || fail "Just picker rows must align at column $((width + 1)) and end with a TAB key" + awk -F'\t' '$1 ~ /mxc-library:pkg \(feature\)$/ { found = 1 } END { exit found ? 0 : 1 }' "$stdin_file" \ + || fail "Just picker should show the branch for non-main patches" + header_val=$(awk '/^--header$/{ getline; print; exit }' "$args_file") + expected_header="LOCAL_PATH$(printf '%*s' "$((width - 10))" '')REMOTE:REMOTE_PATH" + [ "$header_val" = "$expected_header" ] \ + || fail "Just padded header mismatch: got '$header_val', want '$expected_header'" + log_success "Just fzf picker alignment verified" + log_header "017: Just completion prints cd wrappers" comp_bash=$(just cross completion bash 2>&1) || fail "Just completion bash should exit 0" assert_contains "$comp_bash" "crosscd()" "Just bash completion should define crosscd" diff --git a/test/021_fzf_diff_compare.sh b/test/021_fzf_diff_compare.sh index f03537932..0c7e6f351 100755 --- a/test/021_fzf_diff_compare.sh +++ b/test/021_fzf_diff_compare.sh @@ -82,8 +82,8 @@ if [ -n "$GO_BIN" ]; then # --- fzf shim: selection drives diff/compare log_header "021: Go diff/compare operate on the fzf selection" - sel_alpha='upstream\t.\tvendor/alpha' - sel_beta='upstream\t.\tvendor/beta' + sel_alpha='vendor/alpha upstream:.\tvendor/alpha' + sel_beta='vendor/beta upstream:.\tvendor/beta' out=$(FZF_SELECT="$sel_alpha" PATH="$fzf_shim_dir:$PATH" "$GO_BIN" diff 2>&1) || true echo "$out" @@ -222,7 +222,7 @@ if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command - log_header "021: Just diff/compare operate on the fzf selection" git config cross.diffTool 'echo TOOL {left} {right}' wt_alpha=$(jq -r '.patches[] | select(.local_path == "vendor/alpha") | .worktree' .cross/metadata.json) - sel_alpha="vendor/alpha\t$wt_alpha" + sel_alpha="vendor/alpha upstream:.\tvendor/alpha" out=$(FZF_SELECT="$sel_alpha" PATH="$fzf_shim_dir:$PATH" just cross diff 2>&1) || true echo "$out" assert_contains "$out" "local alpha change" "Just diff should operate on the selected alpha patch" From f07f3f09f10fd4782e8aa497aaedb2dd3087de0e Mon Sep 17 00:00:00 2001 From: docs-impl Date: Thu, 12 Nov 2026 09:17:47 +0100 Subject: [PATCH 21/22] feat(cli): concise update warning, review block, cross.dirdifftool - update prints only the fact per patch ('' differs from upstream; local copy preserved) and, after a run that processed any patch, one generic path-less review block: 'git cross diff' / 'git cross compare' (both are fzf-assisted when no path is given) - rename the comparison tool key to cross.dirdifftool (it operates on directories, matching the DIRDIFF_* env vars); cross.diffTool is still read as a deprecated fallback and the new key wins when both are set - Go + Just emit the same warning/block and the same key lookup order - tests 004/018/020/021 updated; 009/021 cover the legacy fallback and precedence; README documents the migration one-liner --- AGENTS.md | 3 +- CHANGELOG.md | 9 ++--- Justfile.cross | 17 +++++++--- README.md | 43 +++++++++++++++++------- src-go/main.go | 30 +++++++++++------ test/004_update.sh | 19 +++++++++-- test/009_go_cli.sh | 30 +++++++++++++---- test/018_sbx_sandbox.sh | 7 ++-- test/019_whole_repo_patch_and_listing.sh | 8 ++--- test/020_help_groups.sh | 4 +-- test/021_fzf_diff_compare.sh | 22 ++++++++---- 11 files changed, 136 insertions(+), 56 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ec5c2fd05..16470eaff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -196,10 +196,11 @@ Tests 001-007 form a chain for Just/Fish (001 is sourced by 002, etc.). Test 009 - **`.git` exclusion**: a worktree root contains a `.git` pointer file that never exists in the local copy (rsync uses `--exclude .git`). Boolean tree comparisons use `rsync -rlcn --delete --exclude=.git --itemize-changes`; the visual diff (`git diff --no-index`) is run against a temporary `.git`-free mirror of the worktree, because pathspec excludes like `:(exclude).git` are rejected by older git versions with a usage error. Without both exclusions, whole-repo patches always look modified. - **Sparse checkout**: `git sparse-checkout init --no-cone` + `git sparse-checkout set /` + `git read-tree -mu HEAD`. The trailing `/` on the pattern is required for reliable directory matching in `--no-cone` mode on newer Git versions (2.43+). `read-tree -mu HEAD` explicitly materializes the worktree (bare `git checkout` can no-op after `--no-checkout`). - **Rsync**: `rsync -av --delete --exclude .git` for worktree-to-local sync. `--delete` removes files locally that were deleted upstream. -- **Directory diff tool**: `cross.diffTool` supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `nvim` when installed, else `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). When unset, env vars extend the default: `DIRDIFF_EXCLUDES` appends names to the exclusion list (`.git` stays permanent) and `DIRDIFF_IGNORE` adds `g:DirDiffIgnore` with a very-nomagic (`\V`) alternation of the comma-separated keywords. Empty/unset vars omit the corresponding argument. Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). +- **Directory diff tool**: `cross.dirdifftool` is the canonical key (the pre-0.4 `cross.diffTool` is still read as a deprecated fallback; the new key wins when both are set). It supports `{left}`/`{right}` placeholders substituted with repo-relative paths, run with cwd = repo root. Default: `nvim` when installed, else `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two separate `+cmd` arguments; `DirDiffIgnore=...` is not a vim command). When unset, env vars extend the default: `DIRDIFF_EXCLUDES` appends names to the exclusion list (`.git` stays permanent) and `DIRDIFF_IGNORE` adds `g:DirDiffIgnore` with a very-nomagic (`\V`) alternation of the comma-separated keywords. Empty/unset vars omit the corresponding argument. Configs without placeholders fall back to appending both absolute paths (legacy, deprecated — it never invoked DirDiff correctly). - **Clipboard helper (parked)**: `copyToClipboard` (Go) / `_clip` (Just) remain implemented but are intentionally unused — `cd`/`wt` print a path and `completion` provides the real `cd`, which made the clipboard workflow obsolete. Reuse rather than reimplement if a clipboard feature returns. - **Shell integration**: `cd`/`wt` print only the path to stdout (hints/rows go to stderr), so a parent-shell wrapper can capture it. `git cross completion [fish|bash|zsh|powershell]` emits the Cobra completion script plus the `crosscd`/`crosswt` functions (fish first in usage/errors); the shell defaults to the basename of `$SHELL`, and an unknown/undetectable shell exits 1 instead of guessing. fish must use `git cross completion fish | source` because fish joins multi-line command substitution with spaces (`eval (...)` breaks); `init` prints the shell-appropriate one-liner. `shell-init` is hidden but kept for compatibility and emits only the wrappers. powershell gets completions only. Just emits the wrappers only (Cobra scripts are a Go CLI concern). - **Interactive picker**: `selectPatchInteractive` (Go) and `_select_patch` (Just) share `cd`/`wt`/`diff`/`compare`. Rows are `` with `width = max(len(local_path)) + 2`, clamped to 16–48; the second column is `remote:remote_path` plus `(branch)` when the branch is not `main`; the header legend is padded with the same width. fzf runs with `--delimiter \t --with-nth=1` so the trailing key is hidden and the selection is parsed from the last TAB field. Just computes the padding in jq. The machine `_list_patches` rows (`local_pathworktree`) are unchanged. +- **`update` reporting**: a patch whose local copy differs from upstream gets one short line (`'' differs from upstream; local copy preserved`) with no inline suggestion. After a run that processed at least one patch, a generic path-less review block is printed once: `git cross diff` (fzf pick, see the diff) and `git cross compare` (fzf pick, dirdiff tool). Both commands already resolve a patch via CWD auto-detect → fzf → rows + exit 1. - **Patch rows**: bare `git cross`, and path-miss cases in `compare`/`diff`/`remove`/`cd`/`wt`, print `local_pathworktree` rows to stdout; hints go to stderr and the command exits 1 where nothing was resolved. - **`list --raw` schema**: remotes first (`REMOTE_NAMEREMOTE_URL`), then patches (`REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`); no banners, no borders, deterministic remote order. - **`rerere` (conflict resolution memory)**: `ensureRerere` (Go) / an inline `git config rerere.enabled true` (Just) runs in `init` (announces, and says "already enabled" on repeat), `patch` (silent), and `update` (announces only when it newly enables it, which self-heals older repos). The key is written to the shared repository config, so the main repo and every cross worktree see it; each worktree records resolutions in its own `rr-cache`. `rerere.autoUpdate` is intentionally left unset (opt-in, users enable it themselves). Just's `init` resolves the repo root explicitly so it never writes global config. diff --git a/CHANGELOG.md b/CHANGELOG.md index 43ebb2a08..b96c52bc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 #### Added - **`git cross cmp`** - Short alias for `compare`; the canonical name is unchanged. -- **Grouped `--help` output** - Commands are listed under `Patch Lifecycle:`, `Repository:`, and `Inspect & Navigate:` instead of one flat list. `use` and `patch` appear first (in that order), and `cd`/`wt` stay adjacent. `git cross -h` still prints full help, and the help text documents `cross.diffTool` setup. +- **Grouped `--help` output** - Commands are listed under `Patch Lifecycle:`, `Repository:`, and `Inspect & Navigate:` instead of one flat list. `use` and `patch` appear first (in that order), and `cd`/`wt` stay adjacent. `git cross -h` still prints full help, and the help text documents `cross.dirdifftool` setup. - **`completion`** - `git cross completion [fish|bash|zsh|powershell]` prints the shell completion script **plus** `crosscd`/`crosswt` functions that perform a real `cd` in the caller's shell (a child process cannot change it). The shell defaults to the basename of `$SHELL`; an unknown or undetectable shell exits 1 instead of guessing. fish uses `git cross completion fish | source` (multi-line `eval (...)` breaks in fish); `init` prints the matching one-liner for the caller's shell. `shell-init` is now hidden (kept for compatibility, wrappers only), and the clipboard fallback is no longer wired into `cd`/`wt`; its helper is kept isolated (unused) for possible reuse. - **Conflict resolution memory (`rerere`)** - `init`, `patch`, and `update` enable Git's `rerere.enabled` in the shared repository config, so a conflict resolved once in a cross worktree is replayed automatically when the same conflict reappears on a later update. `init` announces the setting (and reports when it is already on), `patch` is silent, and `update` re-enables it for repositories set up before this change. `rerere.autoUpdate` is intentionally left unset (opt-in). Documented in README as "Conflict Resolution Memory (`rerere`)" and covered by `test/024_rerere.sh`, including a real resolve-then-replay scenario. - **`list --raw` and `list --no-header`** - `--raw` emits tab-separated rows with no table borders and no `==>` banners; `--no-header` omits the header line. Raw column order is documented and fixed: `REMOTE_NAMEREMOTE_URL` first, then `REMOTEREMOTE_PATHLOCAL_PATHWORKTREEBRANCH`. Remote rows are sorted deterministically, remotes with distinct fetch/push URLs produce one row per URL without `(fetch)`/`(push)` suffixes, and the empty-state message goes to stderr in raw mode. On a terminal the columns are space-padded for readability; piped output stays TAB-separated. @@ -24,10 +24,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **BREAKING: `cd` / `wt` print a path instead of opening a shell** - Both commands print the absolute destination path to stdout (hints to stderr). They no longer start a subshell and no longer copy anything to the clipboard. Use `cd "$(git cross cd)"`, `cd "$(git cross wt)"`, or the `crosscd`/`crosswt` functions from `git cross completion`. Without an argument they auto-detect the current patch, then use `fzf`; if `fzf` is missing, rows plus a hint are printed and the command exits 1. - **Behavior change: interactive `diff` selection** - With no path, `diff` resolves the patch via CWD auto-detect, then `fzf`, then rows + hint + exit 1. Previously, running `diff` from outside a patch directory dumped diffs for all patches. - **`compare` selection ladder** - With no path, `compare` uses the same CWD auto-detect → `fzf` → rows + hint + exit 1 ladder and always operates on exactly one patch. -- **`cross.diffTool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). `DIRDIFF_EXCLUDES` appends extra file/dir names to the exclusion list (`.git` is always ignored) and `DIRDIFF_IGNORE` ignores comma-separated keywords in diff content (converted to a very-nomagic `\V` regexp), e.g. `DIRDIFF_IGNORE=github.com,gitlab.com`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. -- **Concise `update` warning** - Local edits now produce one relative, actionable line: `'' differs from upstream; local copy preserved. Compare with: git cross diff `. The `cross.diffTool` configuration hint and the broken DirDiff invocation are gone. +- **`cross.dirdifftool` template form** - The configured command may contain `{left}` / `{right}`, replaced with repo-relative paths while running with the repo root as cwd. The default is `nvim` when installed, otherwise `vim`, using `"+let g:DirDiffExcludes = '.git'" "+DirDiff {left} {right}"` (two `+cmd` arguments: `DirDiffIgnore=...` is not a vim command). `DIRDIFF_EXCLUDES` appends extra file/dir names to the exclusion list (`.git` is always ignored) and `DIRDIFF_IGNORE` ignores comma-separated keywords in diff content (converted to a very-nomagic `\V` regexp), e.g. `DIRDIFF_IGNORE=github.com,gitlab.com`. The legacy append form (for example `vim "+DirDiff"`) is deprecated. +- **Concise `update` warning** - Local edits now produce only the fact: `'' differs from upstream; local copy preserved`. After the run, one generic path-less block suggests the next step (`git cross diff` / `git cross compare`, both fzf-assisted). The dirdiff configuration hint and the broken DirDiff invocation are gone. - **Simplified upstream workflow** - `git cross update [path]` reads declarative `use`/`patch` entries from `Crossfile`, fetches upstream, fast-forwards sparse worktrees, and installs only when the local copy has no edits. Local edits are preserved while the worktree advances for manual comparison. -- **Manual contribution workflow** - Retired `push`; use `wt`, `compare`, and ordinary Git commands to manually copy and commit desired changes in the sparse worktree. The comparison tool is configured with `cross.diffTool` (see the Directory Diff Tool section in `README.md`). +- **Config key renamed to `cross.dirdifftool`** - The comparison tool operates on directories (DirDiff and similar), so the key now matches the `DIRDIFF_*` environment variables. The pre-0.4 `cross.diffTool` key keeps working as a deprecated fallback (the new key wins when both are set); the README documents a one-line migration. +- **Manual contribution workflow** - Retired `push`; use `wt`, `compare`, and ordinary Git commands to manually copy and commit desired changes in the sparse worktree. The comparison tool is configured with `cross.dirdifftool` (see the Directory Diff Tool section in `README.md`). - **Retired replay and arbitrary Crossfile commands** - `update` interprets only `use` and `patch`; hooks and shell commands are no longer run from Crossfile. - **Supported implementations** - Go remains primary and Just/Fish the reference. Rust source is retained but no longer maintained; release artifacts are Go-only. - **Retired sync workflow** - The prior stash/copy/rebase logic is removed from the supported CLI and Just recipes. diff --git a/Justfile.cross b/Justfile.cross index ee0edd4c1..dfdea819c 100644 --- a/Justfile.cross +++ b/Justfile.cross @@ -666,7 +666,7 @@ _update_patch spec local_path: exit 1 end if test "$local_changed" = "true" - just cross _log warn "'$l_path' differs from upstream; local copy preserved. Compare with: git cross diff $l_path" + just cross _log warn "'$l_path' differs from upstream; local copy preserved" exit 0 end mkdir -p "$local_abs" @@ -738,6 +738,11 @@ update path="": check-deps just cross _log error "No Crossfile patch found for {{path}}" exit 1 end + if test $updates -gt 0 + just cross _log info "Review the differences:" + echo " git cross diff # pick a patch with fzf and see the diff" + echo " git cross compare # pick a patch and update it (dirdiff tool)" + end popd >/dev/null # Diff local vs upstream @@ -821,11 +826,11 @@ diff path="": check-initialized end popd -# Open the configured directory comparison tool (git config cross.diffTool). +# Open the configured directory comparison tool (git config cross.dirdifftool). [no-cd] compare path="": check-initialized #!/usr/bin/env fish - # cross.diffTool may contain {left}/{right} placeholders (repo-relative paths); + # cross.dirdifftool may contain {left}/{right} placeholders (repo-relative paths); # without placeholders the paths are appended as arguments (legacy form). # Resolve metadata: explicit path, CWD auto-detect, then fzf selection set -l ctx (just cross _resolve_context2 "{{path}}" 2>/dev/null) @@ -846,7 +851,11 @@ compare path="": check-initialized end printf '%s\n' $ctx | source - set tool (git config --get cross.diffTool 2>/dev/null) + # cross.dirdifftool is canonical; cross.diffTool is a deprecated fallback. + set tool (git config --get cross.dirdifftool 2>/dev/null) + if test -z "$tool" + set tool (git config --get cross.diffTool 2>/dev/null) + end if test -z "$tool" set -l editor vim if command -v nvim >/dev/null 2>&1 diff --git a/README.md b/README.md index bb1c6c680..078ce6605 100644 --- a/README.md +++ b/README.md @@ -209,7 +209,7 @@ Recommended pattern: 2. Compare it with the local patch using `git cross compare vendor/app`, or print a console diff with `git cross diff vendor/app`. 3. Manually copy desired changes into the worktree, then commit and push with Git. -`compare` uses the command configured in `cross.diffTool`; see [Directory Diff Tool](#directory-diff-tool-crossdifftool). +`compare` uses the command configured in `cross.dirdifftool`; see [Directory Diff Tool](#directory-diff-tool-crossdirdifftool). This lets your main repo keep its local opinionated result while the upstream contribution stays focused. @@ -290,10 +290,18 @@ git cross update [path] Read `Crossfile`, fetch upstream updates, and update each patch. -If the local copy still matches the previously installed upstream content, `update` refreshes it in place. If the local copy has edits, `update` preserves it, advances the sparse worktree to the new upstream state, and prints a single warning: +If the local copy still matches the previously installed upstream content, `update` refreshes it in place. If the local copy has edits, `update` preserves it, advances the sparse worktree to the new upstream state, and prints only the fact: ```text -'vendor/docs' differs from upstream; local copy preserved. Compare with: git cross diff vendor/docs +==> WARNING: 'vendor/docs' differs from upstream; local copy preserved +``` + +After the run, a generic review block follows (both commands use fzf or the current patch when no path is given): + +```text +Review the differences: + git cross diff # pick a patch with fzf and see the diff + git cross compare # pick a patch and update it (dirdiff tool) ``` Review the differences and merge manually. Whole-repository patches (`remote:.` and `remote:/`) take part in this check correctly: the worktree's `.git` pointer file is not counted as a local edit, so a clean whole-repo patch is updated instead of warned about. @@ -335,7 +343,7 @@ Both commands view the same pair of directories — the local copy and the spars | | `diff` | `compare` | |---|---|---| -| Output | unified diff on stdout | the tool from `cross.diffTool` | +| Output | unified diff on stdout | the tool from `cross.dirdifftool` | | Scope | one patch (from a path, CWD, or `fzf`) | exactly one patch (from a path, CWD, or `fzf`) | | Unresolved patch | rows + exit 1 | rows + exit 1 | | Typical use | quick review, scripting, CI | side-by-side editing in an editor | @@ -521,13 +529,22 @@ Select patch> If `fzf` is not installed, the command prints the available patch rows plus a hint to `cd` manually, and exits 1. -## Directory Diff Tool (`cross.diffTool`) +## Directory Diff Tool (`cross.dirdifftool`) -`compare` uses the command configured in `cross.diffTool`. Configure it +`compare` uses the command configured in `cross.dirdifftool`. Configure it globally or per repository: ```bash -git config --global cross.diffTool '' +git config --global cross.dirdifftool '' +``` + +The key is named after the *directory* diff tool it configures (DirDiff and +similar tools compare whole trees of files). The pre-0.4 key `cross.diffTool` +is still read as a deprecated fallback; migrate with: + +```bash +git config --global cross.dirdifftool "$(git config --global --get cross.diffTool)" \ + && git config --global --unset cross.diffTool ``` ### Template form (current) @@ -539,7 +556,7 @@ before the command is run: - `{right}` — the patch's local copy The substituted paths are **repo-relative**, and the command runs with the -repository root as its working directory. When `cross.diffTool` is unset the +repository root as its working directory. When `cross.dirdifftool` is unset the built-in default is used — `nvim` if it is installed, otherwise `vim`: ```text @@ -552,18 +569,18 @@ command, so the exclusion is set with `let` first, then `DirDiff` runs with the directories as arguments. To pin a specific editor, set it explicitly: ```bash -git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" +git config --global cross.dirdifftool "nvim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" # strictly vim: -git config --global cross.diffTool "vim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" +git config --global cross.dirdifftool "vim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" ``` A custom ignore list passes DirDiff a comma-separated list of names to skip: ```bash -git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes = '.git,ves.io,f5fed.com,volterra.us'\" \"+DirDiff {left} {right}\"" +git config --global cross.dirdifftool "nvim \"+let g:DirDiffExcludes = '.git,ves.io,f5fed.com,volterra.us'\" \"+DirDiff {left} {right}\"" ``` -### Environment variables (when `cross.diffTool` is unset) +### Environment variables (when `cross.dirdifftool` is unset) Two optional variables feed the built-in default; both are comma-separated: @@ -594,7 +611,7 @@ paths are appended as trailing arguments. ```bash # Deprecated: paths become vim file arguments, not DirDiff arguments. -git config --global cross.diffTool 'vim "+DirDiff"' +git config --global cross.dirdifftool 'vim "+DirDiff"' ``` This form is deprecated because it does not invoke DirDiff correctly. Migrate diff --git a/src-go/main.go b/src-go/main.go index dfa44e239..1cba3606f 100644 --- a/src-go/main.go +++ b/src-go/main.go @@ -328,9 +328,13 @@ func defaultDiffTool() string { } func diffTool() string { - if out, err := exec.Command("git", "config", "--get", "cross.diffTool").Output(); err == nil { - if tool := strings.TrimSpace(string(out)); tool != "" { - return tool + // cross.dirdifftool is canonical; cross.diffTool is a deprecated fallback so + // configurations written before the rename keep working. + for _, key := range []string{"cross.dirdifftool", "cross.diffTool"} { + if out, err := exec.Command("git", "config", "--get", key).Output(); err == nil { + if tool := strings.TrimSpace(string(out)); tool != "" { + return tool + } } } return defaultDiffTool() @@ -1112,18 +1116,19 @@ func main() { SilenceUsage: true, // no Usage dump on errors Long: `Manage vendored cross-repo patches (worktree + rsync). -Directory diff tool (compare / cmp): when cross.diffTool is unset, nvim is used -if installed, otherwise vim, with .git ignored. To use the built-in default: +Directory diff tool (compare / cmp): when cross.dirdifftool is unset, nvim is +used if installed, otherwise vim, with .git ignored. To use the built-in default: - git config --global --unset cross.diffTool + git config --global --unset cross.dirdifftool To pin it explicitly (recommended): - git config --global cross.diffTool "nvim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" + git config --global cross.dirdifftool "nvim \"+let g:DirDiffExcludes = '.git'\" \"+DirDiff {left} {right}\"" -Replace nvim with vim to pin vim instead. +Replace nvim with vim to pin vim instead. The legacy cross.diffTool key is still +read as a fallback. -Environment variables (used only when cross.diffTool is unset): +Environment variables (used only when cross.dirdifftool is unset): DIRDIFF_EXCLUDES extra comma-separated file/dir names to hide; .git is always ignored DIRDIFF_IGNORE comma-separated keywords ignored in diff content (e.g. github.com,gitlab.com) @@ -1694,8 +1699,7 @@ Shell completions + cd wrappers (crosscd / crosswt) - evaluate once in your prof } updated++ if localChanged { - logWarn(fmt.Sprintf("'%s' differs from upstream; local copy preserved. Compare with: git cross diff %s", - localPath, localPath)) + logWarn(fmt.Sprintf("'%s' differs from upstream; local copy preserved", localPath)) continue } if err := os.MkdirAll(localAbs, 0o755); err != nil { @@ -1711,7 +1715,11 @@ Shell completions + cd wrappers (crosscd / crosswt) - evaluate once in your prof } if updated == 0 { logInfo("No patches updated.") + return nil } + logInfo("Review the differences:") + fmt.Println(" git cross diff # pick a patch with fzf and see the diff") + fmt.Println(" git cross compare # pick a patch and update it (dirdiff tool)") return nil }, } diff --git a/test/004_update.sh b/test/004_update.sh index 62aaca2e6..9d375b6a8 100755 --- a/test/004_update.sh +++ b/test/004_update.sh @@ -13,6 +13,9 @@ assert_grep "vendor/lib/lib.txt" "upstream-v2" if echo "$clean_output" | grep -q "differs from upstream"; then fail "Update should not warn about local edits for a clean patch" fi +if ! echo "$clean_output" | grep -q "Review the differences:"; then + fail "A completed update run should print the review block" +fi log_success "Clean patch updated" log_header "Preserving local edits and refreshing sparse worktree..." @@ -26,8 +29,20 @@ assert_grep "vendor/lib/lib.txt" "local-edit" if ! echo "$output" | grep -q "differs from upstream"; then fail "Update should report that the local copy differs from upstream" fi -if ! echo "$output" | grep -q "cross diff vendor/lib"; then - fail "Update should point at 'git cross diff ' for review" +if echo "$output" | grep -q "Compare with:"; then + fail "Update warning should not inline a per-path suggestion" +fi +if ! echo "$output" | grep -q "Review the differences:"; then + fail "Update should print the end-of-run review block" +fi +if ! echo "$output" | grep -q "git cross diff "; then + fail "Review block should suggest 'git cross diff' without a path" +fi +if ! echo "$output" | grep -q "git cross compare"; then + fail "Review block should suggest 'git cross compare'" +fi +if echo "$output" | grep -q "git cross diff vendor/lib"; then + fail "Review block should not repeat per-patch paths" fi # The old verbose workflow (global config hint + tool invocation) is gone. if echo "$output" | grep -q "Local edits detected"; then diff --git a/test/009_go_cli.sh b/test/009_go_cli.sh index aeca6aa86..f17fed6c1 100755 --- a/test/009_go_cli.sh +++ b/test/009_go_cli.sh @@ -263,8 +263,8 @@ fi if echo "$update_output" | grep -q "DirDiff"; then fail "Go update should not print the configured diff tool command" fi -if echo "$update_output" | grep -q "git config --global cross.diffTool"; then - fail "Go update should not print the global cross.diffTool hint" +if echo "$update_output" | grep -q "git config --global cross.dirdifftool"; then + fail "Go update should not print the global cross.dirdifftool hint" fi log_header "Testing Go 'diff' command..." @@ -286,7 +286,7 @@ EOF chmod +x "$SANDBOX/bin/compare-tool" export COMPARE_TOOL_ARGS="$SANDBOX/compare-args.txt" # Template form: placeholders are substituted with repo-relative paths. -git config cross.diffTool "$SANDBOX/bin/compare-tool {left} {right}" +git config cross.dirdifftool "$SANDBOX/bin/compare-tool {left} {right}" "$GO_BIN" compare vendor/go-src if ! grep -q ".cross/worktrees/demo_" "$COMPARE_TOOL_ARGS"; then fail "Go compare did not pass the sparse worktree path" @@ -300,7 +300,7 @@ fi # Legacy form (no placeholders) still appends the paths as arguments. rm -f "$COMPARE_TOOL_ARGS" -git config cross.diffTool "$SANDBOX/bin/compare-tool" +git config cross.dirdifftool "$SANDBOX/bin/compare-tool" "$GO_BIN" compare vendor/go-src if ! grep -q ".cross/worktrees/demo_" "$COMPARE_TOOL_ARGS"; then fail "Go compare legacy form did not pass the sparse worktree path" @@ -308,16 +308,34 @@ fi if ! grep -q "vendor/go-src" "$COMPARE_TOOL_ARGS"; then fail "Go compare legacy form did not pass the local patch path" fi -git config --unset cross.diffTool +git config --unset cross.dirdifftool unset COMPARE_TOOL_ARGS # The 'cmp' alias behaves like 'compare'. -git config cross.diffTool 'echo TOOL {left} {right}' +git config cross.dirdifftool 'echo TOOL {left} {right}' cmp_output=$("$GO_BIN" cmp vendor/go-src 2>&1 || true) echo "$cmp_output" if ! echo "$cmp_output" | grep -Eq "TOOL \.cross/worktrees/demo_[0-9a-f]+/src vendor/go-src"; then fail "Go 'cmp' alias should resolve and run the diff tool like 'compare'" fi +git config --unset cross.dirdifftool + +log_header "Testing Go legacy cross.diffTool fallback..." +# The deprecated key still drives the tool... +git config cross.diffTool 'echo LEGACY {left} {right}' +legacy_output=$("$GO_BIN" compare vendor/go-src 2>&1 || true) +echo "$legacy_output" +if ! echo "$legacy_output" | grep -q "LEGACY .cross/worktrees/demo_"; then + fail "Legacy cross.diffTool should still be used as a fallback" +fi +# ...but the canonical key wins when both are set. +git config cross.dirdifftool 'echo NEW {left} {right}' +both_output=$("$GO_BIN" compare vendor/go-src 2>&1 || true) +echo "$both_output" +if ! echo "$both_output" | grep -q "NEW .cross/worktrees/demo_"; then + fail "cross.dirdifftool should take precedence over the legacy key" +fi +git config --unset cross.dirdifftool git config --unset cross.diffTool log_header "Testing Go '.crossignore' override status/diff hint..." diff --git a/test/018_sbx_sandbox.sh b/test/018_sbx_sandbox.sh index 5daf3ce81..f1e4e369c 100644 --- a/test/018_sbx_sandbox.sh +++ b/test/018_sbx_sandbox.sh @@ -42,8 +42,11 @@ fi if ! echo "$output" | grep -q "differs from upstream"; then fail "Update did not report that the local copy differs from upstream" fi -if ! echo "$output" | grep -q "cross diff vendor/ai-src"; then - fail "Update did not point at 'git cross diff ' for review" +if ! echo "$output" | grep -q "Review the differences:"; then + fail "Update did not print the end-of-run review block" +fi +if echo "$output" | grep -q "cross diff vendor/ai-src"; then + fail "Review block should be path-less (fzf selection)" fi if echo "$output" | grep -q "Local edits detected"; then fail "Update still prints the old 'Local edits detected' wording" diff --git a/test/019_whole_repo_patch_and_listing.sh b/test/019_whole_repo_patch_and_listing.sh index eb4434cd6..782ff96fb 100755 --- a/test/019_whole_repo_patch_and_listing.sh +++ b/test/019_whole_repo_patch_and_listing.sh @@ -7,7 +7,7 @@ # - `diff` shows real changes and never the `.git` pointer # - bare `git-cross` and an unresolved `compare` print machine-parseable # rows (`local_pathworktree`) instead of a Usage dump -# - `cross.diffTool` template placeholders receive repo-relative paths +# - `cross.dirdifftool` template placeholders receive repo-relative paths source "$(dirname "$0")/common.sh" PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)" @@ -110,8 +110,8 @@ if [ -n "$GO_BIN" ]; then log_success "unresolved 'compare' prints rows and exits 1" # --- diffTool template substitution uses repo-relative paths - log_header "019: cross.diffTool {left}/{right} template substitution" - git config cross.diffTool 'echo TOOL {left} {right}' + log_header "019: cross.dirdifftool {left}/{right} template substitution" + git config cross.dirdifftool 'echo TOOL {left} {right}' tool_out=$("$GO_BIN" compare sub 2>&1 || true) echo "$tool_out" @@ -123,7 +123,7 @@ if [ -n "$GO_BIN" ]; then alias_out=$("$GO_BIN" cmp sub 2>&1 || true) echo "$alias_out" assert_contains "$alias_out" "TOOL .cross/worktrees/up_" "the 'cmp' alias should behave like 'compare'" - git config --unset cross.diffTool || true + git config --unset cross.dirdifftool || true log_success "diffTool template substitution verified" fi diff --git a/test/020_help_groups.sh b/test/020_help_groups.sh index fb70068bc..bdefa2d5e 100755 --- a/test/020_help_groups.sh +++ b/test/020_help_groups.sh @@ -89,10 +89,10 @@ log_success "-h works" log_header "020: help suggests the cross.diffTool setup" assert_contains "$help_output" "cross.diffTool" "help should mention cross.diffTool setup" -assert_contains "$help_output" "--unset cross.diffTool" "help should show how to reset to the built-in default" +assert_contains "$help_output" "--unset cross.dirdifftool" "help should show how to reset to the built-in default" assert_contains "$help_output" "let g:DirDiffExcludes = '.git'" "help should show the correct DirDiff exclusion syntax" assert_contains "$help_output" "DirDiff {left} {right}" "help should show the placeholder form" -pin_lines=$(printf '%s\n' "$help_output" | grep -c 'cross.diffTool "') +pin_lines=$(printf '%s\n' "$help_output" | grep -c 'cross.dirdifftool "') [ "$pin_lines" -eq 1 ] || fail "help should show the explicit diffTool config line exactly once (found $pin_lines)" if printf '%s\n' "$help_output" | grep -q "Strictly vim"; then fail "help must not repeat the same config line for vim" diff --git a/test/021_fzf_diff_compare.sh b/test/021_fzf_diff_compare.sh index 0c7e6f351..2c7d8b0a2 100755 --- a/test/021_fzf_diff_compare.sh +++ b/test/021_fzf_diff_compare.sh @@ -95,7 +95,7 @@ if [ -n "$GO_BIN" ]; then assert_contains "$out" "local beta change" "diff should operate on the selected beta patch" assert_not_contains "$out" "local alpha change" "diff should not include the unselected alpha patch" - git config cross.diffTool 'echo TOOL {left} {right}' + git config cross.dirdifftool 'echo TOOL {left} {right}' out=$(FZF_SELECT="$sel_alpha" PATH="$fzf_shim_dir:$PATH" "$GO_BIN" compare 2>&1) || true echo "$out" assert_contains "$out" "TOOL .cross/worktrees/upstream_" "compare should run the tool on the selected worktree" @@ -106,12 +106,12 @@ if [ -n "$GO_BIN" ]; then echo "$out" assert_contains "$out" "vendor/beta" "the 'cmp' alias should use the fzf selection" assert_not_contains "$out" "vendor/alpha" - git config --unset cross.diffTool || true + git config --unset cross.dirdifftool || true log_success "fzf selection drives diff/compare" # --- default diff tool: nvim preferred, vim fallback log_header "021: default diffTool prefers nvim, falls back to vim" - git config --unset cross.diffTool || true + git config --unset cross.dirdifftool || true both_shims="$SANDBOX/editor-shims" vim_shims="$SANDBOX/vim-shims" mkdir -p "$both_shims" "$vim_shims" @@ -141,7 +141,7 @@ SH echo "$out" assert_contains "$out" "EDITOR:vim" "default tool should fall back to vim when nvim is absent" - # environment-driven extras (only when cross.diffTool is unset) + # environment-driven extras (only when cross.dirdifftool is unset) out=$(env -u DIRDIFF_IGNORE -u DIRDIFF_EXCLUDES PATH="$both_shims:$PATH" "$GO_BIN" compare vendor/alpha 2>/dev/null) assert_contains "$out" "let g:DirDiffExcludes = '.git'" "minimal default keeps .git excluded" assert_not_contains "$out" "DirDiffIgnore" "no ignore argument should be emitted without DIRDIFF_IGNORE" @@ -169,12 +169,12 @@ SH assert_not_contains "$out" "local beta change" assert_not_contains "$out" "fzf is not installed" "auto-detect must not consult fzf" - git config cross.diffTool 'echo TOOL {left} {right}' + git config cross.dirdifftool 'echo TOOL {left} {right}' out=$(PATH="$nofzf_path" "$GO_BIN" compare 2>&1) || true echo "$out" assert_contains "$out" "TOOL .cross/worktrees/upstream_" "compare inside vendor/alpha should auto-detect" assert_contains "$out" "vendor/alpha" - git config --unset cross.diffTool || true + git config --unset cross.dirdifftool || true popd >/dev/null log_success "auto-detect verified" fi @@ -220,7 +220,7 @@ if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command - assert_contains "$compare_out" "fzf is not installed" "Just compare should explain that fzf is missing" log_header "021: Just diff/compare operate on the fzf selection" - git config cross.diffTool 'echo TOOL {left} {right}' + git config cross.dirdifftool 'echo TOOL {left} {right}' wt_alpha=$(jq -r '.patches[] | select(.local_path == "vendor/alpha") | .worktree' .cross/metadata.json) sel_alpha="vendor/alpha upstream:.\tvendor/alpha" out=$(FZF_SELECT="$sel_alpha" PATH="$fzf_shim_dir:$PATH" just cross diff 2>&1) || true @@ -232,6 +232,14 @@ if command -v fish >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && command - echo "$out" assert_contains "$out" "vendor/alpha" "Just compare should resolve the selected local path" assert_contains "$out" "TOOL .cross/worktrees/upstream_" "Just compare should run the tool on the selected worktree" + + # Legacy key fallback: cross.diffTool still works when the new one is unset. + git config --unset cross.dirdifftool || true + git config cross.diffTool 'echo LEGACY {left} {right}' + out=$(FZF_SELECT="$sel_alpha" PATH="$fzf_shim_dir:$PATH" just cross compare 2>&1) || true + echo "$out" + assert_contains "$out" "LEGACY .cross/worktrees/upstream_" \ + "Just compare should fall back to the legacy cross.diffTool key" git config --unset cross.diffTool || true log_header "021: Just default diffTool prefers nvim" From 3e4da9501904e3dda9c278269f7153f9845660f3 Mon Sep 17 00:00:00 2001 From: Petr Michalec Date: Fri, 13 Nov 2026 08:44:53 +0100 Subject: [PATCH 22/22] fixes for go-releaser --- .github/workflows/release.yml | 7 ++++--- .goreleaser.yaml | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ab27b363b..d591cef5f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,13 +20,14 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: '1.23' - cache-path: src-go + go-version: '1.24.4' + cache-path: src-go/go.sum - name: Run GoReleaser uses: goreleaser/goreleaser-action@v6 with: distribution: goreleaser version: latest - args: release --clean + args: release --clean --config ../.goreleaser.yaml + workdir: src-go env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 51cbeb4d5..63a8f3b76 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -4,11 +4,11 @@ project_name: git-cross before: hooks: - - go mod tidy -C src-go + - go mod tidy . builds: - id: git-cross-go - main: ./src-go/main.go + main: ./main.go binary: git-cross env: - CGO_ENABLED=0