use crate::cli;
use gitlimes::fmt::{fit, parse_ts, rel_compact};
use gitlimes::json::Obj;
use gitlimes::pager;
use gitlimes::repo;
use gitlimes::style::{c, BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW};
use std::io::{self, Write};
pub const HELP: &str = "\
gitlimes branches - branch overview
USAGE:
gitlimes branches [OPTIONS]
OPTIONS:
-a, --all include remote-tracking branches
--stale <DAYS> mark branches untouched for longer than DAYS
--vs <REF> show ahead/behind against REF instead of the upstream
--json one JSON object per branch (newline delimited)
-h, --help show this help
";
const FIELDS: &str = "%(symref)%00%(HEAD)%00%(refname:short)%00%(committerdate:unix)%00%(authorname)%00%(upstream:track)%00%(subject)";
fn format_arg(vs: Option<&str>) -> String {
match vs {
Some(base) => format!("--format={}%00%(ahead-behind:{})", FIELDS, base),
None => format!("--format={}", FIELDS),
}
}
fn for_each_ref(format: &str, all: bool) -> Vec<&str> {
let mut argv = vec![
"for-each-ref",
format,
"--sort=-committerdate",
"refs/heads",
];
if all {
argv.push("refs/remotes");
}
argv
}
struct Branch {
current: bool,
name: String,
ts: i64,
author: String,
track: String,
subject: String,
}
#[derive(Default)]
struct Opts {
all: bool,
stale_days: Option<u32>,
vs: Option<String>,
json: bool,
}
fn parse(args: Vec<String>) -> Result<Option<Opts>, String> {
let mut o = Opts::default();
let mut it = args.into_iter();
while let Some(a) = it.next() {
let (key, inline) = match cli::split_eq(&a) {
Some((k, v)) if k.starts_with("--") => (k.to_string(), Some(v.to_string())),
_ => (a.clone(), None),
};
let value = |it: &mut std::vec::IntoIter<String>| match inline.clone() {
Some(v) => Ok(v),
None => it.next().ok_or_else(|| format!("{} needs a value", key)),
};
match key.as_str() {
"-h" | "--help" => {
print!("{}", HELP);
return Ok(None);
}
"-a" | "--all" => {
cli::no_value(&key, &inline)?;
o.all = true
}
"--stale" => {
let v = value(&mut it)?;
o.stale_days =
Some(v.parse::<u32>().map_err(|_| {
format!("--stale expects a whole number of days, got '{}'", v)
})?);
}
"--vs" => o.vs = Some(value(&mut it)?),
"--json" => {
cli::no_value(&key, &inline)?;
o.json = true
}
s => return Err(cli::Unknown(s.to_string()).to_string()),
}
}
Ok(Some(o))
}
pub fn run(args: Vec<String>) -> io::Result<()> {
let o = match parse(args) {
Ok(None) => return Ok(()),
Ok(Some(o)) => o,
Err(e) => {
eprintln!("gitlimes: {}", e);
std::process::exit(2);
}
};
let plain = format_arg(None);
let comparing = o.vs.as_deref().map(|base| format_arg(Some(base)));
let (raw, inline_track) = match &comparing {
Some(f) => match repo::probe(&for_each_ref(f, o.all))? {
Some(raw) => (raw, true),
None => (repo::capture(&for_each_ref(&plain, o.all))?, false),
},
None => (repo::capture(&for_each_ref(&plain, o.all))?, false),
};
let mut branches = Vec::new();
for line in raw.lines() {
if line.is_empty() {
continue;
}
let mut f = line.split(repo::FS);
let (
Some(symref),
Some(head),
Some(name),
Some(ts),
Some(author),
Some(upstream),
Some(subject),
) = (
f.next(),
f.next(),
f.next(),
f.next(),
f.next(),
f.next(),
f.next(),
)
else {
continue;
};
if !symref.is_empty() {
continue;
}
let track = if inline_track {
let mut n = f.next().unwrap_or("").split_whitespace();
describe(n.next().unwrap_or("0"), n.next().unwrap_or("0"))
} else {
clean_track(upstream)
};
branches.push(Branch {
current: head.trim() == "*",
name: name.to_string(),
ts: parse_ts(ts),
author: author.to_string(),
track,
subject: subject.to_string(),
});
}
if branches.is_empty() {
eprintln!("gitlimes: no branches");
return Ok(());
}
if let (Some(base), false) = (&o.vs, inline_track) {
for b in branches.iter_mut() {
b.track = compare_to(base, &b.name)?;
}
}
if o.json {
let mut w = pager::out();
for b in &branches {
let mut o = Obj::new();
o.str("name", &b.name)
.bool("current", b.current)
.num("date", b.ts)
.str("author", &b.author)
.str_opt("track", &b.track)
.str("subject", &b.subject);
writeln!(w, "{}", o.finish())?;
}
return w.finish();
}
let name_w = branches
.iter()
.map(|b| b.name.chars().count())
.max()
.unwrap_or(10)
.clamp(10, 40);
let track_w = branches
.iter()
.map(|b| b.track.chars().count())
.max()
.unwrap_or(0)
.min(20);
let now = gitlimes::fmt::now_secs();
let stale_cutoff = o.stale_days.map(|d| now - i64::from(d) * 86_400);
let mut w = pager::out();
for b in &branches {
let stale = stale_cutoff.is_some_and(|cut| b.ts < cut);
let marker = if b.current {
format!("{}*{}", c(CYAN), c(RESET))
} else {
" ".to_string()
};
let name_color = if b.current {
BOLD
} else if b.name.contains('/') && o.all {
RED
} else {
GREEN
};
write!(
w,
"{} {}{}{} {}{}{} {}{}{}",
marker,
c(name_color),
fit(&b.name, name_w),
c(RESET),
c(DIM),
fit(&rel_compact(b.ts), 5),
c(RESET),
c(CYAN),
fit(&b.author, 18),
c(RESET),
)?;
if track_w > 0 {
write!(w, " {}{}{}", c(YELLOW), fit(&b.track, track_w), c(RESET))?;
}
if stale {
write!(w, " {}stale{}", c(RED), c(RESET))?;
}
writeln!(w, " {}{}{}", c(DIM), b.subject, c(RESET))?;
}
w.finish()
}
fn clean_track(track: &str) -> String {
let t = track.trim();
let t = t.strip_prefix('[').unwrap_or(t);
let t = t.strip_suffix(']').unwrap_or(t);
t.to_string()
}
fn describe(ahead: &str, behind: &str) -> String {
match (ahead, behind) {
("0", "0") => String::new(),
(a, "0") => format!("ahead {}", a),
("0", b) => format!("behind {}", b),
(a, b) => format!("ahead {}, behind {}", a, b),
}
}
fn compare_to(base: &str, branch: &str) -> io::Result<String> {
let range = format!("{}...{}", base, branch);
let out = repo::capture(&["rev-list", "--left-right", "--count", &range, "--"])?;
let mut n = out.split_whitespace();
let behind = n.next().unwrap_or("0");
let ahead = n.next().unwrap_or("0");
Ok(describe(ahead, behind))
}