From 7666bfbe712a597a5205b11ba503f30c03d3d8ee Mon Sep 17 00:00:00 2001 From: bircni Date: Sun, 18 Oct 2026 14:46:03 +0200 Subject: [PATCH 1/5] chore(deps)!: update dependencies and require the latest stable Rust - comfy-table 8.0.1, insta 1.49 and a lockfile refresh - rust-version = "1.99", so the toolchain requirement is enforced instead of only stated in the README - strum's `derive` feature instead of a separate strum_macros dependency --- Cargo.lock | 139 +++++++++++++++++++++--------------------- Cargo.toml | 8 +-- src/gitinfo/status.rs | 2 +- 3 files changed, 74 insertions(+), 75 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ed225c8..4e1ca31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -60,15 +60,15 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "bitflags" -version = "2.13.1" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "cc" -version = "1.4.4" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" dependencies = [ "find-msvc-tools", "jobserver", @@ -78,15 +78,15 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "clap" -version = "4.6.6" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", "clap_derive", @@ -94,9 +94,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.6" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ "anstream", "anstyle", @@ -106,30 +106,30 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.6.9" +version = "4.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be2ad0423bdbbb0e25bc89add796f3559706d4a95e1bc98e4d9662a957b6a19" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" dependencies = [ "clap", ] [[package]] name = "clap_derive" -version = "4.6.4" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] name = "clap_lex" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" [[package]] name = "colorchoice" @@ -139,9 +139,9 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" [[package]] name = "comfy-table" -version = "8.0.0" +version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "136c8c4c3823846e8ba6d4bda011b4e5d5827b8bb0ac26c31f9ab31abe9f54f2" +checksum = "b96a46ad395a5e00676eddaca4a45ed78b29c08be5a878d35e4b071c625637dd" dependencies = [ "crossterm", "unicode-segmentation", @@ -150,9 +150,9 @@ dependencies = [ [[package]] name = "console" -version = "0.16.4" +version = "0.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fe5f465a4f6fee88fad41b85d990f84c835335e85b5d9e6e63e0d06d28cba7c" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" dependencies = [ "encode_unicode", "libc", @@ -161,9 +161,9 @@ dependencies = [ [[package]] name = "crossbeam-deque" -version = "0.8.7" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -171,18 +171,18 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.20" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.22" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "crossterm" @@ -209,9 +209,9 @@ dependencies = [ [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" [[package]] name = "displaydoc" @@ -221,7 +221,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -235,9 +235,9 @@ dependencies = [ [[package]] name = "either" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "encode_unicode" @@ -263,9 +263,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.11" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" [[package]] name = "form_urlencoded" @@ -303,7 +303,6 @@ dependencies = [ "serde_json", "simplelog", "strum", - "strum_macros", "tempfile", "walkdir", ] @@ -435,9 +434,9 @@ dependencies = [ [[package]] name = "insta" -version = "1.48.0" +version = "1.49.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86f0f8fee8c926415c58d6ae43a08523a26faccb2323f5e6b644fe7dd4ef6b82" +checksum = "b67d3d2e287e4b86c10b3f3b641033d1f89b74bdb39d05f34952e2b9a6fe21cd" dependencies = [ "console", "once_cell", @@ -470,9 +469,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libgit2-sys" @@ -490,9 +489,9 @@ dependencies = [ [[package]] name = "libssh2-sys" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c04141a07bb0c0bc461cb657808764de571702a59bc5c726c400ac9a7625e3ab" +checksum = "0f5eb74291e8691cab524a01274a1b1e7742b1a94f29d8b101d8aadc8372c1cd" dependencies = [ "cc", "libc", @@ -504,9 +503,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.29" +version = "1.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9" +checksum = "f710a23e6dbf193214fd46ca56a9d6864e550abe86202184532ae7275e46de19" dependencies = [ "cc", "libc", @@ -528,9 +527,9 @@ checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "litrs" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" [[package]] name = "lock_api" @@ -561,9 +560,9 @@ checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" [[package]] name = "num_threads" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" dependencies = [ "libc", ] @@ -654,9 +653,9 @@ dependencies = [ [[package]] name = "powerfmt" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "proc-macro2" @@ -713,9 +712,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" dependencies = [ "bitflags", "errno", @@ -766,14 +765,14 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -807,9 +806,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.15.2" +version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" [[package]] name = "stable_deref_trait" @@ -857,9 +856,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.3" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -868,13 +867,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -943,9 +942,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-segmentation" @@ -1064,13 +1063,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "synstructure", ] @@ -1085,13 +1084,13 @@ dependencies = [ [[package]] name = "zerofrom-derive" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "synstructure", ] @@ -1125,7 +1124,7 @@ checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 17beeae..4f0df08 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ repository = "https://github.com/bircni/git-statuses" version = "0.8.2" authors = ["bircni"] edition = "2024" +rust-version = "1.99" license = "MIT" readme = "README.md" keywords = ["git", "status", "repository", "plugin", "cli"] @@ -14,19 +15,18 @@ exclude = ["src/tests/*", "tests/*"] anyhow = "1" clap = { version = "4.6", features = ["derive"] } clap_complete = "4.6" -comfy-table = "8.0.0" +comfy-table = "8.0.1" git2 = { version = "0.21", default-features = false, features = ["https", "ssh", "vendored-openssl"] } log = "0.4.34" rayon = "1.12.0" serde = { version = "1.0", features = ["derive"]} serde_json = "1.0" simplelog = "0.12.2" -strum = { version = "0.28", features = ["strum_macros"] } -strum_macros = "0.28" +strum = { version = "0.28", features = ["derive"] } walkdir = "2.5" [dev-dependencies] -insta = { version = "1.48", features = ["json"] } +insta = { version = "1.49", features = ["json"] } tempfile = "3.27" diff --git a/src/gitinfo/status.rs b/src/gitinfo/status.rs index b6bb116..aab00d4 100644 --- a/src/gitinfo/status.rs +++ b/src/gitinfo/status.rs @@ -2,7 +2,7 @@ use std::fmt::{self, Display, Formatter}; use comfy_table::Cell; use git2::{Repository, RepositoryState}; -use strum_macros::EnumIter; +use strum::EnumIter; use crate::gitinfo; From 04572793f694fc3efc95f9b2eae7f320648eb055 Mon Sep 17 00:00:00 2001 From: bircni Date: Sun, 18 Oct 2026 14:46:14 +0200 Subject: [PATCH 2/5] fix!: correct several reported values and make the test suite hermetic Fixes: - scan: with --subdir, a checkout that cannot be opened is reported under the project's name rather than the subdir's, which was the same for all - scan: a symlinked repository is shown under the link's name instead of its absolute target path, by taking the shown path from the walk - gitinfo: an unborn branch keeps its full name (`feature/x`, not `x`) - gitinfo: a detached HEAD is no longer local-only; the Local column shows `-`, the summary stops counting it and JSON gains `is_detached` - gitinfo: `--fetch` runs git with GIT_TERMINAL_PROMPT=0, so the parallel fetches fail instead of blocking on interleaved credential prompts - cli: failed repositories are listed on stderr in --json mode as well - status: the Detached description no longer claims to cover branches without an upstream, which are Unpublished Tests: - fix clippy 1.99's assert_is_empty lint and the macOS temp-path failures - assert on the output of tests that only ran code, replace assertions that could not fail, and drop duplicated tests - no network access, no git CLI for fixtures, and no dependence on the machine's init.defaultBranch - cover --fetch behind counts, --ff on diverged, conflicting and detached repositories, fetching from a worktree, and nested and symlinked repositories --- src/gitinfo/mod.rs | 40 +++- src/gitinfo/repoinfo.rs | 31 ++-- src/gitinfo/status.rs | 6 +- src/main.rs | 4 +- src/scan.rs | 38 +++- src/tests/gitinfo_test.rs | 291 +++++++++++------------------ src/tests/integration_test.rs | 340 +++++++++++++++++++++++----------- src/tests/main_test.rs | 106 +++++++++-- src/tests/printer_test.rs | 67 ++++--- src/tests/smoke_test.rs | 105 ++++------- src/tests/util_test.rs | 96 +--------- tests/cli.rs | 17 +- 12 files changed, 590 insertions(+), 551 deletions(-) diff --git a/src/gitinfo/mod.rs b/src/gitinfo/mod.rs index fca5e59..ddd52f1 100644 --- a/src/gitinfo/mod.rs +++ b/src/gitinfo/mod.rs @@ -1,4 +1,7 @@ -use std::{path, process::Command}; +use std::{ + path::{self, Path}, + process::Command, +}; use git2::{Branch, Repository, StatusOptions}; @@ -114,13 +117,15 @@ pub fn get_branch_name(repo: &Repository) -> String { return "N/A".to_owned(); } if let Ok(Some(target)) = head.symbolic_target() - && let Some(branch) = target.rsplit('/').next() + && let Some(branch) = target.strip_prefix("refs/heads/") { return format!("{branch} (no commits)"); } } else if let Ok(headref) = repo.find_reference("HEAD") && let Ok(Some(sym)) = headref.symbolic_target() - && let Some(branch) = sym.rsplit('/').next() + // Strip the namespace rather than taking the last segment, which would turn + // `feature/x` into `x`. + && let Some(branch) = sym.strip_prefix("refs/heads/") { return format!("{branch} (no commits)"); } @@ -157,7 +162,8 @@ fn upstream_oid(repo: &Repository, branch_name: &str) -> Option { } /// Get the number of commits ahead and behind the upstream branch, and whether the branch is local-only. -/// If the current branch has no upstream, it returns (0, 0, true). +/// If the current branch has no upstream, it returns (0, 0, true). A detached HEAD is not on +/// a branch at all, so it is neither: it returns (0, 0, false). /// # Arguments /// * `repo` - The Git repository to check for ahead/behind status. /// # Returns @@ -168,6 +174,9 @@ pub fn get_ahead_behind_and_local_status(repo: &Repository) -> (usize, usize, bo let Ok(head) = repo.head() else { return LOCAL_ONLY; }; + if !head.is_branch() { + return (0, 0, false); + } let (Ok(branch_name), Some(local_oid)) = (head.shorthand(), head.target()) else { return LOCAL_ONLY; }; @@ -245,11 +254,7 @@ pub fn fetch_remote(repo: &Repository) -> anyhow::Result<()> { .workdir() .or_else(|| repo.path().parent()) .ok_or_else(|| anyhow::anyhow!("No working directory found"))?; - let output = Command::new("git") - .arg("fetch") - .arg(&remote_name) - .current_dir(path) - .output()?; + let output = fetch_command(&remote_name, path).output()?; if !output.status.success() { anyhow::bail!( @@ -262,6 +267,23 @@ pub fn fetch_remote(repo: &Repository) -> anyhow::Result<()> { Ok(()) } +/// Builds the `git fetch` invocation for `remote_name`, run in `dir`. +/// +/// `--fetch` runs one of these per repository in parallel. Git asks for credentials on the +/// terminal rather than on stdin, so concurrent prompts interleave and block the scan. +/// `GIT_TERMINAL_PROMPT=0` makes a repository that needs one fail instead, which is reported +/// as a fetch warning. Credential helpers and the SSH agent still apply; a passphrase prompt +/// from `ssh` itself is outside git's control. +pub fn fetch_command(remote_name: &str, dir: &Path) -> Command { + let mut command = Command::new("git"); + command + .arg("fetch") + .arg(remote_name) + .current_dir(dir) + .env("GIT_TERMINAL_PROMPT", "0"); + command +} + /// Executes a fast-forward merge to update local checkout pub fn merge_ff(repo: &Repository) -> anyhow::Result { let head = repo.head()?; diff --git a/src/gitinfo/repoinfo.rs b/src/gitinfo/repoinfo.rs index 0d53df5..17d0baa 100644 --- a/src/gitinfo/repoinfo.rs +++ b/src/gitinfo/repoinfo.rs @@ -1,11 +1,10 @@ -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use git2::Repository; use crate::{ cli::Args, gitinfo::{self, status::Status}, - util::GitPathExt as _, }; /// Holds information about a Git repository for status display. @@ -43,6 +42,8 @@ pub struct RepoInfo { pub repo_path: String, /// True if this is a Git worktree pub is_worktree: bool, + /// True if HEAD is detached, i.e. not on any branch + pub is_detached: bool, } impl RepoInfo { @@ -51,7 +52,7 @@ impl RepoInfo { /// * `repo` - The Git repository to gather information from. /// * `name` - Fallback name, used when the repository has no remote to derive one from. /// * `args` - CLI arguments; `--remote`, `--fetch` and `--ff` are read from here. - /// * `root` - The already-canonicalized scan root, used to build the relative path. + /// * `repo_path` - The path to show for the repository, relative to the scan root. /// /// # Returns /// A `RepoInfo` instance containing the repository's status information. @@ -65,7 +66,7 @@ impl RepoInfo { repo: &mut Repository, name: &str, args: &Args, - root: &Path, + repo_path: &str, ) -> anyhow::Result { let name = gitinfo::get_repo_name(repo).unwrap_or_else(|| name.to_owned()); @@ -95,18 +96,8 @@ impl RepoInfo { }; let path = gitinfo::get_repo_path(repo); let stash_count = gitinfo::get_stash_count(repo); - let repo_path = path.canonicalize().unwrap_or_else(|_| path.clone()); - let repo_path_relative = repo_path.strip_prefix(root).unwrap_or(&repo_path); - // The scanned directory is the repository itself when git-statuses is run from - // inside one, which leaves the relative path empty. Fall back to the directory - // name, so the column reads like it would for a repository one level down instead - // of suddenly showing an absolute path. - let repo_path = if repo_path_relative.as_os_str().is_empty() { - repo_path.dir_name() - } else { - repo_path_relative.display().to_string() - }; let is_worktree = repo.is_worktree(); + let is_detached = repo.head_detached().unwrap_or(false); Ok(Self { name, @@ -121,16 +112,20 @@ impl RepoInfo { stash_count, is_local_only, fast_forwarded, - repo_path, + repo_path: repo_path.to_owned(), is_worktree, + is_detached, }) } /// Formats the local status showing ahead/behind counts or local-only indication. /// # Returns - /// A formatted string showing ahead/behind counts or local-only indication. + /// A formatted string showing ahead/behind counts or local-only indication, or `-` for + /// a detached HEAD, which has no branch to compare. pub fn format_local_status(&self) -> String { - if self.is_local_only { + if self.is_detached { + "-".to_owned() + } else if self.is_local_only { "local-only".to_owned() } else { format!("↑{} ↓{}", self.ahead, self.behind) diff --git a/src/gitinfo/status.rs b/src/gitinfo/status.rs index aab00d4..30a048e 100644 --- a/src/gitinfo/status.rs +++ b/src/gitinfo/status.rs @@ -27,7 +27,7 @@ pub enum Status { Unpushed, /// The branch is not published. Unpublished, - /// The repository is in a detached HEAD state or has no upstream branch. + /// The repository is in a detached HEAD state. Detached, /// The status of the repository is unknown or not recognized. #[default] @@ -124,9 +124,7 @@ impl Status { pub const fn description(&self) -> &str { match self { Self::Clean => "No changes, no unpushed commits.", - Self::Detached => { - "The repository is in a detached HEAD state or has no upstream branch." - } + Self::Detached => "The repository is in a detached HEAD state.", Self::Dirty(_) => "Working directory has changes.", Self::Merge => "Merge in progress.", Self::Revert => "Revert in progress.", diff --git a/src/main.rs b/src/main.rs index ce6338b..72996d7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -75,13 +75,15 @@ fn run(args: &Args, out: &mut impl Write) -> Outcome { failed: failed_repos.len(), }; + // Goes to stderr, so it is reported in every output mode without touching the report. + printer::failed_summary(&failed_repos); + if args.json { printer::json_output(&displayed, &failed_repos, out); return outcome; } printer::repositories_table(&displayed, args, out); - printer::failed_summary(&failed_repos); if args.summary { // The summary describes the whole scan, not just the filtered selection. printer::summary(&repos, failed_repos.len(), out); diff --git a/src/scan.rs b/src/scan.rs index cd6d97a..4797204 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -43,13 +43,9 @@ pub fn find_repositories(args: &Args) -> (Vec, Vec) { .collect::>() }; - // The scan root never changes, so resolve it once here instead of once per - // repository inside `RepoInfo::new`. - let root = args.dir.canonicalize().unwrap_or_else(|_| args.dir.clone()); - let scanned = walker .par_iter() - .filter_map(|entry| scan_entry(args, entry.path(), &root)) + .filter_map(|entry| scan_entry(args, entry.path())) .collect::>(); let mut repos = Vec::with_capacity(scanned.len()); @@ -71,7 +67,7 @@ pub fn find_repositories(args: &Args) -> (Vec, Vec) { /// # Returns /// `None` if the directory is not a repository the user asked about, `Err` with the /// directory name if it is one but could not be read, and `Ok` otherwise. -fn scan_entry(args: &Args, orig_path: &Path, root: &Path) -> Option> { +fn scan_entry(args: &Args, orig_path: &Path) -> Option> { let path_buf = if orig_path.is_git_directory() { orig_path.to_path_buf() } else { @@ -83,7 +79,13 @@ fn scan_entry(args: &Args, orig_path: &Path, root: &Path) -> Option Some( - RepoInfo::new(&mut git_repo, &orig_path.dir_name(), args, root).map_err(|e| { + RepoInfo::new( + &mut git_repo, + &orig_path.dir_name(), + args, + &display_path(&path_buf, &args.dir), + ) + .map_err(|e| { let name = orig_path.dir_name(); log::debug!("Failed to read repository `{name}`: {e}"); name @@ -91,7 +93,27 @@ fn scan_entry(args: &Args, orig_path: &Path, root: &Path) -> Option { log::debug!("Failed to open repository at {}: {e}", path_buf.display()); - Some(Err(path_buf.dir_name())) + // Name it after the scanned directory, as a read failure is: with `--subdir` + // the opened path ends in the subdir, which is the same for every project. + Some(Err(orig_path.dir_name())) } } } + +/// The path shown for a repository found at `location` during a scan of `root`. +/// +/// Taken from where the walk found it rather than from the repository's working directory, +/// which git resolves through symlinks: a linked repository would otherwise be shown under +/// its absolute target path instead of the name it has in the scanned directory. +fn display_path(location: &Path, root: &Path) -> String { + match location.strip_prefix(root) { + Ok(relative) if !relative.as_os_str().is_empty() => relative.display().to_string(), + // The scanned directory is the repository itself when git-statuses is run from + // inside one. Show its name, so the column reads like it would for a repository + // one level down instead of being empty. + _ => location + .canonicalize() + .unwrap_or_else(|_| location.to_path_buf()) + .dir_name(), + } +} diff --git a/src/tests/gitinfo_test.rs b/src/tests/gitinfo_test.rs index 816a084..a3e9741 100644 --- a/src/tests/gitinfo_test.rs +++ b/src/tests/gitinfo_test.rs @@ -1,7 +1,4 @@ -use std::{ - fs, - path::{Path, PathBuf}, -}; +use std::{fs, path::Path}; use comfy_table::Color; use git2::Repository; @@ -28,7 +25,19 @@ fn changed_count(repo: &Repository) -> usize { fn test_get_branch_name_empty() { let (_tmp, repo) = init_temp_repo(); let branch = gitinfo::get_branch_name(&repo); - assert!(branch.contains("no commits") || branch.contains("no branch") || !branch.is_empty()); + assert!( + branch.ends_with(" (no commits)"), + "an unborn branch must say it has no commits, got {branch:?}" + ); +} + +/// An unborn branch keeps its whole name. Taking the last `/` segment of the ref showed +/// `feature/x` as `x`. +#[test] +fn test_get_branch_name_unborn_branch_with_slash() { + let (_tmp, repo) = init_temp_repo(); + repo.set_head("refs/heads/feature/x").unwrap(); + assert_eq!(gitinfo::get_branch_name(&repo), "feature/x (no commits)"); } #[test] @@ -65,20 +74,6 @@ fn test_get_ahead_behind_no_upstream() { assert_eq!((ahead, behind, is_local_only), (0, 0, true)); } -#[test] -fn test_get_remote_url_none() { - let (_tmp, repo) = init_temp_repo(); - let remote = gitinfo::get_remote_url(&repo); - assert!(remote.is_none()); -} - -#[test] -fn test_get_repo_status_invalid_repo() { - let tmp = tempfile::tempdir().unwrap(); - let repo = Repository::open(tmp.path()); - assert!(repo.is_err()); -} - #[test] fn test_get_branch_name_detached_head() { let (tmp, repo) = init_temp_repo(); @@ -96,7 +91,7 @@ fn test_get_branch_name_detached_head() { // Checkout detached HEAD repo.set_head_detached(commit_oid).unwrap(); let branch = gitinfo::get_branch_name(&repo); - assert!(!branch.is_empty()); + assert_eq!(branch, "N/A", "a detached HEAD has no branch name"); } #[test] @@ -128,26 +123,24 @@ fn test_get_total_commits_multiple() { #[test] fn test_repo_info_new_with_and_without_remote() { - let (_, mut repo) = init_temp_repo(); - // Without remote - let info = RepoInfo::new( - &mut repo, - "tmp", - &Args::default(), - &PathBuf::from("/path/to/repo"), + let (_tmp, mut repo) = init_temp_repo(); + repo.remote("origin", "https://github.com/user/repo.git") + .unwrap(); + let info = RepoInfo::new(&mut repo, "tmp", &Args::default(), "tmp").unwrap(); + assert_eq!( + info.remote_url, None, + "the URL is only looked up with --remote" ); - info.unwrap(); - // With remote (origin does not exist) - let info_remote = RepoInfo::new( - &mut repo, - "tmp", - &Args { - remote: true, - ..Default::default() - }, - &PathBuf::from("/path/to/repo"), + + let args = Args { + remote: true, + ..Default::default() + }; + let info = RepoInfo::new(&mut repo, "tmp", &args, "tmp").unwrap(); + assert_eq!( + info.remote_url.as_deref(), + Some("https://github.com/user/repo.git") ); - info_remote.unwrap(); } #[test] @@ -170,9 +163,10 @@ fn test_get_ahead_behind_error_cases() { #[test] fn test_fetch_remote_failure() { - let (_tmp, repo) = init_temp_repo(); - // Simulate a fetch failure by pointing to a non-existent remote - repo.remote("origin", "https://invalid-url").unwrap(); + let (tmp, repo) = init_temp_repo(); + // A local path that does not exist fails without touching the network. + let missing = tmp.path().join("missing-remote"); + repo.remote("origin", missing.to_str().unwrap()).unwrap(); let result = gitinfo::fetch_remote(&repo); assert!(result.is_err()); } @@ -197,6 +191,9 @@ fn test_status_display_variants() { assert_eq!(Status::Bisect.to_string(), "Bisect"); assert_eq!(Status::CherryPick.to_string(), "Cherry Pick"); assert_eq!(Status::Unknown.to_string(), "Unknown"); + assert_eq!(Status::Unpublished.to_string(), "Unpublished"); + assert_eq!(Status::Unpushed.to_string(), "Unpushed"); + assert_eq!(Status::Detached.to_string(), "Detached"); } #[test] @@ -216,6 +213,16 @@ fn test_status_colors() { b: 0 } ); + assert_eq!(Status::Unpublished.comfy_color(), Color::Red); + assert_eq!(Status::Unpushed.comfy_color(), Color::Red); + assert_eq!( + Status::Detached.comfy_color(), + Color::Rgb { + r: 255, + g: 0, + b: 255 + } + ); } #[test] @@ -237,6 +244,18 @@ fn test_status_descriptions() { Status::Unknown.description(), "Status is unknown or not recognized." ); + assert_eq!( + Status::Unpublished.description(), + "The branch is not published." + ); + assert_eq!( + Status::Unpushed.description(), + "There are unpushed commits." + ); + assert_eq!( + Status::Detached.description(), + "The repository is in a detached HEAD state." + ); } #[test] @@ -256,43 +275,13 @@ fn test_get_stash_count_empty() { #[test] fn test_repo_info_includes_stash_and_local_status() { let (_tmp, mut repo) = init_temp_repo(); - let info = RepoInfo::new( - &mut repo, - "test", - &Args::default(), - &PathBuf::from("/path/to/repo"), - ) - .unwrap(); + let info = RepoInfo::new(&mut repo, "test", &Args::default(), "repo").unwrap(); assert_eq!(info.stash_count, 0); assert!(info.is_local_only); } // New tests for additional git states and edge cases -#[test] -fn test_status_new_with_merge_state() { - let (tmp, repo) = init_temp_repo(); - - // Create initial commit - let path = tmp.path().join("file.txt"); - fs::write(&path, "initial content").unwrap(); - let mut index = repo.index().unwrap(); - index.add_path(Path::new("file.txt")).unwrap(); - index.write().unwrap(); - let oid = index.write_tree().unwrap(); - let sig = repo.signature().unwrap(); - let tree = repo.find_tree(oid).unwrap(); - repo.commit(Some("HEAD"), &sig, &sig, "initial", &tree, &[]) - .unwrap(); - - // Simulate merge state by creating MERGE_HEAD file directly - let merge_head_path = tmp.path().join(".git/MERGE_HEAD"); - fs::write(&merge_head_path, "1234567890abcdef1234567890abcdef12345678").unwrap(); - - let status = Status::new(&repo); - assert_eq!(status, Status::Merge); -} - #[test] fn test_get_changed_count_multiple_types() { let (tmp, repo) = init_temp_repo(); @@ -320,28 +309,8 @@ fn test_get_changed_count_multiple_types() { index.add_path(Path::new("file3.txt")).unwrap(); index.write().unwrap(); - let changed_count = changed_count(&repo); - assert!(changed_count >= 3); // At least the three changes we made -} - -#[test] -fn test_get_branch_push_status_unpublished() { - let (tmp, repo) = init_temp_repo(); - - // Create a commit on local branch - let path = tmp.path().join("file.txt"); - fs::write(&path, "content").unwrap(); - let mut index = repo.index().unwrap(); - index.add_path(Path::new("file.txt")).unwrap(); - index.write().unwrap(); - let oid = index.write_tree().unwrap(); - let sig = repo.signature().unwrap(); - let tree = repo.find_tree(oid).unwrap(); - repo.commit(Some("HEAD"), &sig, &sig, "commit", &tree, &[]) - .unwrap(); - - let status = gitinfo::get_branch_push_status(&repo); - assert_eq!(status, Status::Unpublished); + // One untracked, one modified and one staged file. + assert_eq!(changed_count(&repo), 3); } #[test] @@ -400,76 +369,6 @@ fn test_multiple_stashes() { assert_eq!(stash_count, 2); } -#[test] -fn test_status_new_additional_variants() { - // Test additional status variants that might not be covered - assert_eq!(Status::Unpublished.to_string(), "Unpublished"); - assert_eq!(Status::Unpushed.to_string(), "Unpushed"); - assert_eq!(Status::Detached.to_string(), "Detached"); -} - -#[test] -fn test_status_additional_colors() { - assert_eq!(Status::Unpublished.comfy_color(), Color::Red); - assert_eq!(Status::Unpushed.comfy_color(), Color::Red); - assert_eq!( - Status::Detached.comfy_color(), - Color::Rgb { - r: 255, - g: 0, - b: 255 - } - ); -} - -#[test] -fn test_status_additional_descriptions() { - assert_eq!( - Status::Unpublished.description(), - "The branch is not published." - ); - assert_eq!( - Status::Unpushed.description(), - "There are unpushed commits." - ); - assert_eq!( - Status::Detached.description(), - "The repository is in a detached HEAD state or has no upstream branch." - ); -} - -#[test] -fn test_get_repo_name_from_url() { - // Test the get_repo_name function indirectly through RepoInfo - let (_, mut repo) = init_temp_repo(); - - // Just test with the fallback name since adding remotes can be tricky - let info = RepoInfo::new( - &mut repo, - "fallback-name", - &Args::default(), - &PathBuf::from("/path/to/repo"), - ) - .unwrap(); - assert_eq!(info.name, "fallback-name"); // Should use the provided name -} - -#[test] -fn test_get_repo_path_functionality() { - let (tmp, repo) = init_temp_repo(); - - // Test that the repo path is correctly identified - let repo_path = repo.path(); - assert!(repo_path.ends_with(".git")); - - // When we get the working directory, it should be the parent - let workdir = repo.workdir().unwrap(); - // Canonicalize both paths to handle macOS symlinks (/var vs /private/var) - let workdir_canonical = workdir.canonicalize().unwrap(); - let tmp_canonical = tmp.path().canonicalize().unwrap(); - assert_eq!(workdir_canonical, tmp_canonical); -} - #[test] fn test_get_remote_url_with_origin() { let (_tmp, repo) = init_temp_repo(); @@ -601,13 +500,7 @@ fn test_repo_info_name_from_scp_style_remote() { repo.remote("origin", "git@github.com:bircni/git-statuses.git") .unwrap(); - let info = RepoInfo::new( - &mut repo, - "fallback-name", - &Args::default(), - &PathBuf::from("/path/to/repo"), - ) - .unwrap(); + let info = RepoInfo::new(&mut repo, "fallback-name", &Args::default(), "repo").unwrap(); assert_eq!(info.name, "git-statuses"); } @@ -619,13 +512,7 @@ fn test_repo_info_name_falls_back_to_directory_name() { let (_tmp, mut repo) = init_temp_repo(); repo.remote("origin", "/").unwrap(); - let info = RepoInfo::new( - &mut repo, - "fallback-name", - &Args::default(), - &PathBuf::from("/path/to/repo"), - ) - .unwrap(); + let info = RepoInfo::new(&mut repo, "fallback-name", &Args::default(), "repo").unwrap(); assert_eq!(info.name, "fallback-name"); } @@ -683,7 +570,8 @@ fn test_status_and_changed_count_agree() { // A committed working directory has no changes at all. assert_eq!(changed_count(&repo), 0); - assert_ne!(Status::new(&repo), Status::Dirty(0)); + // `Dirty(0)` is never constructed, so compare against what a clean, untracked branch is. + assert_eq!(Status::new(&repo), Status::Unpublished); // Each new kind of change must move both the status and the count in lockstep. fs::write(tmp.path().join("untracked.txt"), "new").unwrap(); @@ -718,9 +606,9 @@ fn test_ignored_files_do_not_make_a_repository_dirty() { fs::write(tmp.path().join("ignored.txt"), "please ignore me").unwrap(); assert_eq!(changed_count(&repo), 0); - assert_ne!( + assert_eq!( Status::new(&repo), - Status::Dirty(0), + Status::Unpublished, "an ignored file is not a change" ); } @@ -824,7 +712,7 @@ fn test_get_repo_path_for_bare_repository() { &mut Repository::open(&bare_path).unwrap(), "bare", &Args::default(), - tmp.path(), + "bare.git", ) .unwrap(); @@ -834,7 +722,6 @@ fn test_get_repo_path_for_bare_repository() { info.path.canonicalize().unwrap(), bare_path.canonicalize().unwrap() ); - assert_eq!(info.repo_path, "bare.git"); } /// A bare repository does not have to be named `.git`. Its git directory then has no @@ -846,13 +733,12 @@ fn test_get_repo_path_for_bare_repository_without_git_suffix() { Repository::init_bare(&bare_path).unwrap(); let mut repo = Repository::open(&bare_path).unwrap(); - let info = RepoInfo::new(&mut repo, "plain-bare", &Args::default(), tmp.path()).unwrap(); + let info = RepoInfo::new(&mut repo, "plain-bare", &Args::default(), "plain-bare").unwrap(); assert_eq!( info.path.canonicalize().unwrap(), bare_path.canonicalize().unwrap() ); - assert_eq!(info.repo_path, "plain-bare"); } /// A repository without a working directory falls back to its git directory, with the @@ -866,7 +752,7 @@ fn test_repo_path_of_a_bare_handle_strips_the_git_component() { // Opening the `.git` directory bare gives a handle with no working directory. let mut bare = Repository::open_bare(tmp.path().join(".git")).unwrap(); - let info = RepoInfo::new(&mut bare, "bare-handle", &Args::default(), tmp.path()).unwrap(); + let info = RepoInfo::new(&mut bare, "bare-handle", &Args::default(), "bare-handle").unwrap(); let expected = tmp.path().canonicalize().unwrap(); assert_eq!( @@ -1026,3 +912,36 @@ fn test_branch_tracking_a_differently_named_upstream() { "being ahead of its upstream makes it unpushed, not unpublished" ); } + +/// A detached HEAD is not on a branch, so it is neither local-only nor measured against an +/// upstream. It used to show `local-only` and count towards the summary's local-only branches. +#[test] +fn test_detached_head_is_not_local_only() { + let (tmp, repo) = init_temp_repo(); + commit_initial(&tmp, &repo); + let head = repo.head().unwrap().target().unwrap(); + repo.set_head_detached(head).unwrap(); + + assert_eq!( + gitinfo::get_ahead_behind_and_local_status(&repo), + (0, 0, false) + ); + + let mut repo = Repository::open(tmp.path()).unwrap(); + let info = RepoInfo::new(&mut repo, "detached", &Args::default(), "detached").unwrap(); + assert!(info.is_detached); + assert!(!info.is_local_only); + assert_eq!(info.format_local_status(), "-"); +} + +/// `--fetch` runs one `git fetch` per repository in parallel, so git must never stop to ask +/// for credentials on the terminal. +#[test] +fn test_fetch_command_never_prompts_on_the_terminal() { + let command = gitinfo::fetch_command("origin", Path::new(".")); + let prompt = command + .get_envs() + .find(|(key, _)| *key == "GIT_TERMINAL_PROMPT") + .and_then(|(_, value)| value); + assert_eq!(prompt, Some(std::ffi::OsStr::new("0"))); +} diff --git a/src/tests/integration_test.rs b/src/tests/integration_test.rs index e71bf28..7b17f96 100644 --- a/src/tests/integration_test.rs +++ b/src/tests/integration_test.rs @@ -57,6 +57,50 @@ fn create_dirty_repo(path: &Path, repo_name: &str) -> Repository { repo } +/// Commits `content` as `file` on top of the repository's current HEAD. +fn commit_file(repo: &Repository, file: &str, content: &str) -> git2::Oid { + fs::write(repo.workdir().unwrap().join(file), content).unwrap(); + let mut index = repo.index().unwrap(); + index.add_path(Path::new(file)).unwrap(); + index.write().unwrap(); + let tree = repo.find_tree(index.write_tree().unwrap()).unwrap(); + let sig = repo.signature().unwrap(); + let parent = repo.head().unwrap().peel_to_commit().unwrap(); + repo.commit(Some("HEAD"), &sig, &sig, "change", &tree, &[&parent]) + .unwrap() +} + +/// Creates a repository standing in for a remote, and a clone of it at `/scan/clone` +/// whose branch tracks the remote's. Scanning `/scan` finds only the clone. +fn remote_and_clone(temp: &Path) -> (Repository, Repository) { + let remote = create_git_repo_with_commit(temp, "remote"); + let clone = Repository::clone( + remote.workdir().unwrap().to_str().unwrap(), + temp.join("scan").join("clone"), + ) + .unwrap(); + let mut config = clone.config().unwrap(); + config.set_str("user.name", "Test User").unwrap(); + config.set_str("user.email", "test@example.com").unwrap(); + drop(config); + (remote, clone) +} + +/// Scans `/scan` the way `remote_and_clone` laid it out. +fn scan_clone(temp: &Path, fetch: bool, fast_forward: bool) -> crate::gitinfo::repoinfo::RepoInfo { + let args = Args { + dir: temp.join("scan"), + depth: 1, + fetch, + fast_forward, + ..Default::default() + }; + let (mut repos, failed) = scan::find_repositories(&args); + assert_eq!(failed, Vec::::new()); + assert_eq!(repos.len(), 1); + repos.remove(0) +} + #[test] fn test_integration_single_clean_repository() { let temp_dir = TempDir::new().unwrap(); @@ -74,7 +118,7 @@ fn test_integration_single_clean_repository() { assert_eq!(failed.len(), 0); assert_eq!(repos[0].name, "test-repo"); assert!(repos[0].commits > 0); - assert!(!repos[0].branch.is_empty()); + assert_ne!(repos[0].branch, ""); } #[test] @@ -108,70 +152,6 @@ fn test_integration_multiple_repositories() { )); } -#[test] -fn test_integration_nested_repositories_with_depth() { - let temp_dir = TempDir::new().unwrap(); - - // Create nested structure: root/level1/level2/repo - let level1_dir = temp_dir.path().join("level1"); - let level2_dir = level1_dir.join("level2"); - fs::create_dir_all(&level2_dir).unwrap(); - - let _repo_root = create_git_repo_with_commit(temp_dir.path(), "root-repo"); - let _repo_level1 = create_git_repo_with_commit(&level1_dir, "level1-repo"); - let _repo_level2 = create_git_repo_with_commit(&level2_dir, "level2-repo"); - - // Test depth 1 - should only find root repo - let args_depth1 = Args { - dir: temp_dir.path().to_path_buf(), - depth: 1, - ..Default::default() - }; - let (repos_depth1, _) = scan::find_repositories(&args_depth1); - assert_eq!(repos_depth1.len(), 1); - assert_eq!(repos_depth1[0].name, "root-repo"); - - // Test depth 3 - should find all repos - let args_depth3 = Args { - dir: temp_dir.path().to_path_buf(), - depth: 3, - ..Default::default() - }; - let (repos_depth3, _) = scan::find_repositories(&args_depth3); - assert_eq!(repos_depth3.len(), 3); - - let repo_names: Vec<&str> = repos_depth3.iter().map(|r| r.name.as_str()).collect(); - assert!(repo_names.contains(&"root-repo")); - assert!(repo_names.contains(&"level1-repo")); - assert!(repo_names.contains(&"level2-repo")); -} - -#[test] -fn test_integration_subdir_functionality() { - let temp_dir = TempDir::new().unwrap(); - - // Create structure: project/checkout/.git - let project_dir = temp_dir.path().join("project"); - let checkout_dir = project_dir.join("checkout"); - fs::create_dir_all(&checkout_dir).unwrap(); - - let _repo = create_git_repo_with_commit(&checkout_dir, "test-repo"); - - // Test with subdir option - let args = Args { - dir: temp_dir.path().to_path_buf(), - depth: 3, - subdir: Some("checkout".to_owned()), - ..Default::default() - }; - - let (repos, failed) = scan::find_repositories(&args); - - assert_eq!(repos.len(), 1); - assert_eq!(failed.len(), 0); - assert_eq!(repos[0].name, "test-repo"); -} - /// Repositories are collected in parallel with rayon, so the raw collection order depends /// on thread scheduling. `find_repositories` must hand back a sorted, reproducible order, /// otherwise consumers that do not sort themselves (`--json`, the failure warnings) emit a @@ -378,6 +358,15 @@ fn test_integration_repository_fast_forward() { assert_eq!(repos.len(), 1); assert_eq!(failed.len(), 0); assert!(repos[0].fast_forwarded); + assert!( + local_temp_dir.path().join("local-repo/dummy.md").exists(), + "the fast-forward must check the new commit out, not only move the branch" + ); + assert_ne!( + repos[0].status, + crate::gitinfo::status::Status::Dirty(1), + "the index and working tree must match the new commit" + ); assert_eq!( repos[0].commits, 2, "commit count must be gathered after the fast-forward" @@ -485,28 +474,24 @@ fn test_integration_worktree_detection() { // Create a feature branch let head = repo.head().unwrap(); + // Whatever `init.defaultBranch` the machine running the tests has configured. + let default_branch = head.shorthand().unwrap().to_owned(); let target = head.target().unwrap(); let commit = repo.find_commit(target).unwrap(); repo.branch("feature-branch", &commit, false).unwrap(); drop(commit); drop(head); - // Create a worktree using git command (git2-rs doesn't have worktree creation API) + // Check the feature branch out in a worktree. git2 does this itself, so the user's + // global git config (hooks and the like) never runs during the test. let worktree_path = temp_dir.path().join("feature-worktree"); - let output = std::process::Command::new("git") - .arg("worktree") - .arg("add") - .arg(&worktree_path) - .arg("feature-branch") - .current_dir(&main_repo_path) - .output() + let feature = repo + .find_branch("feature-branch", git2::BranchType::Local) + .unwrap(); + let mut opts = git2::WorktreeAddOptions::new(); + opts.reference(Some(feature.get())); + repo.worktree("feature-worktree", &worktree_path, Some(&opts)) .unwrap(); - - assert!( - output.status.success(), - "Failed to create worktree: {}", - String::from_utf8_lossy(&output.stderr) - ); // Now scan the temp directory for repositories let args = Args { @@ -542,12 +527,7 @@ fn test_integration_worktree_detection() { !main_repo.is_worktree, "Main repo should not be marked as worktree" ); - // Git might use "main" or "master" depending on configuration - assert!( - main_repo.branch == "main" || main_repo.branch == "master", - "Main repo branch should be 'main' or 'master', got: {}", - main_repo.branch - ); + assert_eq!(main_repo.branch, default_branch); // Verify worktree IS detected as a worktree assert!( @@ -601,18 +581,9 @@ fn test_integration_worktree_with_changes() { drop(index); // Create worktree + // Without a reference, git2 checks out a new branch named after the worktree. let worktree_path = temp_dir.path().join("worktree"); - let output = std::process::Command::new("git") - .arg("worktree") - .arg("add") - .arg(&worktree_path) - .arg("-b") - .arg("new-branch") - .current_dir(&main_repo_path) - .output() - .unwrap(); - - assert!(output.status.success()); + repo.worktree("new-branch", &worktree_path, None).unwrap(); // Make changes in the worktree let worktree_file = worktree_path.join("new-file.txt"); @@ -731,22 +702,11 @@ fn test_integration_depth_edge_values() { fn test_integration_unlimited_depth_ignores_git_internals() { let temp_dir = TempDir::new().unwrap(); - let main_repo_path = temp_dir.path().join("main-repo"); - create_git_repo_with_commit(temp_dir.path(), "main-repo"); + let repo = create_git_repo_with_commit(temp_dir.path(), "main-repo"); - // `git worktree add` populates .git/worktrees/ with a HEAD, commondir, gitdir... + // Adding a worktree populates .git/worktrees/ with a HEAD, commondir, gitdir... let worktree_path = temp_dir.path().join("feature-worktree"); - let output = std::process::Command::new("git") - .args(["worktree", "add", "-b", "feature"]) - .arg(&worktree_path) - .current_dir(&main_repo_path) - .output() - .unwrap(); - assert!( - output.status.success(), - "failed to create worktree: {}", - String::from_utf8_lossy(&output.stderr) - ); + repo.worktree("feature", &worktree_path, None).unwrap(); // An unlimited scan walks everything below the root, git directories included. let args = Args { @@ -808,7 +768,10 @@ fn test_integration_subdir_finds_repo_below_the_scanned_level() { let (repos, failed) = scan::find_repositories(&with_subdir); assert_eq!(failed.len(), 0); assert_eq!(repos.len(), 1, "--subdir must find the nested checkout"); - assert_eq!(repos[0].repo_path, "project/checkout"); + assert_eq!( + repos[0].repo_path, + Path::new("project").join("checkout").display().to_string() + ); // A subdir that does not exist anywhere must simply yield nothing. let missing_subdir = Args { @@ -907,3 +870,158 @@ fn test_repository_with_unreadable_history_is_reported_as_failed() { "the unreadable repository must be listed as failed, got: {failed:?}" ); } + +/// A `--subdir` checkout that cannot be opened is reported under the scanned directory's +/// name. Reporting the opened path's name listed every broken project as `checkout`. +#[test] +fn test_integration_unreadable_subdir_is_named_after_the_project() { + let temp_dir = TempDir::new().unwrap(); + let checkout = temp_dir.path().join("project").join("checkout"); + fs::create_dir_all(&checkout).unwrap(); + fs::write(checkout.join(".git"), "gitdir: /nowhere").unwrap(); + + let args = Args { + dir: temp_dir.path().to_path_buf(), + depth: 1, + subdir: Some("checkout".to_owned()), + ..Default::default() + }; + let (repos, failed) = scan::find_repositories(&args); + + assert!(repos.is_empty()); + assert_eq!(failed, ["project"]); +} + +/// `--fetch` alone updates the remote-tracking branch but not the local one, so the +/// repository is reported as behind and nothing is fast-forwarded. +#[test] +fn test_integration_fetch_reports_commits_behind() { + let temp = TempDir::new().unwrap(); + let (remote, _clone) = remote_and_clone(temp.path()); + commit_file(&remote, "upstream.txt", "new upstream work"); + + let info = scan_clone(temp.path(), true, false); + + assert_eq!((info.ahead, info.behind), (0, 1)); + assert!(!info.fast_forwarded); + assert_eq!(info.status, crate::gitinfo::status::Status::Clean); +} + +/// A branch that diverged from its upstream cannot be fast-forwarded. `--ff` must leave it +/// where it is and report both sides. +#[test] +fn test_integration_fast_forward_leaves_a_diverged_branch_alone() { + let temp = TempDir::new().unwrap(); + let (remote, clone) = remote_and_clone(temp.path()); + commit_file(&remote, "upstream.txt", "upstream"); + let local_head = commit_file(&clone, "local.txt", "local"); + + let info = scan_clone(temp.path(), false, true); + + assert!(!info.fast_forwarded); + assert_eq!((info.ahead, info.behind), (1, 1)); + let clone = Repository::open(clone.workdir().unwrap()).unwrap(); + assert_eq!(clone.head().unwrap().target(), Some(local_head)); +} + +/// An uncommitted change to a file the upstream changed too would be overwritten by the +/// fast-forward. The checkout must refuse, keeping both the branch and the change. +#[test] +fn test_integration_fast_forward_keeps_conflicting_local_changes() { + let temp = TempDir::new().unwrap(); + let (remote, clone) = remote_and_clone(temp.path()); + let before = clone.head().unwrap().target(); + commit_file(&remote, "README.md", "# Changed upstream\n"); + let readme = clone.workdir().unwrap().join("README.md"); + fs::write(&readme, "# Changed locally\n").unwrap(); + + let info = scan_clone(temp.path(), false, true); + + assert!(!info.fast_forwarded); + assert_eq!(info.behind, 1); + let clone = Repository::open(clone.workdir().unwrap()).unwrap(); + assert_eq!(clone.head().unwrap().target(), before, "HEAD must not move"); + assert_eq!(fs::read_to_string(&readme).unwrap(), "# Changed locally\n"); +} + +/// A detached HEAD is not on a branch, so there is nothing to fast-forward. +#[test] +fn test_integration_fast_forward_skips_a_detached_head() { + let temp = TempDir::new().unwrap(); + let (remote, clone) = remote_and_clone(temp.path()); + let before = clone.head().unwrap().target().unwrap(); + clone.set_head_detached(before).unwrap(); + commit_file(&remote, "upstream.txt", "upstream"); + + let info = scan_clone(temp.path(), false, true); + + assert!(!info.fast_forwarded); + assert!(info.is_detached); + let clone = Repository::open(clone.workdir().unwrap()).unwrap(); + assert_eq!(clone.head().unwrap().target(), Some(before)); +} + +/// A worktree's git directory lives inside the main repository's, so the fetch has to run +/// in the worktree's working directory to reach the remote at all. +#[test] +fn test_integration_fetch_from_a_worktree() { + let temp = TempDir::new().unwrap(); + let (remote, clone) = remote_and_clone(temp.path()); + let branch = clone.head().unwrap().shorthand().unwrap().to_owned(); + let worktree_path = temp.path().join("worktree"); + clone.worktree("wt", &worktree_path, None).unwrap(); + let upstream = commit_file(&remote, "upstream.txt", "upstream"); + + let worktree = Repository::open(&worktree_path).unwrap(); + crate::gitinfo::fetch_remote(&worktree).unwrap(); + + let tracking = worktree + .find_reference(&format!("refs/remotes/origin/{branch}")) + .unwrap(); + assert_eq!(tracking.target(), Some(upstream)); +} + +/// An unlimited scan keeps descending into a repository's working directory, so a +/// repository nested inside another one is reported as well. +#[test] +fn test_integration_unlimited_depth_finds_nested_repositories() { + let temp_dir = TempDir::new().unwrap(); + let outer = create_git_repo_with_commit(temp_dir.path(), "outer"); + create_git_repo_with_commit(outer.workdir().unwrap(), "inner"); + + let args = Args { + dir: temp_dir.path().to_path_buf(), + depth: -1, + ..Default::default() + }; + let (repos, failed) = scan::find_repositories(&args); + + assert_eq!(failed, Vec::::new()); + let paths: Vec<&str> = repos.iter().map(|r| r.repo_path.as_str()).collect(); + let inner = Path::new("outer").join("inner").display().to_string(); + assert_eq!(paths, ["outer", inner.as_str()]); +} + +/// The walk does not follow symlinks, but a link to a repository is still a directory +/// with a `.git` in it. It is shown under the link's name: git resolves the link when it +/// opens the repository, which used to put the absolute target path in the table. +#[cfg(unix)] +#[test] +fn test_integration_symlinked_repository_is_shown_under_the_link_name() { + let target_dir = TempDir::new().unwrap(); + create_git_repo_with_commit(target_dir.path(), "real"); + let scan_dir = TempDir::new().unwrap(); + std::os::unix::fs::symlink(target_dir.path().join("real"), scan_dir.path().join("link")) + .unwrap(); + + let args = Args { + dir: scan_dir.path().to_path_buf(), + depth: 1, + ..Default::default() + }; + let (repos, failed) = scan::find_repositories(&args); + + assert_eq!(failed, Vec::::new()); + assert_eq!(repos.len(), 1); + assert_eq!(repos[0].repo_path, "link"); +} diff --git a/src/tests/main_test.rs b/src/tests/main_test.rs index 7bc71f8..8fdd952 100644 --- a/src/tests/main_test.rs +++ b/src/tests/main_test.rs @@ -1,4 +1,4 @@ -use std::{fs, io, path::Path, path::PathBuf}; +use std::{fs, path::Path, path::PathBuf}; use clap::Parser; use clap_complete::Shell; @@ -28,6 +28,7 @@ fn repo_info_with_status(status: Status, stash_count: usize, fast_forwarded: boo fast_forwarded, repo_path: "repo".to_owned(), is_worktree: false, + is_detached: false, } } @@ -80,6 +81,9 @@ fn test_args_parse_json_fast_forward_and_subdir() { } /// Creates a repository with one commit, and optionally an uncommitted file. +/// +/// The commit is also on a remote-tracking branch, so a repository without the +/// uncommitted file is `Clean` rather than `Unpublished`. fn create_repo(parent: &Path, name: &str, dirty: bool) { let repo_path = parent.join(name); fs::create_dir_all(&repo_path).unwrap(); @@ -100,6 +104,13 @@ fn create_repo(parent: &Path, name: &str, dirty: bool) { repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[]) .unwrap(); + let head = repo.head().unwrap(); + let tracking = format!("refs/remotes/origin/{}", head.shorthand().unwrap()); + repo.remote("origin", &format!("https://example.com/{name}.git")) + .unwrap(); + repo.reference(&tracking, head.target().unwrap(), true, "test") + .unwrap(); + if dirty { fs::write(repo_path.join("uncommitted.txt"), "work in progress").unwrap(); } @@ -113,21 +124,42 @@ fn scan_dir() -> TempDir { temp } +/// Runs the tool and returns the report it wrote. +fn run_to_string(args: &Args) -> String { + let mut out = Vec::new(); + run(args, &mut out); + String::from_utf8(out).unwrap() +} + #[test] fn test_run_prints_table() { let temp = scan_dir(); - let args = Args { + let out = run_to_string(&Args { dir: temp.path().to_path_buf(), depth: 1, ..Default::default() - }; - run(&args, &mut io::sink()); + }); + + for expected in [ + "Directory", + "Branch", + "Commits", + "clean-repo", + "dirty-repo", + "Dirty (1)", + ] { + assert!(out.contains(expected), "missing {expected:?} in:\n{out}"); + } + assert!( + !out.contains("Remote") && !out.contains("Summary:"), + "optional columns and the summary are off by default, got:\n{out}" + ); } #[test] fn test_run_with_all_display_options() { let temp = scan_dir(); - let args = Args { + let out = run_to_string(&Args { dir: temp.path().to_path_buf(), depth: 1, remote: true, @@ -135,45 +167,73 @@ fn test_run_with_all_display_options() { condensed: true, summary: true, ..Default::default() - }; - run(&args, &mut io::sink()); + }); + + for expected in [ + "Remote", + "Path", + "Summary:", + "Total repositories: 2", + "Clean: 1", + "With changes: 1", + ] { + assert!(out.contains(expected), "missing {expected:?} in:\n{out}"); + } } #[test] fn test_run_with_non_clean_filter() { let temp = scan_dir(); - let args = Args { + let out = run_to_string(&Args { dir: temp.path().to_path_buf(), depth: 1, non_clean: true, summary: true, ..Default::default() - }; - run(&args, &mut io::sink()); + }); + + assert!(out.contains("dirty-repo"), "got:\n{out}"); + assert!( + !out.contains("clean-repo"), + "--non-clean must hide the clean repository, got:\n{out}" + ); + // The summary describes the whole scan, not only what the filter let through. + assert!(out.contains("Total repositories: 2"), "got:\n{out}"); } #[test] fn test_run_json() { let temp = scan_dir(); - let args = Args { + let out = run_to_string(&Args { dir: temp.path().to_path_buf(), depth: 1, json: true, ..Default::default() - }; - run(&args, &mut io::sink()); + }); + + let json: serde_json::Value = serde_json::from_str(&out).unwrap(); + let names: Vec<&str> = json["repositories"] + .as_array() + .unwrap() + .iter() + .map(|r| r["repo_path"].as_str().unwrap()) + .collect(); + assert_eq!(names, ["clean-repo", "dirty-repo"]); + assert_eq!(json["failed"], serde_json::json!([])); } #[test] fn test_run_on_directory_without_repositories() { let temp = TempDir::new().unwrap(); - let args = Args { + let out = run_to_string(&Args { dir: temp.path().to_path_buf(), depth: 1, summary: true, ..Default::default() - }; - run(&args, &mut io::sink()); + }); + + assert!(!out.contains("Directory"), "no table without repositories"); + assert!(out.contains("Total repositories: 0"), "got:\n{out}"); } /// A directory whose `.git` git cannot open is reported as failed, not as a hard error. @@ -190,18 +250,24 @@ fn test_run_reports_failed_repositories() { summary: true, ..Default::default() }; - run(&args, &mut io::sink()); + let mut out = Vec::new(); + let outcome = run(&args, &mut out); + + assert_eq!(outcome.failed, 1); + let out = String::from_utf8(out).unwrap(); + assert!(out.contains("Failed to process: 1"), "got:\n{out}"); } #[test] fn test_run_legend() { for condensed in [false, true] { - let args = Args { + let out = run_to_string(&Args { legend: true, condensed, ..Default::default() - }; - run(&args, &mut io::sink()); + }); + assert!(out.contains("Description"), "got:\n{out}"); + assert!(out.contains("⎇ indicates a Git worktree"), "got:\n{out}"); } } diff --git a/src/tests/printer_test.rs b/src/tests/printer_test.rs index 38c8984..b83a6ad 100644 --- a/src/tests/printer_test.rs +++ b/src/tests/printer_test.rs @@ -5,9 +5,7 @@ use strum::IntoEnumIterator as _; use crate::cli::Args; use crate::gitinfo::repoinfo::RepoInfo; use crate::gitinfo::status::Status; -use crate::printer::{ - failed_summary, json_output, json_value, legend, repositories_table, summary, -}; +use crate::printer::{json_output, json_value, legend, repositories_table, summary}; /// Renders one printer call into a string so tests can assert on real output. fn capture(f: impl FnOnce(&mut Vec)) -> String { @@ -48,6 +46,7 @@ fn test_repositories_table_with_data() { fast_forwarded: false, repo_path: "repo1".to_owned(), is_worktree: false, + is_detached: false, }]; let args = Args { dir: ".".into(), @@ -120,6 +119,7 @@ fn test_repositories_table_with_stashes_and_local_only() { fast_forwarded: false, repo_path: "repo-with-stash".to_owned(), is_worktree: false, + is_detached: false, }, RepoInfo { name: "repo-with-upstream".to_owned(), @@ -136,6 +136,7 @@ fn test_repositories_table_with_stashes_and_local_only() { fast_forwarded: false, repo_path: "repo-with-upstream".to_owned(), is_worktree: false, + is_detached: false, }, ]; let args = Args { @@ -171,6 +172,7 @@ fn test_repositories_table_with_path_option() { fast_forwarded: false, repo_path: "test-repo".to_owned(), is_worktree: false, + is_detached: false, }]; let args = Args { dir: ".".into(), @@ -191,7 +193,7 @@ fn test_repositories_table_with_path_option() { #[test] fn test_repositories_table_condensed_layout() { - let repos = vec![RepoInfo { + let mut repos = vec![RepoInfo { name: "repo".to_owned(), branch: "develop".to_owned(), ahead: 2, @@ -206,7 +208,12 @@ fn test_repositories_table_condensed_layout() { fast_forwarded: false, repo_path: "repo".to_owned(), is_worktree: false, + is_detached: false, }]; + // The presets differ in the separator drawn between rows, which takes a second row. + let mut second = repos[0].clone(); + second.repo_path = "other".to_owned(); + repos.push(second); let args = Args { dir: ".".into(), depth: 1, @@ -229,12 +236,24 @@ fn test_repositories_table_condensed_layout() { "condensed table must contain `{expected}`, got:\n{rendered}" ); } - // The condensed preset drops the separator line drawn between rows; with a single row - // there is none to drop, so only the multi-row case can tell the presets apart. assert!( !rendered.contains('╌'), "the condensed preset must not draw inter-row separators, got:\n{rendered}" ); + let full = capture(|w| { + repositories_table( + &repos, + &Args { + condensed: false, + ..args + }, + w, + ); + }); + assert!( + full.contains('╌'), + "the full preset draws a separator between rows, got:\n{full}" + ); } #[test] @@ -255,6 +274,7 @@ fn test_repositories_table_non_clean_filter() { fast_forwarded: false, repo_path: "clean-repo".to_owned(), is_worktree: false, + is_detached: false, }, RepoInfo { name: "dirty-repo".to_owned(), @@ -271,6 +291,7 @@ fn test_repositories_table_non_clean_filter() { fast_forwarded: false, repo_path: "dirty-repo".to_owned(), is_worktree: false, + is_detached: false, }, ]; let args = Args { @@ -309,6 +330,7 @@ fn test_repositories_table_renders_rows_in_given_order() { fast_forwarded: false, repo_path: "zebra-repo".to_owned(), is_worktree: false, + is_detached: false, }, RepoInfo { name: "Alpha-Repo".to_owned(), // Capital letter @@ -325,6 +347,7 @@ fn test_repositories_table_renders_rows_in_given_order() { fast_forwarded: false, repo_path: "Alpha-Repo".to_owned(), is_worktree: false, + is_detached: false, }, RepoInfo { name: "beta-repo".to_owned(), @@ -341,6 +364,7 @@ fn test_repositories_table_renders_rows_in_given_order() { fast_forwarded: false, repo_path: "beta-repo".to_owned(), is_worktree: false, + is_detached: false, }, ]; let args = Args { @@ -357,9 +381,6 @@ fn test_repositories_table_renders_rows_in_given_order() { zebra < alpha && alpha < beta, "the printer must keep the order it was given, got:\n{rendered}" ); - assert_eq!(repos[0].name, "zebra-repo"); - assert_eq!(repos[1].name, "Alpha-Repo"); - assert_eq!(repos[2].name, "beta-repo"); } #[test] @@ -380,6 +401,7 @@ fn test_repositories_table_various_statuses() { fast_forwarded: false, repo_path: "rebase-repo".to_owned(), is_worktree: false, + is_detached: false, }, RepoInfo { name: "cherry-repo".to_owned(), @@ -396,6 +418,7 @@ fn test_repositories_table_various_statuses() { fast_forwarded: false, repo_path: "cherry-repo".to_owned(), is_worktree: false, + is_detached: false, }, RepoInfo { name: "bisect-repo".to_owned(), @@ -412,6 +435,7 @@ fn test_repositories_table_various_statuses() { fast_forwarded: false, repo_path: "bisect-repo".to_owned(), is_worktree: false, + is_detached: false, }, ]; let args = Args { @@ -457,6 +481,7 @@ fn test_summary_comprehensive() { fast_forwarded: false, repo_path: "clean1".to_owned(), is_worktree: false, + is_detached: false, }, RepoInfo { name: "clean2".to_owned(), @@ -473,6 +498,7 @@ fn test_summary_comprehensive() { fast_forwarded: false, repo_path: "clean2".to_owned(), is_worktree: false, + is_detached: false, }, RepoInfo { name: "dirty".to_owned(), @@ -489,6 +515,7 @@ fn test_summary_comprehensive() { fast_forwarded: false, repo_path: "dirty".to_owned(), is_worktree: false, + is_detached: false, }, ]; @@ -517,24 +544,6 @@ fn test_summary_comprehensive() { // - 1 failed } -#[test] -fn test_failed_summary_empty() { - let failed_repos: Vec = vec![]; - failed_summary(&failed_repos); - // Should not print anything -} - -#[test] -fn test_failed_summary_multiple() { - let failed_repos = vec![ - "broken-repo-1".to_owned(), - "corrupted-repo-2".to_owned(), - "invalid-git-dir".to_owned(), - ]; - failed_summary(&failed_repos); - // Should print warning about failed repos -} - #[test] fn test_summary_edge_cases() { // Test with no repos @@ -572,6 +581,7 @@ fn test_summary_edge_cases() { fast_forwarded: false, repo_path: "unknown-status".to_owned(), is_worktree: false, + is_detached: false, }]; let rendered = capture(|w| summary(&edge_repos, 0, w)); assert!( @@ -598,6 +608,7 @@ fn test_repositories_table_marks_worktree_rows() { fast_forwarded: false, repo_path: "worktree-repo".to_owned(), is_worktree: true, + is_detached: false, }]; let args = Args { dir: ".".into(), @@ -628,6 +639,7 @@ fn test_json_output_smoke() { fast_forwarded: false, repo_path: "json-repo".to_owned(), is_worktree: false, + is_detached: false, }]; let failed = vec!["broken-repo".to_owned()]; let rendered = capture(|w| json_output(&repos, &failed, w)); @@ -660,6 +672,7 @@ fn repo_named(name: &str, status: Status) -> RepoInfo { fast_forwarded: false, repo_path: name.to_owned(), is_worktree: false, + is_detached: false, } } diff --git a/src/tests/smoke_test.rs b/src/tests/smoke_test.rs index 6e95d7a..a436645 100644 --- a/src/tests/smoke_test.rs +++ b/src/tests/smoke_test.rs @@ -5,22 +5,21 @@ use std::{fs, path::Path, time::Instant}; -use git2::Repository; +use git2::{Repository, RepositoryInitOptions}; use crate::scan; -use crate::{ - cli::Args, - gitinfo::{self, status::Status}, -}; +use crate::{cli::Args, gitinfo::status::Status}; /// Helper function to create a repository with a commit fn create_repo_with_commit(path: &Path, file_content: &str) -> Repository { - let repo = Repository::init(path).unwrap(); + // Setting `init.defaultBranch` after `init` has no effect, so name the branch up front: + // the remote-tracking refs the tests create assume it is `main`. + let repo = + Repository::init_opts(path, RepositoryInitOptions::new().initial_head("main")).unwrap(); { let mut config = repo.config().unwrap(); config.set_str("user.name", "Test User").unwrap(); config.set_str("user.email", "test@example.com").unwrap(); - config.set_str("init.defaultBranch", "main").unwrap(); } let file_path = path.join("test.txt"); @@ -101,10 +100,17 @@ fn test_multiple_repos_with_different_remotes_and_statuses() { dir: base_path.to_path_buf(), ..Default::default() }; - _ = scan::find_repositories(&args); + let (repos, failed) = scan::find_repositories(&args); let duration = start.elapsed(); + assert_eq!(failed, Vec::::new()); + assert_eq!(repos.len(), test_cases.len()); + assert!( + repos.iter().all(|r| r.status == Status::Clean), + "every repository matches its remote-tracking branch" + ); + // A generous ceiling on purpose: this guards against a pathological regression (a // per-repository network call, an accidental O(n^2) walk), not against a slow or // loaded CI runner. A tight bound here only buys flaky failures. @@ -116,59 +122,6 @@ fn test_multiple_repos_with_different_remotes_and_statuses() { println!("✓ All 40 repositories checked correctly in {duration:?}"); } -struct RemoteTest { - name: &'static str, - remote_name: &'static str, - remote_url: &'static str, - should_prefer_origin: bool, -} - -#[test] -fn test_remote_url_extraction_from_various_sources() { - let tmp_dir = tempfile::tempdir().unwrap(); - let base_path = tmp_dir.path(); - - let test_cases = vec![ - RemoteTest { - name: "origin_github", - remote_name: "origin", - remote_url: "https://github.com/user/repo.git", - should_prefer_origin: true, - }, - RemoteTest { - name: "upstream_gitlab", - remote_name: "upstream", - remote_url: "https://gitlab.com/user/repo.git", - should_prefer_origin: false, - }, - RemoteTest { - name: "custom_bitbucket", - remote_name: "custom", - remote_url: "https://bitbucket.org/user/repo.git", - should_prefer_origin: false, - }, - ]; - - for test in &test_cases { - let repo_path = base_path.join(test.name); - fs::create_dir_all(&repo_path).unwrap(); - let repo = create_repo_with_commit(&repo_path, "content"); - - if test.should_prefer_origin { - add_remote(&repo, "upstream", "https://github.com/upstream/repo.git"); - } - add_remote(&repo, test.remote_name, test.remote_url); - - let url = gitinfo::get_remote_url(&repo); - assert_eq!( - url.as_deref(), - Some(test.remote_url), - "Failed for {}", - test.name - ); - } -} - #[test] fn test_concurrent_status_checks_performance() { use rayon::prelude::*; @@ -176,9 +129,10 @@ fn test_concurrent_status_checks_performance() { let tmp_dir = tempfile::tempdir().unwrap(); let base_path = tmp_dir.path(); - // Create 20 repositories + // Create 20 repositories, each with the status its configuration must produce let repo_count = 20; let mut repo_paths = Vec::new(); + let mut expected = Vec::new(); for i in 0..repo_count { let repo_path = base_path.join(format!("repo_{i:02}")); @@ -194,6 +148,7 @@ fn test_concurrent_status_checks_performance() { &format!("https://github.com/user/repo_{i}.git"), ); create_remote_branch(&repo, "origin", "main", initial_commit); + expected.push(Status::Clean); } else if i % 3 == 1 { add_remote( &repo, @@ -202,28 +157,36 @@ fn test_concurrent_status_checks_performance() { ); create_remote_branch(&repo, "upstream", "main", initial_commit); make_commit(&repo, &repo_path.join("test.txt"), "new", "Second"); + expected.push(Status::Unpushed); + } else { + expected.push(Status::Unpublished); } - // else: no remote repo_paths.push(repo_path); } // Sequential check let start_seq = Instant::now(); - for path in &repo_paths { - let repo = Repository::open(path).unwrap(); - let _status = Status::new(&repo); - } + let sequential: Vec = repo_paths + .iter() + .map(|path| Status::new(&Repository::open(path).unwrap())) + .collect(); let duration_seq = start_seq.elapsed(); // Parallel check (simulating real-world usage with rayon) let start_par = Instant::now(); - repo_paths.par_iter().for_each(|path| { - let repo = Repository::open(path).unwrap(); - let _status = Status::new(&repo); - }); + let parallel: Vec = repo_paths + .par_iter() + .map(|path| Status::new(&Repository::open(path).unwrap())) + .collect(); let duration_par = start_par.elapsed(); + assert_eq!(sequential, expected); + assert_eq!( + parallel, expected, + "checking in parallel must not change a result" + ); + println!("Sequential: {duration_seq:?}, Parallel: {duration_par:?}"); // Deliberately generous - see the note in the 40-repository test above. No speedup diff --git a/src/tests/util_test.rs b/src/tests/util_test.rs index dae9bcb..5f70e7d 100644 --- a/src/tests/util_test.rs +++ b/src/tests/util_test.rs @@ -1,4 +1,3 @@ -// Remove the unused import use crate::cli::Args; use crate::gitinfo::{repoinfo::RepoInfo, status::Status}; use crate::printer; @@ -30,7 +29,7 @@ fn test_find_repositories_empty_dir() { }; let (repos, failed) = scan::find_repositories(&args); assert!(repos.is_empty()); - assert!(failed.is_empty()); + assert_eq!(failed, Vec::::new()); } #[test] @@ -51,6 +50,7 @@ fn test_print_repositories_and_summary() { fast_forwarded: false, repo_path: "dummy".to_owned(), is_worktree: false, + is_detached: false, }; let args = Args { dir: Path::new(".").to_path_buf(), @@ -83,39 +83,7 @@ fn test_find_repositories_with_non_git_dir() { }; let (repos, failed) = scan::find_repositories(&args); assert!(repos.is_empty()); - assert!(failed.is_empty()); -} - -#[test] -fn test_print_repositories_with_remote() { - let repo = RepoInfo { - name: "dummy".to_owned(), - branch: "main".to_owned(), - ahead: 0, - behind: 0, - commits: 1, - status: Status::Clean, - has_unpushed: false, - remote_url: Some("https://example.com".to_owned()), - path: PathBuf::from("/path/to/dummy"), - stash_count: 0, - is_local_only: false, - fast_forwarded: false, - repo_path: "dummy".to_owned(), - is_worktree: false, - }; - let args = Args { - dir: Path::new(".").to_path_buf(), - depth: 1, - remote: true, - ..Default::default() - }; - let repos = vec![repo]; - let rendered = capture(|w| printer::repositories_table(&repos, &args, w)); - assert!( - rendered.contains("Remote"), - "`--remote` must add the Remote column, got:\n{rendered}" - ); + assert_eq!(failed, Vec::::new()); } // New tests for GitPathExt trait @@ -177,42 +145,6 @@ fn test_git_path_ext_dir_name_unicode() { assert_eq!(emoji_path.dir_name(), "🚀-repo"); } -#[test] -fn test_find_repositories_negative_depth() { - let temp = TempDir::new().unwrap(); - - // Test unlimited depth behavior - let args = Args { - dir: temp.path().to_path_buf(), - depth: -1, - ..Default::default() - }; - - let (repos, failed) = scan::find_repositories(&args); - - // Should complete without crashing (empty dir, no repos expected) - assert_eq!(failed.len(), 0); - assert!(repos.is_empty()); // No repos in empty temp dir -} - -#[test] -fn test_find_repositories_depth_zero() { - let temp = TempDir::new().unwrap(); - - // Test depth 0 behavior - should work like depth 1 - let args = Args { - dir: temp.path().to_path_buf(), - depth: 0, - ..Default::default() - }; - - let (repos, failed) = scan::find_repositories(&args); - - // Should complete without crashing (empty dir, no repos expected) - assert_eq!(failed.len(), 0); - assert!(repos.is_empty()); // No repos in empty temp dir -} - #[test] fn test_find_repositories_with_failed_repos() { let temp = TempDir::new().unwrap(); @@ -234,25 +166,3 @@ fn test_find_repositories_with_failed_repos() { assert_eq!(failed.len(), 1); assert_eq!(failed[0], "fake-repo"); } - -#[test] -fn test_find_repositories_with_subdir_not_found() { - let temp = TempDir::new().unwrap(); - - // Create directory without the specified subdir - let project_dir = temp.path().join("project"); - fs::create_dir_all(&project_dir).unwrap(); - - let args = Args { - dir: temp.path().to_path_buf(), - depth: 2, - subdir: Some("nonexistent".to_owned()), - ..Default::default() - }; - - let (repos, failed) = scan::find_repositories(&args); - - // Should find no repos because subdir doesn't exist - assert_eq!(repos.len(), 0); - assert_eq!(failed.len(), 0); -} diff --git a/tests/cli.rs b/tests/cli.rs index b102fd5..3836f0a 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -60,13 +60,16 @@ fn json_output_is_the_only_thing_on_stdout() { .unwrap(); let stdout = String::from_utf8(output.stdout).unwrap(); - serde_json::from_str::(&stdout) + let json = serde_json::from_str::(&stdout) .unwrap_or_else(|e| panic!("`--json` stdout must parse as JSON ({e}), got:\n{stdout}")); + assert_eq!(json["failed"], serde_json::json!(["broken"])); - // The diagnostic about the unreadable repository still has to be reported somewhere. + // The unreadable repository is reported on stderr as well, as it is for the table. Only + // a debug-level line used to mention it, which a release build does not print. let stderr = String::from_utf8(output.stderr).unwrap(); assert!( - stderr.contains("broken"), + stderr.contains("Failed to process the following repositories") + && stderr.contains("broken"), "the unreadable repository must be reported on stderr, got:\n{stderr}" ); } @@ -86,6 +89,14 @@ fn table_output_is_the_only_thing_on_stdout() { !stdout.contains("DEBUG") && !stdout.contains("WARN"), "log records must not appear on stdout, got:\n{stdout}" ); + + // `failed_summary` logs, so this is where its output can be observed. + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("Failed to process the following repositories") + && stderr.contains(" - broken"), + "the unreadable repository must be listed on stderr, got:\n{stderr}" + ); } /// A repository that cannot be processed makes the run fail, so scripts can notice. From 12cc51dc763380d1cfee139a62c80ed5e8c84a79 Mon Sep 17 00:00:00 2001 From: bircni Date: Sun, 18 Oct 2026 14:46:15 +0200 Subject: [PATCH 3/5] feat(release): publish a Homebrew formula to bircni/homebrew-tap The release workflow renders Formula/git-statuses.rb from the archives it built with scripts/homebrew_formula.sh and pushes it to the tap with the HOMEBREW_TAP_DEPLOY_KEY deploy key. Prereleases are skipped. The workflow is modernized along the way: dtolnay/rust-toolchain instead of the archived actions-rs, $GITHUB_OUTPUT instead of set-output, --locked builds instead of a `cargo update` at release time, no OpenSSL install on macOS where it was unused, and current action versions. Closes #50 --- .github/workflows/deploy.yml | 156 +++++++++++++++-------------------- scripts/homebrew_formula.sh | 86 +++++++++++++++++++ 2 files changed, 154 insertions(+), 88 deletions(-) create mode 100755 scripts/homebrew_formula.sh diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 33887ff..c46e037 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -9,43 +9,27 @@ jobs: create-windows-binaries: runs-on: windows-latest steps: - - uses: actions/checkout@v4 - with: - lfs: true + - uses: actions/checkout@v7 - - name: Install stable - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true + - name: Install Rust stable + uses: dtolnay/rust-toolchain@stable - name: Build git-statuses - run: | - cargo build --release - - - name: Get the version - shell: bash - id: tagName - run: | - VERSION=$(cargo pkgid | cut -d# -f2 | cut -d: -f2) - echo "::set-output name=tag::$VERSION" + run: cargo build --release --locked - name: Build package id: package shell: bash run: | - ARCHIVE_TARGET="x86_64-pc-windows-msvc" - ARCHIVE_NAME="git-statuses-${{ steps.tagName.outputs.tag }}-$ARCHIVE_TARGET" - ARCHIVE_FILE="${ARCHIVE_NAME}.zip" - 7z a ${ARCHIVE_FILE} ./target/release/git-statuses.exe - echo "::set-output name=file::${ARCHIVE_FILE}" - echo "::set-output name=name::${ARCHIVE_NAME}.zip" + VERSION=$(cargo pkgid | cut -d# -f2 | cut -d: -f2) + ARCHIVE_FILE="git-statuses-${VERSION}-x86_64-pc-windows-msvc.zip" + 7z a "$ARCHIVE_FILE" ./target/release/git-statuses.exe + echo "file=$ARCHIVE_FILE" >> "$GITHUB_OUTPUT" - name: Upload artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: - name: ${{ steps.package.outputs.name }} + name: ${{ steps.package.outputs.file }} path: ${{ steps.package.outputs.file }} create-unix-binaries: @@ -62,58 +46,39 @@ jobs: runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 - with: - lfs: true + - uses: actions/checkout@v7 - - name: Install Rust - uses: actions-rs/toolchain@v1 + - name: Install Rust stable + uses: dtolnay/rust-toolchain@stable with: - profile: minimal - toolchain: stable - target: ${{ matrix.target }} - override: true + targets: ${{ matrix.target }} + # macOS needs nothing extra: libgit2 uses the system TLS there, and OpenSSL is only + # vendored into the Linux build. - name: Install musl-tools and musl OpenSSL if: matrix.os == 'ubuntu-latest' run: | sudo apt-get update sudo apt-get install -y musl-tools curl pkg-config libssl-dev - echo "Enable musl OpenSSL" - echo "PKG_CONFIG_ALLOW_CROSS=1" >> $GITHUB_ENV - rustup target add x86_64-unknown-linux-musl - - - name: Install OpenSSL on macOS - if: matrix.os == 'macos-latest' - run: | - brew install openssl - echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV + echo "PKG_CONFIG_ALLOW_CROSS=1" >> "$GITHUB_ENV" - name: Build git-statuses - run: | - cargo build --release --target ${{ matrix.target }} + run: cargo build --release --locked --target ${{ matrix.target }} - name: Strip binary - run: | - strip target/${{ matrix.target }}/release/git-statuses - - - name: Get the version - id: tagName - run: | - VERSION=$(cargo pkgid | cut -d# -f2 | cut -d: -f2) - echo "::set-output name=tag::$VERSION" + run: strip target/${{ matrix.target }}/release/git-statuses - name: Build package id: package run: | - TAR_FILE=git-statuses-${{ steps.tagName.outputs.tag }}-${{ matrix.target }} - cd target/${{ matrix.target }}/release - tar -czvf $GITHUB_WORKSPACE/$TAR_FILE.tar.gz git-statuses - echo ::set-output "name=name::${TAR_FILE}" - echo ::set-output "name=file::${TAR_FILE}.tar.gz " + VERSION=$(cargo pkgid | cut -d# -f2 | cut -d: -f2) + TAR_FILE="git-statuses-${VERSION}-${{ matrix.target }}" + tar -czvf "$TAR_FILE.tar.gz" -C target/${{ matrix.target }}/release git-statuses + echo "name=$TAR_FILE" >> "$GITHUB_OUTPUT" + echo "file=$TAR_FILE.tar.gz" >> "$GITHUB_OUTPUT" - name: Upload artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: ${{ steps.package.outputs.name }} path: ${{ steps.package.outputs.file }} @@ -126,38 +91,53 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - with: - lfs: true - - - name: Install Rust stable - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true - - - name: Create Cargo.lock - run: | - cargo update - - - name: Get version - id: tagName - run: | - VERSION=$(cargo pkgid | cut -d# -f2 | cut -d: -f2) - echo "::set-output name=tag::$VERSION" - - name: Download artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: path: ./binaries + merge-multiple: true - name: Create a release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: - name: v${{ steps.tagName.outputs.tag }} + name: v${{ github.ref_name }} files: | - ./binaries/**/*.zip - ./binaries/**/*.tar.gz - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ./binaries/*.zip + ./binaries/*.tar.gz + + homebrew: + name: Update the Homebrew formula + needs: deploy + # Prereleases never become the formula's version. + if: ${{ !contains(github.ref_name, '-') }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + sparse-checkout: scripts/homebrew_formula.sh + sparse-checkout-cone-mode: false + + - name: Download the release archives + uses: actions/download-artifact@v8 + with: + path: release + merge-multiple: true + + - uses: actions/checkout@v7 + with: + repository: bircni/homebrew-tap + ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }} + path: tap + + - name: Commit the formula + run: | + mkdir -p tap/Formula + bash scripts/homebrew_formula.sh "$GITHUB_REF_NAME" release > tap/Formula/git-statuses.rb + cd tap + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add Formula/git-statuses.rb + if ! git diff --cached --quiet; then + git commit -m "git-statuses $GITHUB_REF_NAME" + git push + fi diff --git a/scripts/homebrew_formula.sh b/scripts/homebrew_formula.sh new file mode 100755 index 0000000..01733ad --- /dev/null +++ b/scripts/homebrew_formula.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# +# Renders the Homebrew formula for a release to stdout. The release workflow commits the +# result to bircni/homebrew-tap as Formula/git-statuses.rb. +# +# Usage: scripts/homebrew_formula.sh +# +# The version doubles as the tag name, which is how release_version.sh tags releases. + +set -euo pipefail + +# Function to print errors only +err() { echo "$@" 1>&2; } + +if [ $# -ne 2 ]; then + err "Usage: $0 " + exit 1 +fi + +version="$1" +archives="$2" +download="https://github.com/bircni/git-statuses/releases/download/${version}" + +# Prints the SHA-256 of the archive built for the given target. +checksum() { + local archive="${archives}/git-statuses-${version}-$1.tar.gz" + if [ ! -f "$archive" ]; then + err "Missing release archive: $archive" + exit 1 + fi + shasum -a 256 "$archive" | cut -d' ' -f1 +} + +# Resolved before rendering: a failure inside the heredoc would not stop the script. +sha_macos_arm=$(checksum aarch64-apple-darwin) +sha_macos_intel=$(checksum x86_64-apple-darwin) +sha_linux_intel=$(checksum x86_64-unknown-linux-musl) + +cat < Date: Sun, 18 Oct 2026 14:46:15 +0200 Subject: [PATCH 4/5] ci: pin third-party actions and restrict workflow permissions crate-ci/typos and cargo-bins/cargo-binstall ran from their default branches. Both workflows now also default to a read-only token, like the release workflow already does. --- .github/workflows/ci.yml | 19 +++++++++++-------- .github/workflows/publish_checks.yml | 5 ++++- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 55b8d63..0cb31b8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,28 +10,31 @@ on: branches: - main +permissions: + contents: read + jobs: typos: name: Typos runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: lfs: true - - uses: crate-ci/typos@master + - uses: crate-ci/typos@v1.51.1 cargo-shear: runs-on: ubuntu-latest needs: typos steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: lfs: true - name: Install cargo-binstall - uses: cargo-bins/cargo-binstall@main + uses: cargo-bins/cargo-binstall@v1.26.0 - name: Install cargo-shear run: cargo binstall --no-confirm cargo-shear @@ -42,7 +45,7 @@ jobs: runs-on: ubuntu-latest needs: typos steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: lfs: true - uses: EmbarkStudios/cargo-deny-action@v2 @@ -53,7 +56,7 @@ jobs: needs: [cargo-shear, cargo-deny] steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: lfs: true - uses: dtolnay/rust-toolchain@master @@ -72,7 +75,7 @@ jobs: needs: build steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: lfs: true - uses: dtolnay/rust-toolchain@master @@ -101,7 +104,7 @@ jobs: needs: check steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: lfs: true diff --git a/.github/workflows/publish_checks.yml b/.github/workflows/publish_checks.yml index 96e8fcc..d8e0f75 100644 --- a/.github/workflows/publish_checks.yml +++ b/.github/workflows/publish_checks.yml @@ -5,6 +5,9 @@ on: branches: - main +permissions: + contents: read + jobs: publish-check: name: Publish Check @@ -13,7 +16,7 @@ jobs: - uses: dtolnay/rust-toolchain@master with: toolchain: stable - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: lfs: true - uses: Swatinem/rust-cache@v2 From 83c492a77069356d879d67add38c638165769d5c Mon Sep 17 00:00:00 2001 From: bircni Date: Sun, 18 Oct 2026 14:46:15 +0200 Subject: [PATCH 5/5] docs(readme): document Homebrew and refresh the usage and output sections --- README.md | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 68ce83d..0a19836 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,15 @@ A command-line tool to display the status of multiple Git repositories in a clea ## Installation -You need [Rust](https://www.rust-lang.org/tools/install) installed. +With [Homebrew](https://brew.sh) on macOS (Apple Silicon and Intel) or Linux (x86_64): + +```sh +brew install bircni/tap/git-statuses +``` + +This also installs the bash, zsh and fish completions. + +With Cargo, which needs [Rust](https://www.rust-lang.org/tools/install) installed: ```sh cargo install git-statuses @@ -45,7 +53,7 @@ Run in any directory to scan for Git repositories: ```text A tool to display git repository statuses in a table format -Usage: git-statuses.exe [OPTIONS] [DIR] +Usage: git-statuses [OPTIONS] [DIR] Arguments: [DIR] Directory to scan [default: .] @@ -56,11 +64,13 @@ Options: -c, --condensed Use a condensed layout -s, --summary Show a summary of the scan -f, --fetch Run a fetch before scanning to update the repository state Note: This may take a while for large repositories + -F, --ff Run a fast-forward merge after fetching -l, --legend Print a legend explaining the color codes and statuses used in the output --subdir Look in a specific subdir if it exists for each folder This can be useful, if you don't checkout in a folder directly but in a subfolder like `repo-name/checkout` --completions Generate shell completions [possible values: bash, elvish, fish, powershell, zsh] -p, --path Show the path to the repository -n, --non-clean Only show non clean repositories + --json Output in JSON format -h, --help Print help -V, --version Print version ``` @@ -69,10 +79,12 @@ Options: The tool prints a table with the following columns: -- Path +- Directory (relative to the scanned directory, `⎇` marks a worktree) - Branch -- Status (clean/dirty) -- Ahead/Behind +- Local (commits ahead/behind the upstream, or `local-only`) +- Commits +- Status (run `git-statuses --legend` for what each one means) +- Remote and Path, with `--remote` and `--path` The report goes to stdout and diagnostics go to stderr, so `--json` can be piped straight into another tool: @@ -90,7 +102,7 @@ git-statuses --json | jq '.repositories[] | select(.status != "Clean")' ## Development -- Requires Rust 1.88+ (edition 2024) +- Requires the latest stable Rust (1.99+, edition 2024) - Linting: `cargo clippy` - Tests: `cargo test`