use super::propose;
use std::io::Read;
use std::path::{Path, PathBuf};
use super::diff::{self, Diff, FileDiff, Hunk, Kind, Line, Status};
use super::forge::{self, PullRequest};
use super::project::Project;
use super::tree::Tree;
use super::{Options, Source, demo, desc, git, render, rules, session};
const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
pub struct Change {
pub root: PathBuf,
pub id: String,
pub revision: String,
pub title: String,
pub url: Option<String>,
pub checked_out: bool,
pub checkout: Option<String>,
pub description: String,
pub notes: Vec<String>,
pub report: render::Report,
pub files: Vec<FileDiff>,
pub pull: Option<(u64, String)>,
pub branch: Option<propose::Of>,
}
pub enum Loaded {
Change(Box<Change>),
Empty(String),
}
#[derive(Debug, PartialEq, Eq)]
pub enum Target {
Demo,
PullRequest(u64),
Name(String),
}
pub fn parse_target(text: &str, is_ref: impl Fn(&str) -> bool) -> Target {
let text = text.trim();
if text.eq_ignore_ascii_case("demo") {
return Target::Demo;
}
let number = |s: &str| s.parse::<u64>().ok().filter(|n| *n > 0 && s.bytes().all(|b| b.is_ascii_digit()));
for prefix in ["#", "pr/", "pr#", "!"] {
if let Some(n) = text.strip_prefix(prefix).and_then(number) {
return Target::PullRequest(n);
}
}
if text.starts_with("https://") || text.starts_with("http://") {
let mut parts = text.split(['?', '#']).next().unwrap_or("").split('/');
while let Some(p) = parts.next() {
if ["pull", "pulls", "merge_requests", "pull-requests"].contains(&p)
&& let Some(n) = parts.next().and_then(number)
{
return Target::PullRequest(n);
}
}
}
match number(text) {
Some(n) if text.len() < 7 && !is_ref(text) => Target::PullRequest(n),
_ => Target::Name(text.to_string()),
}
}
pub fn repository(cwd: &Path) -> Result<PathBuf, String> {
git::line(cwd, &["rev-parse", "--show-toplevel"])
.map(PathBuf::from)
.map_err(|_| format!("{} is not inside a git repository", cwd.display()))
}
pub fn default_base(root: &Path) -> Option<String> {
if let Ok(head) = git::line(root, &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]) {
return Some(head);
}
["origin/main", "origin/master", "main", "master", "develop"]
.into_iter()
.find(|b| git::commit_id(root, b).is_some())
.map(str::to_string)
}
fn git_diff(root: &Path, revisions: &[&str]) -> Result<Diff, String> {
let mut args = vec!["diff", "--no-color", "--no-ext-diff", "--no-textconv", "-M", "--unified=3", "--src-prefix=a/", "--dst-prefix=b/"];
args.extend(revisions);
args.push("--");
Ok(diff::parse(&git::output(root, &args)?))
}
fn untracked(root: &Path) -> Vec<FileDiff> {
let Ok(list) = git::output(root, &["ls-files", "--others", "--exclude-standard", "-z"]) else { return Vec::new() };
list.split('\0')
.filter(|p| !p.is_empty())
.take(500)
.map(|path| {
let full = root.join(path);
let text = std::fs::metadata(&full)
.ok()
.filter(|m| m.is_file() && m.len() < 1_000_000)
.and_then(|_| std::fs::read_to_string(&full).ok())
.filter(|t| !t.contains('\0'));
let lines = text.as_deref().map(|t| {
t.lines()
.enumerate()
.map(|(i, l)| Line { kind: Kind::Added, text: l.to_string(), old_no: None, new_no: Some(i as u32 + 1) })
.collect::<Vec<_>>()
});
FileDiff {
path: path.to_string(),
old_path: None,
status: Status::Added,
binary: text.is_none(),
old_mode: None,
new_mode: None,
hunks: lines.map(|lines| vec![Hunk { lines }]).unwrap_or_default(),
}
})
.collect()
}
pub fn read_input(cwd: &Path, path: &str) -> Result<String, String> {
let mut bytes = Vec::new();
if path == "-" {
std::io::stdin().read_to_end(&mut bytes).map_err(|e| format!("could not read stdin: {e}"))?;
} else {
bytes = std::fs::read(cwd.join(path)).map_err(|e| format!("could not read {path}: {e}"))?;
}
let text = match bytes.as_slice() {
[0xff, 0xfe, rest @ ..] => String::from_utf16_lossy(&rest.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect::<Vec<_>>()),
[0xef, 0xbb, 0xbf, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
_ => String::from_utf8_lossy(&bytes).into_owned(),
};
Ok(text)
}
struct Picked {
root: PathBuf,
id: String,
revision: Option<String>,
title: String,
against: String,
url: Option<String>,
diff: Diff,
tree: Tree,
description: Option<(String, String)>,
head: Option<String>,
checkout: Option<String>,
notes: Vec<String>,
empty: String,
pull: Option<(u64, String)>,
branch: Option<propose::Of>,
}
impl Picked {
fn new(root: &Path, id: String, title: String, against: String, diff: Diff) -> Picked {
Picked {
root: root.to_path_buf(),
id,
revision: None,
empty: format!("no changes in {against}"),
title,
against,
url: None,
diff,
tree: Tree::Disk(root.to_path_buf()),
description: None,
head: None,
checkout: None,
notes: Vec::new(),
pull: None,
branch: None,
}
}
fn at_commit(mut self, sha: &str) -> Result<Picked, String> {
self.tree = Tree::commit(&self.root, sha)?;
self.head = Some(sha.to_string());
self.revision = Some(sha.to_string());
Ok(self)
}
}
fn short(sha: &str) -> &str {
sha.get(..10).unwrap_or(sha)
}
fn commit_messages(root: &Path, range: &str) -> Option<(String, String)> {
git::output(root, &["log", "--reverse", "--format=%B", range, "--"])
.ok()
.filter(|m| !m.trim().is_empty())
.map(|m| (m, "commit messages".to_string()))
}
fn working_copy(root: &Path, source: &Source) -> Result<Picked, String> {
let (diff, id, title, against) = if *source == Source::Staged {
(git_diff(root, &["--cached"])?, "staged", "Staged changes", "staged changes")
} else {
let from = if git::commit_id(root, "HEAD").is_some() { "HEAD" } else { EMPTY_TREE };
let mut d = git_diff(root, &[from])?;
d.files.extend(untracked(root));
(d, "uncommitted", "Uncommitted changes", "uncommitted changes")
};
Ok(Picked::new(root, id.into(), title.into(), against.into(), diff))
}
fn branch(root: &Path, name: Option<&str>, base: Option<&str>) -> Result<Picked, String> {
let base = match base {
Some(b) => b.to_string(),
None => default_base(root).ok_or("cannot tell which branch to compare with; name it: review --base origin/main")?,
};
let shown = name.unwrap_or("HEAD");
let base_id = git::commit_id(root, &base).ok_or_else(|| format!("`{base}` is not a branch or commit here"))?;
let head_id = git::commit_id(root, shown).ok_or_else(|| format!("`{shown}` is not a branch or commit here"))?;
let current = git::line(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).ok();
let label = name.map(str::to_string).or_else(|| current.clone()).unwrap_or_else(|| "HEAD".into());
let diff = git_diff(root, &[&format!("{base_id}...{head_id}")])?;
let mut p = Picked::new(root, format!("branch {label}"), format!("Branch {label}"), format!("{base}...{label}"), diff);
p.empty = format!(
"`{label}` has no commits that `{base}` lacks. For work in progress use `review --uncommitted`; \
to compare the current branch with `{label}`, use `review --base {label}`"
);
p.description = commit_messages(root, &format!("{base_id}..{head_id}"));
let reference = match name {
Some(n) => git::line(root, &["rev-parse", "--verify", "--quiet", "--symbolic-full-name", "--end-of-options", n]).ok(),
None => current.as_ref().map(|c| format!("refs/heads/{c}")),
};
p.branch = reference.filter(|r| proposable(r, &base)).map(|name| propose::Of { name, base: Some(base.clone()) });
p.checkout = name.map(|n| match n.strip_prefix("origin/") {
Some(local) => format!("git switch {local}"),
None => format!("git switch {n}"),
});
p.at_commit(&head_id)
}
fn proposable(reference: &str, base: &str) -> bool {
let name = reference
.strip_prefix("refs/heads/")
.or_else(|| reference.strip_prefix("refs/remotes/").and_then(|r| r.split_once('/')).map(|(_, n)| n));
let base = base.strip_prefix("origin/").unwrap_or(base);
name.is_some_and(|n| n != base && n != "HEAD")
}
fn commit(root: &Path, id: &str) -> Result<Picked, String> {
let parent = git::commit_id(root, &format!("{id}^1")).unwrap_or_else(|| EMPTY_TREE.to_string());
let diff = git_diff(root, &[&parent, id])?;
let subject = git::line(root, &["log", "-1", "--format=%s", id, "--"])?;
let mut p = Picked::new(root, format!("commit {id}"), format!("{} {subject}", short(id)), format!("commit {}", short(id)), diff);
p.description = git::output(root, &["log", "-1", "--format=%B", id, "--"]).ok().map(|m| (m, "commit message".to_string()));
p.checkout = Some(format!("git switch --detach {}", short(id)));
p.at_commit(id)
}
fn named(root: &Path, name: &str, base: Option<&str>) -> Result<Picked, String> {
let full = git::line(root, &["rev-parse", "--verify", "--quiet", "--symbolic-full-name", "--end-of-options", name]).unwrap_or_default();
if full.starts_with("refs/heads/") || full.starts_with("refs/remotes/") {
if name != "HEAD" {
return branch(root, Some(name), base);
}
}
if let Some(id) = git::commit_id(root, name) {
return match base {
Some(b) => branch(root, Some(name), Some(b)),
None => commit(root, &id),
};
}
let remote = format!("origin/{name}");
if git::commit_id(root, &remote).is_some() {
return branch(root, Some(&remote), base);
}
Err(format!("`{name}` is not a pull request number, branch or commit (try `git fetch`, or `pr` to see what is there)"))
}
fn plain_ref(name: &str) -> bool {
!name.is_empty() && !name.contains("..") && !name.chars().any(|c| c.is_whitespace() || c.is_control() || ":*?[\\^~".contains(c))
}
fn fetch(root: &Path, remote: &str, specs: &[String]) -> Result<(), String> {
let mut args = vec!["fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--end-of-options", remote];
args.extend(specs.iter().map(String::as_str));
git::output(root, &args).map(|_| ())
}
fn pull_request(root: &Path, number: u64, base: Option<&str>) -> Result<Picked, String> {
let (remote, _) = forge::remote(root)?;
let local = |what: &str| format!("refs/rustimal/pr/{number}/{what}");
let head_spec = |from: &str| format!("+{from}:{}", local("head"));
let found = forge::pull_request(root, number);
let mut notes = Vec::new();
let info: Option<PullRequest> = match &found {
Ok((kind, pr)) => {
let from = match kind.head_ref(number) {
Some(r) => r,
None if plain_ref(&pr.head_branch) => format!("refs/heads/{}", pr.head_branch),
None => return Err(format!("pull request #{number} has no branch that can be fetched")),
};
let mut specs = vec![head_spec(&from)];
if plain_ref(&pr.base) {
specs.push(format!("+refs/heads/{}:{}", pr.base, local("base")));
}
fetch(root, &remote, &specs).map_err(|e| format!("could not fetch pull request #{number}: {e}"))?;
Some(pr.clone())
}
Err(why) => {
let kinds = [forge::Kind::GitHub, forge::Kind::GitLab, forge::Kind::BitbucketServer];
if !kinds.iter().filter_map(|k| k.head_ref(number)).any(|r| fetch(root, &remote, &[head_spec(&r)]).is_ok()) {
return Err(format!("could not get pull request #{number}: {why}"));
}
notes.push(format!("the title and description could not be read ({why}); the commit messages stand in"));
None
}
};
let head = git::commit_id(root, &local("head")).ok_or("the fetched pull request has no commit")?;
let (base_name, base_rev) = match (base, &info) {
(Some(b), _) => (b.to_string(), b.to_string()),
(None, Some(pr)) if plain_ref(&pr.base) => (pr.base.clone(), local("base")),
_ => {
let b = default_base(root).ok_or("cannot tell which branch the pull request goes into; add --base")?;
(b.clone(), b)
}
};
if let Some(pr) = &info
&& !pr.head_sha.is_empty()
&& !head.starts_with(&pr.head_sha)
{
notes.push(format!("the host says the pull request is at {}, but {} was fetched; reload in a moment", short(&pr.head_sha), short(&head)));
}
let base_id = git::commit_id(root, &base_rev).ok_or_else(|| format!("`{base_name}` is not a branch or commit here"))?;
let diff = git_diff(root, &[&format!("{base_id}...{head}")])?;
let title = match &info {
Some(pr) => format!("#{number} {}", pr.title),
None => format!("Pull request #{number}"),
};
let mut p = Picked::new(root, format!("pr {number}"), title, format!("{base_name}...#{number}"), diff);
p.empty = format!("pull request #{number} adds nothing to `{base_name}`; it may be merged already");
p.description = match &info {
Some(pr) => Some((pr.body.clone(), "PR description".to_string())).filter(|(b, _)| !b.trim().is_empty()),
None => commit_messages(root, &format!("{base_id}..{head}")),
};
p.url = info.map(|pr| pr.url).filter(|u| u.starts_with("https://"));
p.checkout = Some(format!("git switch --detach {}", short(&head)));
p.pull = Some((number, head.clone()));
p.notes = notes;
p.at_commit(&head)
}
fn demo_change() -> Result<Picked, String> {
let root = demo::create()?;
let mut p = branch(&root, Some(demo::BRANCH), Some("main"))?;
p.id = "demo".into();
p.title = demo::TITLE.into();
p.description = Some((demo::DESCRIPTION.into(), "PR description".into()));
p.checkout = None;
p.branch = None;
Ok(p)
}
fn pick(cwd: &Path, o: &Options) -> Result<Picked, String> {
if let Source::File(path) = &o.source {
let root = repository(cwd).unwrap_or_else(|_| cwd.to_path_buf());
let against = if path == "-" { "stdin".to_string() } else { path.clone() };
let diff = diff::parse(&read_input(cwd, path)?);
return Ok(Picked::new(&root, format!("diff {against}"), format!("Diff {against}"), against, diff));
}
if o.target.as_deref().is_some_and(|t| parse_target(t, |_| false) == Target::Demo) {
return demo_change();
}
let root = repository(cwd)?;
if o.source != Source::Branch {
return working_copy(&root, &o.source);
}
let base = o.base.as_deref();
match o.target.as_deref().map(|t| parse_target(t, |name| git::commit_id(&root, &format!("refs/heads/{name}")).is_some())) {
None => {
let mut p = branch(&root, None, base)?;
if git::output(&root, &["status", "--porcelain"]).is_ok_and(|s| !s.trim().is_empty()) {
p.notes.push("uncommitted changes are not part of this review (see --uncommitted)".into());
}
Ok(p)
}
Some(Target::Demo) => demo_change(),
Some(Target::PullRequest(n)) => pull_request(&root, n, base),
Some(Target::Name(name)) => named(&root, &name, base),
}
}
pub fn load(cwd: &Path, o: &Options) -> Result<Loaded, String> {
let p = pick(cwd, o)?;
if p.diff.files.is_empty() {
return Ok(Loaded::Empty(p.empty));
}
let given = match &o.desc {
Some(path) => Some((read_input(cwd, path)?, "PR description".to_string())),
None => p.description,
};
let description = given.as_ref().map(|(text, from)| desc::parse(text, from));
let project = Project::from_tree(p.tree);
let findings = rules::analyze(&rules::Cx { diff: &p.diff, project: &project, desc: description.as_ref() });
let report = render::Report {
against: p.against,
project: project.describe(),
files: p.diff.files.len(),
added: p.diff.added_count(),
removed: p.diff.removed_count(),
plan: render::plan(&findings),
described_steps: description.as_ref().and_then(|d| d.test_section()).map(|s| s.body.clone()).unwrap_or_default(),
findings,
};
let current = git::commit_id(&p.root, "HEAD");
let checked_out = p.head.is_none() || p.head == current || p.id == "demo";
let revision = p.revision.unwrap_or_else(|| session::fingerprint_diff(&p.diff));
Ok(Loaded::Change(Box::new(Change {
checkout: p.checkout.filter(|_| !checked_out),
root: p.root,
id: p.id,
revision,
title: p.title,
url: p.url,
checked_out,
description: given.map(|(text, _)| text).unwrap_or_default(),
notes: p.notes,
report,
files: p.diff.files,
pull: p.pull,
branch: p.branch,
})))
}
#[derive(Clone, Debug)]
pub struct Entry {
pub target: String,
pub title: String,
pub detail: String,
}
#[derive(Default)]
pub struct Local {
pub work: Vec<Entry>,
pub branches: Vec<Entry>,
pub commits: Vec<Entry>,
}
pub fn local(root: &Path) -> Local {
let mut out = Local::default();
let changed = git::output(root, &["status", "--porcelain"]).map_or(0, |s| s.lines().count());
if changed > 0 {
let detail = format!("{changed} changed {}", if changed == 1 { "file" } else { "files" });
out.work.push(Entry { target: "--uncommitted".into(), title: "Uncommitted changes".into(), detail });
}
let format = "--format=%(refname:short)%1f%(contents:subject)%1f%(committerdate:relative)%1f%(HEAD)";
if let Ok(list) = git::output(root, &["for-each-ref", "--sort=-committerdate", "--count=12", format, "refs/heads"]) {
out.branches = list
.lines()
.filter_map(|l| {
let mut f = l.split('\x1f');
let (name, subject, age, head) = (f.next()?, f.next()?, f.next()?, f.next()?);
let current = if head == "*" { "current · " } else { "" };
Some(Entry { target: name.into(), title: name.into(), detail: format!("{current}{age} · {subject}") })
})
.collect();
}
if let Ok(list) = git::output(root, &["log", "-n", "12", "--format=%h%x1f%s%x1f%cr%x1f%an", "--"]) {
out.commits = list
.lines()
.filter_map(|l| {
let mut f = l.split('\x1f');
let (id, subject, age, author) = (f.next()?, f.next()?, f.next()?, f.next()?);
Some(Entry { target: format!("{id}^{{commit}}"), title: format!("{id} {subject}"), detail: format!("{age} · {author}") })
})
.collect();
}
out
}
pub fn pull_request_entry(p: &PullRequest) -> Entry {
let draft = if p.draft { "draft · " } else { "" };
Entry {
target: format!("#{}", p.number),
title: format!("#{} {}", p.number, p.title),
detail: format!("{draft}{} · {} → {}", p.author, p.head_branch, p.base),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::review::testutil::Scratch;
#[test]
fn tells_pull_requests_from_branches_and_commits() {
let none = |_: &str| false;
for pr in ["12", "#12", "pr/12", "!12", "https://github.com/a/b/pull/12", "https://gl.example/a/b/-/merge_requests/12?x=1"] {
assert_eq!(parse_target(pr, none), Target::PullRequest(12), "{pr}");
}
assert_eq!(parse_target("1234567", none), Target::Name("1234567".into()), "a short commit id");
assert_eq!(parse_target("2024", |n| n == "2024"), Target::Name("2024".into()), "a branch of that name wins");
assert_eq!(parse_target("Demo", none), Target::Demo);
for name in ["main", "feature/12", "abc1234", "HEAD~2", "0", "#x"] {
assert_eq!(parse_target(name, none), Target::Name(name.into()), "{name}");
}
}
fn options(target: Option<&str>, base: Option<&str>) -> Options {
Options { target: target.map(Into::into), base: base.map(Into::into), ..Default::default() }
}
fn change(l: Result<Loaded, String>) -> Box<Change> {
match l.unwrap() {
Loaded::Change(c) => c,
Loaded::Empty(why) => panic!("{why}"),
}
}
#[test]
fn reviews_a_branch_or_a_commit_by_name() {
let s = Scratch::new("source-names");
git::testing::init(&s.0);
s.write("a.txt", "one\n");
git::testing::commit(&s.0, "first");
git::testing::run(&s.0, &["switch", "--quiet", "-c", "feature"]);
s.write("a.txt", "one\ntwo\n");
git::testing::commit(&s.0, "second");
s.write("b.txt", "three\n");
git::testing::commit(&s.0, "third");
git::testing::run(&s.0, &["switch", "--quiet", "main"]);
let c = change(load(&s.0, &options(Some("feature"), None)));
assert_eq!((c.report.files, c.report.added, c.id.as_str()), (2, 2, "branch feature"));
assert!(!c.checked_out);
assert_eq!(c.checkout.as_deref(), Some("git switch feature"));
let c = change(load(&s.0, &options(Some("feature~1"), None)));
assert_eq!((c.report.files, c.report.added), (1, 1));
assert!(c.title.ends_with(" second"), "{}", c.title);
let first = change(load(&s.0, &options(Some("HEAD"), None)));
assert!(first.checked_out && first.title.ends_with(" first"), "a first commit has no parent");
assert!(matches!(load(&s.0, &options(Some("main"), None)), Ok(Loaded::Empty(why)) if why.contains("--base main")));
assert!(load(&s.0, &options(Some("nope"), None)).is_err_and(|e| e.contains("`nope`")));
assert!(load(&s.0, &options(Some("--output=x"), None)).is_err(), "a name is never an option");
assert!(!s.0.join("x").exists());
let l = local(&s.0);
assert_eq!(l.branches.len(), 2);
assert_eq!(l.commits.len(), 1);
assert!(l.work.is_empty());
}
#[test]
fn hosted_branch_names_cannot_add_to_a_refspec() {
assert!(plain_ref("feature/x-1"));
for bad in ["", "a:refs/heads/main", "a b", "a..b", "*", "a^", "x\n"] {
assert!(!plain_ref(bad), "{bad:?}");
}
}
}