use crate::{
git::{self, Opts},
history::{self, LogEntry},
input,
model::Config,
policy, repo_state, safety, screen,
ui::{self, Choice, DiffChoice, Key},
};
use anyhow::{anyhow, bail, Result};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::time::{Duration, Instant};
const BATCH: usize = 300;
const SLOW_FIRST_BATCH: Duration = Duration::from_secs(2);
const SHOW_CAP: usize = 5000;
const PICKAXE_TIMEOUT: Duration = Duration::from_secs(30);
const PAGE_TIMEOUT: Duration = Duration::from_secs(120);
const STREAM_TIMEOUT: Duration = Duration::from_secs(60 * 60 * 24 * 365);
const QP: [&str; 2] = ["-c", "core.quotepath=false"];
#[derive(Debug, Clone, PartialEq, Eq)]
enum Pickaxe {
S(String),
G(String),
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Query {
graph: bool,
all: bool,
first_parent: bool,
author: Option<String>,
since: Option<String>,
until: Option<String>,
path: Option<String>,
grep: Option<String>,
pickaxe: Option<Pickaxe>,
skip: usize,
max_count: Option<usize>,
}
fn build_log_args(q: &Query) -> Vec<String> {
let mut a: Vec<String> = QP.iter().map(|s| s.to_string()).collect();
a.extend(["-c", "color.ui=never", "--no-pager", "log"].map(String::from));
if q.graph {
a.push("--graph".into());
}
a.extend(
[
"--date-order",
"--no-color",
"--no-show-signature",
"--no-ext-diff",
"--decorate-refs-exclude=refs/gct/*",
]
.map(String::from),
);
a.push(format!("--format=%x1e{}", history::LOG_FORMAT));
if q.first_parent {
a.push("--first-parent".into());
}
let mut value = |flag: &str, v: &Option<String>| {
if let Some(v) = v {
a.push(format!("{flag}{v}"));
}
};
value("--author=", &q.author);
value("--since=", &q.since);
value("--until=", &q.until);
if let Some(grep) = &q.grep {
a.push(format!("--grep={grep}"));
a.push("-i".into());
}
match &q.pickaxe {
Some(Pickaxe::S(text)) => a.push(format!("-S{text}")),
Some(Pickaxe::G(text)) => a.push(format!("-G{text}")),
None => {}
}
if !q.graph {
if q.skip > 0 {
a.push(format!("--skip={}", q.skip));
}
if let Some(n) = q.max_count {
a.push(format!("--max-count={n}"));
}
}
if q.all {
a.push("--exclude=refs/gct/*".into());
a.push("--all".into());
} else {
a.push("HEAD".into());
}
if let Some(path) = &q.path {
a.push("--".into());
a.push(path.clone());
}
a
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Row {
graph: String,
commit: Option<LogEntry>,
}
fn parse_graph_line(line: &str) -> Row {
match line.split_once('\u{1e}') {
None => Row {
graph: line.trim_end().to_string(),
commit: None,
},
Some((graph, rest)) => Row {
graph: graph.trim_end().to_string(),
commit: history::parse_log(rest).into_iter().next(),
},
}
}
fn commit_index(rows: &[Row], i: usize) -> Option<usize> {
let has = |j: &usize| rows[*j].commit.is_some();
(i.min(rows.len())..rows.len())
.find(has)
.or_else(|| (0..i.min(rows.len())).rev().find(has))
}
fn stream_rows(
args: &[String],
batch: usize,
cancel: Option<&AtomicBool>,
rows: &mut Vec<Row>,
on_batch: &mut dyn FnMut(&mut Vec<Row>) -> bool,
) -> Result<git::Out> {
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let opts = Opts {
timeout: Some(STREAM_TIMEOUT),
cancel,
..Opts::default()
};
let mut count = 0usize;
git::git_stream(&args, &opts, &mut |line| {
let row = parse_graph_line(&String::from_utf8_lossy(line));
let is_commit = row.commit.is_some();
rows.push(row);
if is_commit {
count += 1;
if count.is_multiple_of(batch) {
return on_batch(rows);
}
}
true
})
}
fn fetch_page(args: &[String], timeout: Duration, cancel: &AtomicBool) -> Result<Vec<Row>> {
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let opts = Opts {
timeout: Some(timeout),
cancel: Some(cancel),
max_lines: Some(BATCH * 2),
..Opts::default()
};
let mut rows = Vec::new();
let out = git::git_stream(&args, &opts, &mut |line| {
rows.push(parse_graph_line(&String::from_utf8_lossy(line)));
true
})?;
if out.cancelled {
bail!(input::CANCELLED);
}
if !out.ok() && !out.truncated {
bail!("{}", out.stderr.trim());
}
Ok(rows)
}
fn parse_shortlog(text: &str) -> Vec<(u64, String)> {
text.lines()
.filter_map(|line| {
let (count, who) = line.trim_start().split_once('\t')?;
Some((count.trim().parse().ok()?, who.trim().to_string()))
})
.collect()
}
fn clipboard_cmd(os: &str) -> Vec<(&'static str, &'static [&'static str])> {
match os {
"windows" => vec![("clip.exe", &[])],
"macos" => vec![("pbcopy", &[])],
"linux" | "freebsd" | "openbsd" | "netbsd" => {
vec![("wl-copy", &[]), ("xclip", &["-selection", "clipboard"])]
}
_ => Vec::new(),
}
}
fn base64(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for chunk in data.chunks(3) {
let b = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
for i in 0..4 {
if i <= chunk.len() {
out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
fn copy_to_clipboard(text: &str) -> bool {
use std::io::Write;
use std::process::{Command, Stdio};
clipboard_cmd(std::env::consts::OS)
.into_iter()
.any(|(program, args)| {
let Ok(mut child) = Command::new(program)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
else {
return false;
};
let wrote = child
.stdin
.take()
.is_some_and(|mut pipe| pipe.write_all(text.as_bytes()).is_ok());
let started = Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) => return wrote && status.success(),
Ok(None) if started.elapsed() < Duration::from_secs(3) => {
std::thread::sleep(Duration::from_millis(20))
}
_ => {
let _ = child.kill();
let _ = child.wait();
return false;
}
}
}
})
}
fn copy_hash(hash: &str) -> Result<()> {
let copied = copy_to_clipboard(hash);
if !copied {
use std::io::Write;
let mut out = std::io::stdout();
let _ = write!(out, "\x1b]52;c;{}\x07", base64(hash.as_bytes()));
let _ = out.flush();
screen::invalidate();
}
let status = if copied {
screen::success("Copied to the clipboard.")
} else {
screen::warning("Could not reach a clipboard program; select and copy it by hand:")
};
ui::notice(
"Commit hash",
&[status, String::new(), screen::accent(hash)],
)
}
fn qp<'a>(args: &[&'a str]) -> Vec<&'a str> {
QP.iter().copied().chain(args.iter().copied()).collect()
}
fn files_changed(lines: &[String]) -> Option<usize> {
lines.iter().find_map(|line| {
let line = line.trim();
let (n, rest) = line.split_once(' ')?;
(rest.starts_with("file changed") || rest.starts_with("files changed"))
.then(|| n.parse().ok())
.flatten()
})
}
fn show_lines(rev: &str, first_parent: bool, new_git: bool) -> Result<Vec<String>> {
if rev.starts_with('-') {
bail!("'{rev}' is not a revision");
}
let mut args = qp(&[
"--no-pager",
"show",
"--stat",
"--patch",
"-M",
"--format=fuller",
"--no-color",
"--no-ext-diff",
]);
match (first_parent, new_git) {
(false, _) => args.push("--cc"),
(true, true) => args.push("--diff-merges=first-parent"),
(true, false) => args.extend(["-m", "--first-parent"]),
}
args.extend([rev, "--"]);
let opts = Opts {
max_lines: Some(SHOW_CAP),
..Opts::default()
};
let mut lines = Vec::new();
let out = git::git_stream(&args, &opts, &mut |line| {
lines.push(String::from_utf8_lossy(line).into_owned());
true
})?;
if out.truncated {
let n = files_changed(&lines).map_or("many".to_string(), |n| n.to_string());
lines.push(String::new());
lines.push(format!(
"(truncated: {n} files changed; narrow with a path filter)"
));
} else if !out.ok() {
bail!("{}", out.stderr.trim());
}
Ok(lines)
}
pub fn show(cfg: &mut Config, rev: &str) -> Result<()> {
let _ = cfg;
let new_git = git::version().is_ok_and(|v| v >= (2, 31, 0));
let keys = [
Key {
key: 'm',
label: "merge: first-parent diff",
},
Key {
key: 'y',
label: "copy hash",
},
];
let mut first_parent = false;
loop {
let rev_owned = rev.to_string();
let lines = match ui::git_job("Loading commit", move || {
show_lines(&rev_owned, first_parent, new_git)
}) {
Ok(lines) => lines,
Err(e) if input::is_cancel(&e) || e.is::<ui::JobPanic>() => return Err(e),
Err(e) => {
return ui::notice(
"Could not show the commit",
&[screen::danger(format!("{e:#}"))],
)
}
};
let title = if first_parent {
format!("Commit {rev} (first-parent diff)")
} else {
format!("Commit {rev}")
};
match ui::diff_view(&title, &lines, &keys)? {
DiffChoice::Action('m', _) => first_parent = !first_parent,
DiffChoice::Action('y', _) => {
let oid = git::git_ok(
&qp(&["rev-parse", "--verify", "-q", &format!("{rev}^{{commit}}")]),
&Opts::default(),
)
.unwrap_or_else(|_| rev.to_string());
copy_hash(&oid)?;
}
_ => return Ok(()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Apply {
Revert,
Pick,
}
fn apply_args(kind: Apply, oid: &str, mainline: Option<usize>) -> Vec<String> {
let mut a: Vec<String> = match kind {
Apply::Revert => vec!["revert".into(), "--no-edit".into()],
Apply::Pick => vec!["cherry-pick".into(), "-x".into()],
};
if let Some(n) = mainline {
a.push("-m".into());
a.push(n.to_string());
}
a.push(oid.to_string());
a
}
#[derive(Debug, PartialEq, Eq)]
enum Outcome {
Done(String),
Conflicts(String),
}
fn run_apply(kind: Apply, oid: &str, mainline: Option<usize>) -> Result<Outcome> {
let args = apply_args(kind, oid, mainline);
let args = qp(&args.iter().map(String::as_str).collect::<Vec<_>>());
let out = git::git_raw(&args, &Opts::default())?;
let report = format!("{}\n{}", out.text(), out.stderr.trim())
.trim()
.to_string();
if out.ok() {
return Ok(Outcome::Done(report));
}
if repo_state::load().is_ok_and(|s| s.op.is_some()) {
return Ok(Outcome::Conflicts(report));
}
Err(anyhow!(
"{}",
if report.is_empty() {
"git failed".to_string()
} else {
report
}
))
}
fn report(result: Result<()>) -> Result<()> {
match result {
Err(e) if !input::is_cancel(&e) && !e.is::<ui::JobPanic>() => {
ui::notice("Log", &[screen::danger(format!("{e:#}"))])
}
other => other,
}
}
fn apply(cfg: &mut Config, kind: Apply, entry: &LogEntry) -> Result<bool> {
let name = if kind == Apply::Revert {
"Revert"
} else {
"Cherry-pick"
};
if let Some(op) = repo_state::load()?.op {
ui::notice(
name,
&[format!(
"A {op:?} is in progress. Finish or abort it first; opening Conflicts."
)],
)?;
crate::modes::open("conflicts", cfg)?;
return Ok(true);
}
let mut mainline = None;
if entry.parents.len() > 1 {
let options: Vec<String> = entry
.parents
.iter()
.enumerate()
.map(|(i, p)| format!("Parent {}: {}", i + 1, p.get(..10).unwrap_or(p)))
.collect();
let options: Vec<&str> = options.iter().map(String::as_str).collect();
let context = [format!(
"{} is a merge. Which parent is the mainline (usually 1)?",
entry.short
)];
match ui::choose(name, &context, &options)? {
Some(i) => mainline = Some(i + 1),
None => return Ok(false),
}
}
let command = format!("git {}", apply_args(kind, &entry.oid, mainline).join(" "));
let what = match kind {
Apply::Revert => format!(
"Create a new commit that undoes {} \"{}\"",
entry.short, entry.subject
),
Apply::Pick => format!(
"Copy {} \"{}\" onto the current branch",
entry.short, entry.subject
),
};
if !ui::gate(
cfg,
&policy::check(cfg, &policy::Op::CreatesCommit),
&what,
&command,
)? {
return Ok(false);
}
let oid = entry.oid.clone();
match ui::git_job(&format!("{name}..."), move || {
run_apply(kind, &oid, mainline)
})? {
Outcome::Done(text) => {
let mut lines = vec![screen::success(format!("Done: {command}")), String::new()];
lines.extend(text.lines().map(String::from));
lines.extend(ui::explain(
cfg,
&["A new commit was added on top; nothing was rewritten."],
));
ui::notice(name, &lines)?;
}
Outcome::Conflicts(text) => {
let mut lines = vec![
screen::warning(format!("Stopped with conflicts: {command}")),
String::new(),
];
lines.extend(text.lines().map(String::from));
ui::notice(name, &lines)?;
crate::modes::open("conflicts", cfg)?;
}
}
Ok(true)
}
fn orphaned_by_leaving(target: &str) -> Result<usize> {
let attached = git::git_raw(&["symbolic-ref", "-q", "HEAD"], &Opts::default())?;
if attached.ok() {
return Ok(0);
}
let out = git::git_ok(
&[
"rev-list",
"HEAD",
"--not",
"--branches",
"--tags",
"--remotes",
target,
"--",
],
&Opts::default(),
)?;
Ok(out.lines().filter(|l| !l.trim().is_empty()).count())
}
fn detach_exec(oid: &str) -> Result<Option<String>> {
if oid.starts_with('-') {
bail!("Invalid revision: {oid}");
}
let backup = if orphaned_by_leaving(oid)? > 0 {
Some(safety::backup("detached", "HEAD")?)
} else {
None
};
git::git_ok(&qp(&["switch", "--detach", oid]), &Opts::default())?;
Ok(backup)
}
fn checkout(cfg: &mut Config, entry: &LogEntry) -> Result<bool> {
let command = format!("git switch --detach {}", entry.oid);
let mut what = format!(
"Check out {} \"{}\" (detached HEAD: you are not on a branch)",
entry.short, entry.subject
);
let orphans = orphaned_by_leaving(&entry.oid)?;
if orphans > 0 {
what.push_str(&format!(
"\nWARNING: you are on a detached HEAD with {orphans} commit(s) that are on no branch. Moving away hides them; a backup ref is made first."
));
}
if !ui::confirm_action(cfg, &what, &command)? {
return Ok(false);
}
let backup = ui::git_job("Switching", {
let oid = entry.oid.clone();
move || detach_exec(&oid)
})?;
let mut context = vec![
screen::success(format!("Done: {command}")),
format!(
"HEAD is now detached at {}. New commits here belong to no branch.",
entry.short
),
];
if let Some(name) = backup {
context.push(screen::warning(format!(
"Your previous detached commits are saved as {name}"
)));
}
context.extend(ui::explain(
cfg,
&["Create a branch to keep work you make here."],
));
if ui::choose(
"Detached HEAD",
&context,
&["Create a branch here", "Stay detached"],
)? == Some(0)
{
crate::modes::branch::create_at(cfg, &entry.oid)?;
}
Ok(true)
}
fn contributors() -> Result<()> {
let args = qp(&["shortlog", "-sne", "--no-merges", "HEAD"]);
let out = ui::git_job_cancellable("Counting contributors", |cancel| {
let opts = Opts {
cancel: Some(cancel),
timeout: Some(PAGE_TIMEOUT),
..Opts::default()
};
git::git_ok(&args, &opts)
});
let text = match out {
Err(e) if input::is_cancel(&e) => return Ok(()),
other => other?,
};
let people = parse_shortlog(&text);
let mut lines = vec![
format!("{} people (merges not counted)", people.len()),
String::new(),
];
lines.extend(people.iter().map(|(n, who)| format!("{n:>7} {who}")));
ui::pager("Contributors", &lines, "")
}
const FILTERS: [&str; 8] = [
"Author (name or email)",
"Since (e.g. 2024-01-01, 2 weeks ago)",
"Until",
"Path (file or folder)",
"Message contains",
"Code text added/removed (-S, slow)",
"Code changed, regex (-G, slow)",
"Clear all filters",
];
fn edit_filters(q: &mut Query) -> Result<bool> {
let context = filter_summary(q);
let Some(choice) = ui::choose("Filters", &context, &FILTERS)? else {
return Ok(false);
};
if choice == 7 {
let keep = Query {
graph: q.graph,
all: q.all,
first_parent: q.first_parent,
..Query::default()
};
let changed = *q != keep;
*q = keep;
return Ok(changed);
}
let current = match (choice, &q.pickaxe) {
(0, _) => q.author.clone(),
(1, _) => q.since.clone(),
(2, _) => q.until.clone(),
(3, _) => q.path.clone(),
(4, _) => q.grep.clone(),
(5, Some(Pickaxe::S(t))) | (6, Some(Pickaxe::G(t))) => Some(t.clone()),
_ => None,
};
let initial = current.clone().unwrap_or_default();
let Some(answer) = ui::ask(
&format!("{} (clear the text to remove):", FILTERS[choice]),
&initial,
)?
else {
return Ok(false);
};
let mut value = Some(answer.trim().to_string()).filter(|v| !v.is_empty());
if choice == 3 && cfg!(windows) {
value = value.map(|p| p.replace('\\', "/"));
}
let changed = value != current;
match choice {
0 => q.author = value,
1 => q.since = value,
2 => q.until = value,
3 => q.path = value,
4 => q.grep = value,
5 => q.pickaxe = value.map(Pickaxe::S),
_ => q.pickaxe = value.map(Pickaxe::G),
}
Ok(changed)
}
fn filter_summary(q: &Query) -> Vec<String> {
let mut parts = Vec::new();
let mut add = |name: &str, v: &Option<String>| {
if let Some(v) = v {
parts.push(format!("{name}: {v}"));
}
};
add("author", &q.author);
add("since", &q.since);
add("until", &q.until);
add("path", &q.path);
add("message", &q.grep);
match &q.pickaxe {
Some(Pickaxe::S(t)) => parts.push(format!("-S {t}")),
Some(Pickaxe::G(t)) => parts.push(format!("-G {t}")),
None => {}
}
if parts.is_empty() {
vec![screen::muted("No filters.")]
} else {
vec![format!("Filters: {}", parts.join(" · "))]
}
}
struct Session {
query: Query,
index: usize,
notes: Vec<String>,
shallow: bool,
auto_off: bool,
patient: bool,
complete: bool,
}
enum Flow {
More,
Restart,
Quit,
}
const KEYS: [Key; 14] = [
Key {
key: 'v',
label: "view",
},
Key {
key: 'y',
label: "copy hash",
},
Key {
key: 'c',
label: "checkout",
},
Key {
key: 'r',
label: "revert",
},
Key {
key: 'p',
label: "cherry-pick",
},
Key {
key: 't',
label: "tag",
},
Key {
key: 'b',
label: "branch",
},
Key {
key: 'd',
label: "diff vs HEAD",
},
Key {
key: 'C',
label: "(shift) contributors",
},
Key {
key: 'f',
label: "filters",
},
Key {
key: 'g',
label: "graph",
},
Key {
key: 'a',
label: "all branches",
},
Key {
key: '1',
label: "first-parent",
},
Key {
key: 'n',
label: "more",
},
];
const MENU: [(&str, char); 15] = [
("Show commit", 'v'),
("Copy hash", 'y'),
("Check out (detached HEAD)", 'c'),
("Revert (new commit that undoes it)", 'r'),
("Cherry-pick onto the current branch", 'p'),
("Tag here", 't'),
("Branch here", 'b'),
("Compare with HEAD", 'd'),
("Contributors", 'C'),
("Filters...", 'f'),
("Graph on/off", 'g'),
("All branches on/off", 'a'),
("First-parent only on/off", '1'),
("Load 300 more", 'n'),
("Refresh", 'R'),
];
fn render(rows: &[Row]) -> Vec<String> {
let width = rows
.iter()
.map(|r| r.graph.chars().count())
.max()
.unwrap_or(0)
.min(40);
rows.iter()
.map(|row| {
let graph = format!("{:<width$}", row.graph);
let Some(c) = &row.commit else {
return screen::muted(graph);
};
let refs = if c.refs.is_empty() {
String::new()
} else {
format!(" {}", screen::tag(&c.refs))
};
format!(
"{graph} {} {} {}{refs} {}",
screen::accent(&c.short),
screen::muted(c.author_date.get(..10).unwrap_or(&c.author_date)),
c.subject,
screen::muted(&c.author)
)
})
.collect()
}
fn browse(cfg: &mut Config, s: &mut Session, rows: &[Row]) -> Result<Flow> {
loop {
let commits = rows.iter().filter(|r| r.commit.is_some()).count();
let q = &s.query;
let mut header = vec![format!(
"{} commits{} · graph {} · {} · {}",
commits,
if s.complete { "" } else { " loaded" },
if q.graph { "on" } else { "off" },
if q.all {
"all branches"
} else {
"current branch"
},
if q.first_parent {
"first-parent only"
} else {
"all parents"
},
)];
header.extend(filter_summary(q));
if s.shallow {
header.push(screen::warning(
"Shallow clone: older history is missing (git fetch --unshallow).",
));
}
if s.auto_off && !q.graph {
header.push(screen::warning(
"Graph off: the first 300 commits took over 2 s (big repository). Press G to turn it back on.",
));
}
header.extend(s.notes.iter().cloned());
let mut list = render(rows);
if !s.complete {
list.push(screen::muted(
"-- more: press N or Enter here to load 300 more --",
));
} else if commits == 0 {
list.push(screen::muted(
"No commits match. Press F to change the filters.",
));
}
let (key, i) = match ui::action_list("Log", &header, &list, &KEYS, &mut s.index)? {
Choice::Back => return Ok(Flow::Quit),
Choice::Open(i) if i >= rows.len() => ('n', i),
Choice::Open(i) => {
let options: Vec<&str> = MENU.iter().map(|(label, _)| *label).collect();
let context = commit_index(rows, i)
.and_then(|c| rows[c].commit.as_ref())
.map(|c| vec![format!("{} {}", screen::accent(&c.short), c.subject)])
.unwrap_or_default();
match ui::choose("Commit", &context, &options)? {
Some(m) => (MENU[m].1, i),
None => continue,
}
}
Choice::Action(key, i) => (key, i),
};
let entry = commit_index(rows, i).and_then(|c| rows[c].commit.clone());
if let Some(flow) = act(cfg, s, key, entry.as_ref())? {
return Ok(flow);
}
}
}
fn act(
cfg: &mut Config,
s: &mut Session,
key: char,
entry: Option<&LogEntry>,
) -> Result<Option<Flow>> {
let q = &mut s.query;
match key {
'n' if s.complete => {
ui::notice("Log", &["That is the whole history for this view.".into()])?
}
'n' => return Ok(Some(Flow::More)),
'R' => return Ok(Some(Flow::Restart)),
'g' => {
q.graph = !q.graph;
s.patient = q.graph;
return Ok(Some(Flow::Restart));
}
'a' => {
q.all = !q.all;
return Ok(Some(Flow::Restart));
}
'1' => {
q.first_parent = !q.first_parent;
return Ok(Some(Flow::Restart));
}
'f' => {
if edit_filters(q)? {
return Ok(Some(Flow::Restart));
}
}
'C' => contributors()?,
_ => {
let Some(e) = entry else { return Ok(None) };
let changed = match key {
'v' => report(show(cfg, &e.oid)).map(|()| false),
'y' => copy_hash(&e.oid).map(|()| false),
'c' => checkout(cfg, e),
'r' => apply(cfg, Apply::Revert, e),
'p' => apply(cfg, Apply::Pick, e),
't' => crate::modes::tag::create_at(cfg, &e.oid).map(|()| true),
'b' => crate::modes::branch::create_at(cfg, &e.oid).map(|()| true),
'd' => crate::modes::compare::open(cfg, "HEAD", &e.oid).map(|()| false),
_ => Ok(false),
};
match changed {
Ok(true) => return Ok(Some(Flow::Restart)),
Ok(false) => {}
Err(e) => report(Err(e))?,
}
}
}
Ok(None)
}
const PENDING: u8 = 0;
const FIRST: u8 = 1;
const SLOW: u8 = 2;
fn browse_graph(cfg: &mut Config, s: &mut Session) -> Result<Flow> {
let args = build_log_args(&s.query);
let state = AtomicU8::new(if s.patient { FIRST } else { PENDING });
let cancel = AtomicBool::new(false);
let finished = AtomicBool::new(false);
let started = Instant::now();
let mut rows = Vec::new();
let mut flow: Option<Result<Flow>> = None;
s.complete = false;
screen::draw(
&[screen::accent("Reading history...")],
"Please wait...",
None,
)?;
let out = std::thread::scope(|scope| {
scope.spawn(|| {
while state.load(Ordering::Acquire) == PENDING
&& !finished.load(Ordering::Acquire)
&& started.elapsed() < SLOW_FIRST_BATCH
{
std::thread::sleep(Duration::from_millis(20));
}
if state
.compare_exchange(PENDING, SLOW, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
cancel.store(true, Ordering::Release);
}
});
let out = stream_rows(&args, BATCH, Some(&cancel), &mut rows, &mut |rows| {
if state
.compare_exchange(PENDING, FIRST, Ordering::AcqRel, Ordering::Acquire)
.is_err()
&& state.load(Ordering::Acquire) == SLOW
{
return false;
}
match browse(cfg, s, rows) {
Ok(Flow::More) => true,
other => {
flow = Some(other);
false
}
}
});
finished.store(true, Ordering::Release);
out
});
if let Some(flow) = flow {
return flow;
}
let out = out?;
if state.load(Ordering::Acquire) == SLOW && !out.ok() {
s.query.graph = false;
s.auto_off = true;
return Ok(Flow::Restart);
}
s.complete = true;
if !out.ok() && !out.truncated {
s.notes.push(screen::danger(format!(
"git log failed: {}",
out.stderr.trim()
)));
}
loop {
match browse(cfg, s, &rows)? {
Flow::More => continue,
other => return Ok(other),
}
}
}
fn browse_paged(cfg: &mut Config, s: &mut Session) -> Result<Flow> {
let mut rows: Vec<Row> = Vec::new();
s.complete = false;
loop {
let mut q = s.query.clone();
q.graph = false;
q.skip = rows.iter().filter(|r| r.commit.is_some()).count();
q.max_count = Some(BATCH);
let args = build_log_args(&q);
let timeout = if q.pickaxe.is_some() {
PICKAXE_TIMEOUT
} else {
PAGE_TIMEOUT
};
match ui::git_job_cancellable("Reading history (Esc cancels)", |cancel| {
fetch_page(&args, timeout, cancel)
}) {
Ok(page) => {
s.complete = page.iter().filter(|r| r.commit.is_some()).count() < BATCH;
rows.extend(page);
}
Err(e) if e.is::<ui::JobPanic>() => return Err(e),
Err(e) => {
s.complete = true;
let why = if input::is_cancel(&e) {
"Search cancelled.".to_string()
} else {
format!("{e:#}")
};
s.notes.push(screen::warning(format!(
"Stopped: {why} Narrow the filters (F)."
)));
}
}
match browse(cfg, s, &rows)? {
Flow::More => continue,
other => return Ok(other),
}
}
}
fn has_commits() -> bool {
git::git_raw(
&qp(&["rev-parse", "--verify", "-q", "HEAD"]),
&Opts::default(),
)
.is_ok_and(|o| o.ok())
}
fn is_shallow() -> bool {
git::git_raw(
&qp(&["rev-parse", "--is-shallow-repository"]),
&Opts::default(),
)
.is_ok_and(|o| o.ok() && o.text() == "true")
}
pub fn run(config: &mut Config) -> Result<()> {
if !has_commits() {
return ui::notice(
"Log",
&[
"No commits yet.".into(),
String::new(),
"Make your first commit (Commit mode), then come back.".into(),
],
);
}
let mut s = Session {
query: Query {
graph: true,
..Query::default()
},
index: 0,
notes: Vec::new(),
shallow: is_shallow(),
auto_off: false,
patient: false,
complete: false,
};
loop {
s.notes.clear();
let flow = if s.query.graph && s.query.pickaxe.is_none() {
browse_graph(config, &mut s)?
} else {
browse_paged(config, &mut s)?
};
if let Flow::Quit = flow {
return Ok(());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
fn line(graph: &str, oid: &str, parents: &str, subject: &str) -> String {
format!(
"{graph}\u{1e}{oid}\u{1f}{short}\u{1f}{parents}\u{1f}Ann\u{1f}a@x\u{1f}2024-01-01T00:00:00+00:00\u{1f}d\u{1f}\u{1f}{subject}\u{1e}",
short = &oid[..1]
)
}
#[test]
fn parses_graph_lines() {
let row = parse_graph_line(&line("* ", "a1", "b2", "linear"));
assert_eq!(row.graph, "*");
let c = row.commit.unwrap();
assert_eq!(
(c.oid.as_str(), c.parents.len(), c.subject.as_str()),
("a1", 1, "linear")
);
let merge = parse_graph_line(&line("* ", "m", "p1 p2", "Merge x"));
assert_eq!(merge.commit.unwrap().parents, ["p1", "p2"]);
let octopus = parse_graph_line(&line("*-. ", "o", "p1 p2 p3", "oct"));
assert_eq!(octopus.commit.unwrap().parents.len(), 3);
let root = parse_graph_line(&line("* ", "r", "", "root"));
assert!(root.commit.unwrap().parents.is_empty());
let empty = parse_graph_line(&line("| * ", "e", "p", ""));
assert_eq!(empty.graph, "| *");
assert_eq!(empty.commit.unwrap().subject, "");
let tricky = parse_graph_line(&line("* ", "t", "p", "a | b * c \\ /"));
assert_eq!(tricky.graph, "*");
assert_eq!(tricky.commit.unwrap().subject, "a | b * c \\ /");
for connector in ["|\\", "| | ", "|/", "| * |", "", "|\\ \\"] {
let row = parse_graph_line(connector);
assert!(row.commit.is_none(), "{connector}");
assert_eq!(row.graph, connector.trim_end());
}
assert!(parse_graph_line(&line("", "x", "", "s")).commit.is_some());
assert!(parse_graph_line("* \u{1e}garbage\u{1e}").commit.is_none());
}
#[test]
fn selection_skips_connectors() {
let rows = vec![
parse_graph_line(&line("* ", "a", "", "a")),
parse_graph_line("|\\"),
parse_graph_line(&line("| * ", "b", "", "b")),
parse_graph_line("|/"),
];
assert_eq!(commit_index(&rows, 0), Some(0));
assert_eq!(commit_index(&rows, 1), Some(2));
assert_eq!(commit_index(&rows, 3), Some(2));
assert_eq!(commit_index(&rows, 9), Some(2));
assert_eq!(commit_index(&[], 0), None);
}
#[test]
fn log_args_table() {
let fmt = format!("--format=%x1e{}", history::LOG_FORMAT);
let base = |extra: &[&str], tail: &[&str], graph: bool| {
let mut v: Vec<String> = [
"-c",
"core.quotepath=false",
"-c",
"color.ui=never",
"--no-pager",
"log",
]
.map(String::from)
.to_vec();
if graph {
v.push("--graph".into());
}
v.extend(
[
"--date-order",
"--no-color",
"--no-show-signature",
"--no-ext-diff",
"--decorate-refs-exclude=refs/gct/*",
]
.map(String::from),
);
v.push(fmt.clone());
v.extend(extra.iter().map(|s| s.to_string()));
v.extend(tail.iter().map(|s| s.to_string()));
v
};
let g = Query {
graph: true,
..Query::default()
};
let cases: Vec<(Query, Vec<String>)> = vec![
(g.clone(), base(&[], &["HEAD"], true)),
(
Query {
all: true,
..g.clone()
},
base(&[], &["--exclude=refs/gct/*", "--all"], true),
),
(
Query {
first_parent: true,
..g.clone()
},
base(&["--first-parent"], &["HEAD"], true),
),
(
Query {
author: Some("Ann B".into()),
..g.clone()
},
base(&["--author=Ann B"], &["HEAD"], true),
),
(
Query {
since: Some("2 weeks ago".into()),
until: Some("2024-01-01".into()),
..g.clone()
},
base(
&["--since=2 weeks ago", "--until=2024-01-01"],
&["HEAD"],
true,
),
),
(
Query {
grep: Some("fix".into()),
..g.clone()
},
base(&["--grep=fix", "-i"], &["HEAD"], true),
),
(
Query {
path: Some("-odd dir/a.rs".into()),
..g.clone()
},
base(&[], &["HEAD", "--", "-odd dir/a.rs"], true),
),
(
Query {
pickaxe: Some(Pickaxe::S("-x".into())),
..Query::default()
},
base(&["-S-x"], &["HEAD"], false),
),
(
Query {
pickaxe: Some(Pickaxe::G("fn \\w+".into())),
skip: 300,
max_count: Some(300),
..Query::default()
},
base(
&["-Gfn \\w+", "--skip=300", "--max-count=300"],
&["HEAD"],
false,
),
),
(
Query {
skip: 5,
max_count: Some(3),
..g.clone()
},
base(&[], &["HEAD"], true),
),
(
Query {
max_count: Some(3),
..Query::default()
},
base(&["--max-count=3"], &["HEAD"], false),
),
(
Query {
graph: true,
all: true,
first_parent: true,
author: Some("a".into()),
grep: Some("g".into()),
path: Some("p".into()),
..Query::default()
},
base(
&["--first-parent", "--author=a", "--grep=g", "-i"],
&["--exclude=refs/gct/*", "--all", "--", "p"],
true,
),
),
];
for (query, expected) in cases {
assert_eq!(build_log_args(&query), expected, "{query:?}");
}
}
#[test]
fn shortlog_clipboard_and_helpers() {
let text = " 12\tAnn Lee <ann@x.io>\r\n 3\tZoë <z@x>\n\nbad line\n";
assert_eq!(
parse_shortlog(text),
[
(12, "Ann Lee <ann@x.io>".to_string()),
(3, "Zoë <z@x>".to_string())
]
);
assert!(parse_shortlog("").is_empty());
assert_eq!(clipboard_cmd("windows")[0].0, "clip.exe");
assert_eq!(clipboard_cmd("macos")[0].0, "pbcopy");
let linux = clipboard_cmd("linux");
assert_eq!(linux[0].0, "wl-copy");
assert_eq!(linux[1], ("xclip", &["-selection", "clipboard"][..]));
assert!(clipboard_cmd("plan9").is_empty());
assert_eq!(base64(b"abc"), "YWJj");
assert_eq!(base64(b"ab"), "YWI=");
assert_eq!(base64(b"a"), "YQ==");
let stat = [
" a | 1 +".to_string(),
" 12 files changed, 3 insertions(+)".to_string(),
];
assert_eq!(files_changed(&stat), Some(12));
assert_eq!(files_changed(&[" 1 file changed".to_string()]), Some(1));
assert_eq!(files_changed(&[]), None);
assert_eq!(
apply_args(Apply::Revert, "abc", Some(2)),
["revert", "--no-edit", "-m", "2", "abc"]
);
assert_eq!(
apply_args(Apply::Pick, "abc", None),
["cherry-pick", "-x", "abc"]
);
}
fn graph_args() -> Vec<String> {
build_log_args(&Query {
graph: true,
..Query::default()
})
}
#[test]
fn streams_first_batch_and_kills_git() {
let repo = TempRepo::new(5);
repo.run(|| {
let mut rows = Vec::new();
let mut batches = 0;
let out = stream_rows(&graph_args(), 2, None, &mut rows, &mut |rows| {
batches += 1;
assert_eq!(rows.iter().filter(|r| r.commit.is_some()).count(), 2);
false
})
.unwrap();
assert!(out.truncated && out.code.is_none());
assert_eq!(batches, 1);
assert_eq!(rows[0].commit.as_ref().unwrap().subject, "commit 5");
let started = Instant::now();
let mut all = Vec::new();
let out = stream_rows(&graph_args(), BATCH, None, &mut all, &mut |_| true).unwrap();
assert!(out.ok() && started.elapsed() < Duration::from_secs(10));
assert_eq!(all.iter().filter(|r| r.commit.is_some()).count(), 5);
assert!(all
.last()
.unwrap()
.commit
.as_ref()
.unwrap()
.parents
.is_empty());
});
}
#[test]
fn merge_history_parses_two_parents() {
let repo = TempRepo::new(2);
repo.git(&["switch", "-q", "-c", "side", "HEAD~1"]);
repo.write("side.txt", "s\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "side | * work"]);
repo.git(&["switch", "-q", "main"]);
repo.git(&["merge", "-q", "--no-ff", "--no-edit", "side"]);
let rows = repo.run(|| {
let mut rows = Vec::new();
stream_rows(&graph_args(), BATCH, None, &mut rows, &mut |_| true).unwrap();
rows
});
let commits: Vec<&LogEntry> = rows.iter().filter_map(|r| r.commit.as_ref()).collect();
assert_eq!(commits.len(), 4);
assert_eq!(commits[0].parents.len(), 2);
assert!(commits.iter().any(|c| c.subject == "side | * work"));
assert!(
rows.iter().any(|r| r.commit.is_none()),
"expected connector rows"
);
let page = repo.run(|| {
let q = Query {
max_count: Some(BATCH),
all: true,
..Query::default()
};
fetch_page(&build_log_args(&q), PAGE_TIMEOUT, &AtomicBool::new(false)).unwrap()
});
assert_eq!(page.len(), 4);
assert!(page
.iter()
.all(|r| r.commit.is_some() && r.graph.is_empty()));
}
#[test]
fn revert_creates_commit() {
let repo = TempRepo::new(3);
let head = repo.git(&["rev-parse", "HEAD"]);
let outcome = repo.run(|| run_apply(Apply::Revert, &head, None)).unwrap();
assert!(matches!(outcome, Outcome::Done(_)));
assert_eq!(repo.git(&["rev-list", "--count", "HEAD"]), "4");
assert!(!repo.path().join("f3.txt").exists());
assert!(repo
.run(|| run_apply(Apply::Revert, "nonexistent", None))
.is_err());
}
#[test]
fn cherry_pick_onto_other_branch() {
let repo = TempRepo::new(3);
let third = repo.git(&["rev-parse", "HEAD"]);
repo.git(&["switch", "-q", "-c", "other", "HEAD~2"]);
let outcome = repo.run(|| run_apply(Apply::Pick, &third, None)).unwrap();
assert!(matches!(outcome, Outcome::Done(_)));
assert!(repo.path().join("f3.txt").exists());
assert!(!repo.path().join("f2.txt").exists());
assert!(repo
.git(&["log", "-1", "--format=%B"])
.contains("cherry picked from commit"));
repo.write("f3.txt", "mine\n");
repo.git(&["commit", "-q", "-am", "mine"]);
repo.git(&["switch", "-q", "main"]);
repo.write("f3.txt", "theirs\n");
repo.git(&["commit", "-q", "-am", "theirs"]);
let theirs = repo.git(&["rev-parse", "HEAD"]);
repo.git(&["switch", "-q", "other"]);
let outcome = repo.run(|| run_apply(Apply::Pick, &theirs, None)).unwrap();
assert!(matches!(outcome, Outcome::Conflicts(_)));
}
#[test]
fn show_caps_huge_commit() {
let repo = TempRepo::new(1);
let big: String = (0..6000).map(|i| format!("line {i}\n")).collect();
repo.write("big.txt", &big);
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "huge"]);
let lines = repo.run(|| show_lines("HEAD", false, true)).unwrap();
assert_eq!(lines.len(), SHOW_CAP + 2);
assert_eq!(
lines.last().unwrap(),
"(truncated: 1 files changed; narrow with a path filter)"
);
let small = repo.run(|| show_lines("HEAD~1", true, false)).unwrap();
assert!(small.iter().any(|l| l.contains("commit 1")));
assert!(repo.run(|| show_lines("--evil", false, true)).is_err());
assert!(repo.run(|| show_lines("nope", false, true)).is_err());
}
#[test]
fn empty_and_shallow_checks() {
let empty = TempRepo::new(0);
assert!(!empty.run(has_commits));
assert!(!empty.run(is_shallow));
let repo = TempRepo::new(2);
assert!(repo.run(has_commits));
let shortlog = repo.run(|| {
git::git_ok(
&qp(&["shortlog", "-sne", "--no-merges", "HEAD"]),
&Opts::default(),
)
});
assert_eq!(
parse_shortlog(&shortlog.unwrap()),
[(2, "Test User <test@example.com>".to_string())]
);
}
#[test]
fn checkout_detaches_and_guards_orphans() {
let repo = TempRepo::new(3);
let first = repo.git(&["rev-parse", "HEAD~2"]);
let second = repo.git(&["rev-parse", "HEAD~1"]);
assert_eq!(repo.run(|| detach_exec(&first)).unwrap(), None);
assert_eq!(repo.git(&["rev-parse", "HEAD"]), first);
assert_eq!(repo.run(|| detach_exec(&second)).unwrap(), None);
repo.write("lost.txt", "x");
repo.git(&["add", "lost.txt"]);
repo.git(&["commit", "-qm", "orphan candidate"]);
let lost = repo.git(&["rev-parse", "HEAD"]);
assert_eq!(repo.run(|| orphaned_by_leaving(&first)).unwrap(), 1);
let backup = repo
.run(|| detach_exec(&first))
.unwrap()
.expect("backup name");
assert_eq!(repo.git(&["rev-parse", "HEAD"]), first);
assert!(backup.starts_with("refs/gct/backup/") && backup.ends_with("detached"));
assert_eq!(repo.git(&["rev-parse", &backup]), lost);
assert_eq!(repo.run(|| detach_exec(&lost)).unwrap(), None);
assert!(repo.run(|| detach_exec("--evil")).is_err());
}
}