diff --git a/Cargo.lock b/Cargo.lock index 839f06f..fc2df3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20,6 +20,12 @@ dependencies = [ "libc", ] +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + [[package]] name = "anstream" version = "0.6.21" @@ -132,6 +138,12 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + [[package]] name = "cc" version = "1.2.56" @@ -162,6 +174,33 @@ dependencies = [ "windows-link", ] +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + [[package]] name = "clap" version = "4.5.60" @@ -236,6 +275,73 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "criterion" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "is-terminal", + "itertools", + "num-traits", + "once_cell", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_derive", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" +dependencies = [ + "cast", + "itertools", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "difflib" version = "0.4.0" @@ -248,6 +354,12 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + [[package]] name = "encode_unicode" version = "1.0.0" @@ -407,6 +519,7 @@ dependencies = [ "clap", "colored", "console", + "criterion", "predicates", "rmcp", "schemars", @@ -417,6 +530,17 @@ dependencies = [ "toml", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.15.5" @@ -438,6 +562,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -480,12 +610,32 @@ dependencies = [ "serde_core", ] +[[package]] +name = "is-terminal" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.17" @@ -579,6 +729,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + [[package]] name = "parking_lot" version = "0.12.5" @@ -614,6 +770,34 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "plotters" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" + +[[package]] +name = "plotters-svg" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" +dependencies = [ + "plotters-backend", +] + [[package]] name = "predicates" version = "3.1.4" @@ -678,6 +862,26 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rayon" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -767,6 +971,15 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "schemars" version = "0.8.22" @@ -960,6 +1173,16 @@ dependencies = [ "syn", ] +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "tokio" version = "1.50.0" @@ -1106,6 +1329,16 @@ dependencies = [ "libc", ] +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -1209,6 +1442,25 @@ dependencies = [ "semver", ] +[[package]] +name = "web-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -1447,6 +1699,26 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "zerocopy" +version = "0.8.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96e13bc581734df6250836c59a5f44f3c57db9f9acb9dc8e3eaabdaf6170254d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3545ea9e86d12ab9bba9fcd99b54c1556fd3199007def5a03c375623d05fac1c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zmij" version = "1.0.21" diff --git a/Cargo.toml b/Cargo.toml index 7fbf912..c9047f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,9 +22,14 @@ schemars = "0.8" [dev-dependencies] assert_cmd = "2" +criterion = { version = "0.5", features = ["html_reports"] } predicates = "3" tempfile = "3" +[[bench]] +name = "status_bench" +harness = false + # The profile that 'dist' will build with [profile.dist] inherits = "release" diff --git a/benches/status_bench.rs b/benches/status_bench.rs new file mode 100644 index 0000000..9e3ee49 --- /dev/null +++ b/benches/status_bench.rs @@ -0,0 +1,111 @@ +use std::path::{Path, PathBuf}; +use std::process::Command; + +use criterion::{Criterion, criterion_group, criterion_main}; + +struct BenchRepo { + // Hold TempDir so it doesn't get dropped + _dir: tempfile::TempDir, + path: PathBuf, + gw_bin: PathBuf, +} + +impl BenchRepo { + fn new() -> Self { + let dir = tempfile::TempDir::new().unwrap(); + let path = dir.path().to_path_buf(); + + git(&path, &["init"]); + git(&path, &["config", "user.email", "bench@test.com"]); + git(&path, &["config", "user.name", "Bench"]); + + write_and_commit(&path, "README.md", "# bench repo", "initial commit"); + + let gw_bin = assert_cmd::cargo::cargo_bin!("gw").to_path_buf(); + + let repo = Self { + _dir: dir, + path, + gw_bin, + }; + + // Create a stack with 3 branches, each with a couple commits + repo.gw(&["stack", "create", "feat"]); + + write_and_commit(&repo.path, "feat1.txt", "feat 1", "feat: first change"); + write_and_commit(&repo.path, "feat2.txt", "feat 2", "feat: second change"); + + repo.gw(&["branch", "create", "feat-tests"]); + write_and_commit(&repo.path, "test1.txt", "test 1", "test: add tests"); + write_and_commit(&repo.path, "test2.txt", "test 2", "test: more tests"); + + repo.gw(&["branch", "create", "feat-docs"]); + write_and_commit(&repo.path, "docs1.txt", "docs 1", "docs: add docs"); + + // Go back to the middle branch for the benchmark + repo.gw(&["switch", "feat-tests"]); + + repo + } + + fn gw(&self, args: &[&str]) -> String { + let output = Command::new(&self.gw_bin) + .args(args) + .current_dir(&self.path) + .output() + .unwrap(); + assert!( + output.status.success(), + "gw {:?} failed: {}", + args, + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + } + + fn run_status(&self) -> std::process::Output { + Command::new(&self.gw_bin) + .arg("status") + .current_dir(&self.path) + .output() + .unwrap() + } +} + +fn git(path: &Path, args: &[&str]) { + let output = Command::new("git") + .args(args) + .current_dir(path) + .output() + .unwrap(); + assert!( + output.status.success(), + "git {:?} failed: {}", + args, + String::from_utf8_lossy(&output.stderr) + ); +} + +fn write_and_commit(path: &Path, file: &str, content: &str, message: &str) { + std::fs::write(path.join(file), content).unwrap(); + git(path, &["add", file]); + git(path, &["commit", "-m", message]); +} + +fn bench_status(c: &mut Criterion) { + let repo = BenchRepo::new(); + + // Sanity check: status should succeed + let output = repo.run_status(); + assert!(output.status.success(), "status failed during setup"); + + c.bench_function("gw status", |b| { + b.iter(|| { + let output = repo.run_status(); + assert!(output.status.success()); + }); + }); +} + +criterion_group!(benches, bench_status); +criterion_main!(benches); diff --git a/src/commands/completions.rs b/src/commands/completions.rs index 2b432c2..47d3707 100644 --- a/src/commands/completions.rs +++ b/src/commands/completions.rs @@ -37,10 +37,14 @@ _gw() { 'sync:Sync stacks with the base branch' 'push:Push the current branch' 'switch:Switch to a branch tracked by gw' + 'status:Show status of the current branch in its stack' + 'diff:Show diff for the current branch changes' 'log:Show log of all stacks with branches and commits' 'tree:Alias for log' + 'split:Split a branch into a stack of focused branches' 'config:Configure gw settings' 'completions:Generate shell completions' + 'mcp-setup:Set up the MCP server for Claude Code' ) _arguments -C \ @@ -118,13 +122,30 @@ _gw() { switch) _arguments '1:branch:_gw_branches' ;; + status) + ;; + diff) + _arguments \ + '--stat[Show diffstat summary]' \ + '--no-difftastic[Use regular git diff]' + ;; log|tree) _arguments '--pr[Show PR status]' ;; + split) + _arguments \ + '--plan[Plan file]:file:_files' \ + '--base[Base branch]:branch:_gw_branches' \ + '--name[Stack name]:name:' \ + '--yes[Skip confirmation]' \ + '--continue[Continue after resolving conflicts]' \ + '--abort[Abort the split]' + ;; config) local -a config_commands config_commands=( 'set-base:Set the default base branch' + 'set-delete-on-merge:Set whether to delete branches after merge' 'show:Show current configuration' ) _arguments -C \ @@ -135,6 +156,7 @@ _gw() { config_args) case $words[1] in set-base) _arguments '1:branch:_gw_branches' ;; + set-delete-on-merge) _arguments '1:value:(true false)' ;; esac ;; esac @@ -166,10 +188,10 @@ _gw() { local cur prev words cword _init_completion || return - local commands="stack branch adopt rebase sync push switch log tree config completions" + local commands="stack branch adopt rebase sync push switch status diff log tree split config completions mcp-setup" local stack_commands="create delete list" local branch_commands="create remove" - local config_commands="set-base show" + local config_commands="set-base set-delete-on-merge show" if [[ $cword -eq 1 ]]; then COMPREPLY=($(compgen -W "$commands" -- "$cur")) @@ -227,14 +249,31 @@ _gw() { switch) COMPREPLY=($(compgen -W "$(_gw_branches)" -- "$cur")) ;; - tree) + diff) + COMPREPLY=($(compgen -W "--stat --no-difftastic" -- "$cur")) + ;; + log|tree) COMPREPLY=($(compgen -W "--pr" -- "$cur")) ;; + split) + if [[ "$prev" == "--plan" ]]; then + COMPREPLY=($(compgen -f -- "$cur")) + elif [[ "$prev" == "--base" ]]; then + COMPREPLY=($(compgen -W "$(_gw_branches)" -- "$cur")) + elif [[ "$prev" == "--name" ]]; then + : + else + COMPREPLY=($(compgen -W "--plan --base --name --yes --continue --abort" -- "$cur")) + fi + ;; config) if [[ $cword -eq 2 ]]; then COMPREPLY=($(compgen -W "$config_commands" -- "$cur")) - elif [[ "${words[2]}" == "set-base" ]]; then - COMPREPLY=($(compgen -W "$(_gw_branches)" -- "$cur")) + elif [[ $cword -ge 3 ]]; then + case "${words[2]}" in + set-base) COMPREPLY=($(compgen -W "$(_gw_branches)" -- "$cur")) ;; + set-delete-on-merge) COMPREPLY=($(compgen -W "true false" -- "$cur")) ;; + esac fi ;; completions) @@ -280,10 +319,14 @@ complete -c gw -f -n __gw_needs_command -a rebase -d 'Propagate rebases' complete -c gw -f -n __gw_needs_command -a sync -d 'Sync with base branch' complete -c gw -f -n __gw_needs_command -a push -d 'Push current branch' complete -c gw -f -n __gw_needs_command -a switch -d 'Switch branches' +complete -c gw -f -n __gw_needs_command -a status -d 'Show status of current branch' +complete -c gw -f -n __gw_needs_command -a diff -d 'Show diff for current branch' complete -c gw -f -n __gw_needs_command -a log -d 'Show stacks' complete -c gw -f -n __gw_needs_command -a tree -d 'Alias for log' +complete -c gw -f -n __gw_needs_command -a split -d 'Split branch into a stack' complete -c gw -f -n __gw_needs_command -a config -d 'Configure settings' complete -c gw -f -n __gw_needs_command -a completions -d 'Generate completions' +complete -c gw -f -n __gw_needs_command -a mcp-setup -d 'Set up MCP server for Claude Code' # stack subcommands complete -c gw -f -n '__gw_using_command stack' -a create -d 'Create a new stack' @@ -318,14 +361,28 @@ complete -c gw -f -n '__gw_using_command push' -l yes -d 'Skip confirmation' # switch complete -c gw -f -n '__gw_using_command switch' -a '(__gw_branches)' +# diff +complete -c gw -f -n '__gw_using_command diff' -l stat -d 'Show diffstat summary' +complete -c gw -f -n '__gw_using_command diff' -l no-difftastic -d 'Use regular git diff' + # tree complete -c gw -f -n '__gw_using_command log' -l pr -d 'Show PR status' complete -c gw -f -n '__gw_using_command tree' -l pr -d 'Show PR status' +# split +complete -c gw -f -n '__gw_using_command split' -l plan -d 'Plan file' -rF +complete -c gw -f -n '__gw_using_command split' -l base -d 'Base branch' -ra '(__gw_branches)' +complete -c gw -f -n '__gw_using_command split' -l name -d 'Stack name' +complete -c gw -f -n '__gw_using_command split' -l yes -d 'Skip confirmation' +complete -c gw -f -n '__gw_using_command split' -l continue -d 'Continue after conflicts' +complete -c gw -f -n '__gw_using_command split' -l abort -d 'Abort the split' + # config complete -c gw -f -n '__gw_using_command config' -a set-base -d 'Set default base branch' +complete -c gw -f -n '__gw_using_command config' -a set-delete-on-merge -d 'Set delete on merge' complete -c gw -f -n '__gw_using_command config' -a show -d 'Show configuration' complete -c gw -f -n '__gw_using_subcommand config set-base' -a '(__gw_branches)' +complete -c gw -f -n '__gw_using_subcommand config set-delete-on-merge' -a 'true false' # completions complete -c gw -f -n '__gw_using_command completions' -a 'zsh bash fish' diff --git a/src/commands/status.rs b/src/commands/status.rs index b0ab533..610b6fb 100644 --- a/src/commands/status.rs +++ b/src/commands/status.rs @@ -2,6 +2,7 @@ use anyhow::{bail, Result}; use colored::Colorize; use crate::context::Ctx; +use crate::git::Git; pub fn run(ctx: &Ctx) -> Result<()> { let current = ctx.git.current_branch()?; @@ -27,22 +28,42 @@ pub fn run(ctx: &Ctx) -> Result<()> { let is_root = idx == 0; let is_leaf = idx == total - 1; - // Gather git info - let merge_base = ctx.git.merge_base(&parent, ¤t)?; - let commits = ctx.git.log_oneline(&merge_base, "HEAD", 100)?; - let behind_parent: usize = ctx - .git - .run(&["rev-list", "--count", &format!("{merge_base}..{parent}")]) + // Spawn all git subprocesses at once for maximum parallelism. + // status --porcelain dominates (~350ms in large repos); everything else + // runs concurrently while we wait for it. + let wt_child = ctx.git.spawn(&["status", "--porcelain"])?; + let remote_child = ctx.git.spawn(&[ + "for-each-ref", + &format!("--format=%(upstream:short)\t%(upstream:track)"), + &format!("refs/heads/{current}"), + ])?; + let mb_child = ctx.git.spawn(&["merge-base", &parent, ¤t])?; + + // Collect merge-base first (~22ms), then spawn log + rev-list + let merge_base = Git::collect(mb_child)?; + let log_child = ctx.git.spawn(&[ + "log", + "--reverse", + "--oneline", + "--format=%h %s", + "--max-count=100", + &format!("{merge_base}..HEAD"), + ])?; + let behind_child = ctx.git.spawn(&[ + "rev-list", + "--count", + &format!("{merge_base}..{parent}"), + ])?; + + // Collect remaining results (status --porcelain is still running) + let commits = parse_log_output(&Git::collect(log_child)?); + let behind_parent: usize = Git::collect(behind_child) .ok() .and_then(|s| s.trim().parse().ok()) .unwrap_or(0); let needs_rebase = behind_parent > 0; - - // Remote status - let remote_status = remote_info(ctx, ¤t); - - // Working tree - let wt = working_tree_info(ctx); + let remote_status = parse_remote_output(Git::collect(remote_child).ok()); + let wt = parse_wt_output(Git::collect(wt_child).ok()); // === Render === @@ -171,12 +192,10 @@ enum WorkingTree { }, } -fn working_tree_info(ctx: &Ctx) -> WorkingTree { - let output = ctx.git.run(&["status", "--porcelain"]); +fn parse_wt_output(output: Option) -> WorkingTree { let output = match output { - Ok(o) if o.is_empty() => return WorkingTree::Clean, - Ok(o) => o, - Err(_) => return WorkingTree::Clean, + Some(o) if !o.is_empty() => o, + _ => return WorkingTree::Clean, }; let mut staged = 0usize; @@ -217,16 +236,10 @@ enum RemoteStatus { NoRemote, } -fn remote_info(ctx: &Ctx, branch: &str) -> RemoteStatus { - let output = ctx.git.run(&[ - "for-each-ref", - &format!("--format=%(upstream:short)\t%(upstream:track)"), - &format!("refs/heads/{branch}"), - ]); - +fn parse_remote_output(output: Option) -> RemoteStatus { let output = match output { - Ok(o) => o, - Err(_) => return RemoteStatus::NoRemote, + Some(o) => o, + None => return RemoteStatus::NoRemote, }; let parts: Vec<&str> = output.split('\t').collect(); @@ -264,6 +277,19 @@ fn remote_info(ctx: &Ctx, branch: &str) -> RemoteStatus { RemoteStatus::UpToDate } +fn parse_log_output(output: &str) -> Vec<(String, String)> { + if output.is_empty() { + return vec![]; + } + output + .lines() + .map(|line| { + let (sha, subject) = line.split_once(' ').unwrap_or((line, "")); + (sha.to_string(), subject.to_string()) + }) + .collect() +} + fn parse_count_after(s: &str, prefix: &str) -> usize { s.split(prefix) .nth(1) diff --git a/src/git.rs b/src/git.rs index 0df0a36..950cd26 100644 --- a/src/git.rs +++ b/src/git.rs @@ -87,6 +87,36 @@ impl Git { Ok(stdout.trim().to_string()) } + /// Spawn a git command without waiting for it to finish. + /// Call `collect()` on the returned `Child` to get the result. + pub fn spawn(&self, args: &[&str]) -> Result { + Command::new("git") + .args(args) + .current_dir(&self.repo_path) + .env_remove("GIT_DIR") + .env_remove("GIT_WORK_TREE") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .with_context(|| format!("failed to spawn git {}", args.first().unwrap_or(&""))) + } + + /// Collect the output of a spawned git command. + pub fn collect(child: std::process::Child) -> Result { + let output = child + .wait_with_output() + .context("failed to wait for git process")?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(anyhow!("git command failed: {}", stderr.trim())); + } + + let stdout = + String::from_utf8(output.stdout).context("git output was not valid UTF-8")?; + Ok(stdout.trim().to_string()) + } + /// Run a git command and return the raw output, regardless of exit code. fn run_raw(&self, args: &[&str]) -> Result { Command::new("git")