use std::path::{Path, PathBuf};
use super::forge::{self, NewPull, PullRequest};
use super::{git, source};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Of {
pub name: String,
pub base: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Proposal {
pub root: PathBuf,
pub reference: String,
pub remote: String,
pub host: String,
pub pull: NewPull,
pub sha: String,
pub commits: Vec<String>,
pub push: bool,
pub dirty: usize,
}
#[derive(Clone, Debug)]
pub enum Start {
Exists(Box<PullRequest>),
New(Box<Proposal>),
}
fn checked_out(root: &Path) -> Option<String> {
git::line(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).ok()
}
fn resolve(root: &Path, remote: &str, name: Option<&str>) -> Result<(String, String), String> {
let Some(name) = name else {
let branch = checked_out(root).ok_or("No branch is checked out. Name one: pr new BRANCH")?;
return Ok((format!("refs/heads/{branch}"), branch));
};
let full = |n: &str| {
git::line(root, &["rev-parse", "--verify", "--quiet", "--symbolic-full-name", "--end-of-options", n])
.ok()
.filter(|f| !f.is_empty())
};
let on_remote = format!("refs/remotes/{remote}/");
let reference = full(name)
.or_else(|| full(&format!("{remote}/{name}")))
.ok_or_else(|| format!("`{name}` is not a branch here"))?;
let branch = reference
.strip_prefix("refs/heads/")
.or_else(|| reference.strip_prefix(&on_remote))
.filter(|b| *b != "HEAD")
.ok_or_else(|| format!("`{name}` is not a local branch, or a branch of `{remote}`"))?
.to_string();
Ok((reference, branch))
}
fn base_branch(root: &Path, remote: &str, base: &str) -> Option<String> {
let name = [format!("refs/remotes/{remote}/"), format!("{remote}/"), "refs/heads/".to_string()]
.iter()
.find_map(|prefix| base.strip_prefix(prefix.as_str()))
.unwrap_or(base);
let known = [format!("refs/remotes/{remote}/{name}"), format!("refs/heads/{name}")]
.iter()
.any(|r| git::commit_id(root, r).is_some());
(known && name != "HEAD").then(|| name.to_string())
}
fn remote_tip(root: &Path, remote: &str, branch: &str) -> Result<Option<String>, String> {
let name = format!("refs/heads/{branch}");
let refs = git::output(root, &["ls-remote", "--refs", "--", remote, &name])?;
Ok(refs.lines().filter_map(|l| l.split_once('\t')).find(|(_, r)| *r == name).map(|(id, _)| id.to_string()))
}
fn needs_push(root: &Path, remote: &str, branch: &str, sha: &str) -> Result<bool, String> {
match remote_tip(root, remote, branch)? {
Some(tip) if tip == sha => Ok(false),
Some(tip) if git::output(root, &["merge-base", "--is-ancestor", &tip, sha]).is_err() => {
Err(format!("`{branch}` on the host has commits you don't have. Fetch and merge them first"))
}
_ => Ok(true),
}
}
fn title_from_branch(branch: &str) -> String {
let words = branch.rsplit('/').next().unwrap_or(branch).replace(['-', '_'], " ");
let mut chars = words.trim().chars();
chars.next().map_or_else(|| branch.to_string(), |first| first.to_uppercase().chain(chars).collect())
}
fn suggest(branch: &str, commits: &[(String, String)]) -> (String, String) {
match commits {
[(subject, body)] => (subject.clone(), body.trim().to_string()),
_ => {
let list: Vec<String> = commits.iter().map(|(subject, _)| format!("- {subject}")).collect();
(title_from_branch(branch), list.join("\n"))
}
}
}
fn read_log(log: &str) -> Vec<(String, String)> {
log.split('\0')
.filter(|entry| !entry.trim().is_empty())
.map(|entry| {
let (subject, body) = entry.split_once('\u{1}').unwrap_or((entry, ""));
(subject.trim().to_string(), body.replace('\r', ""))
})
.collect()
}
pub fn propose(cwd: &Path, of: Option<&Of>) -> Result<Start, String> {
let root = source::repository(cwd)?;
let (remote, at) = forge::remote(&root)?;
let (reference, branch) = resolve(&root, &remote, of.map(|o| o.name.as_str()))?;
let sha = git::commit_id(&root, &reference).ok_or_else(|| format!("`{branch}` has no commits yet"))?;
let host = at.ok_or_else(|| format!("the remote `{remote}` is not a hosted repository"))?.host;
let (_, open) = forge::list(&root)?;
if let Some(pull) = open.into_iter().find(|p| p.head_branch == branch) {
return Ok(Start::Exists(Box::new(pull)));
}
let base = of
.and_then(|o| o.base.as_deref())
.and_then(|b| base_branch(&root, &remote, b))
.or_else(|| source::default_base(&root).and_then(|b| base_branch(&root, &remote, &b)))
.ok_or("Cannot tell which branch pull requests merge into")?;
if base == branch {
return Err(format!(
"You are on `{branch}`, the branch pull requests merge into. Put your commits on a branch of \
their own first: in the Git view, `n` creates one and `m` moves commits to one"
));
}
let from = git::commit_id(&root, &format!("{remote}/{base}"))
.or_else(|| git::commit_id(&root, &base))
.ok_or_else(|| format!("Cannot find the branch `{base}`. Fetch first"))?;
let log = git::output(&root, &["log", "-z", "--reverse", "--format=%s%x01%b", &format!("{from}..{sha}"), "--"])?;
let commits = read_log(&log);
if commits.is_empty() {
return Err(format!("`{branch}` has no commits that `{base}` doesn't have"));
}
let push = needs_push(&root, &remote, &branch, &sha)?;
let dirty = if checked_out(&root).as_deref() == Some(branch.as_str()) {
git::output(&root, &["status", "--porcelain"])?.lines().count()
} else {
0
};
let (title, body) = suggest(&branch, &commits);
Ok(Start::New(Box::new(Proposal {
root,
reference,
remote,
host,
pull: NewPull { title, body, head: branch, base },
sha,
commits: commits.into_iter().map(|(subject, _)| subject).collect(),
push,
dirty,
})))
}
pub fn create(p: &Proposal) -> Result<(&'static str, PullRequest), String> {
let root = &p.root;
let NewPull { title, head, base, .. } = &p.pull;
if title.trim().is_empty() {
return Err("A pull request needs a title".into());
}
if base == head {
return Err("It can't merge a branch into itself".into());
}
git::output(root, &["check-ref-format", "--branch", base]).map_err(|_| format!("`{base}` is not a branch name"))?;
if git::commit_id(root, &p.reference).as_ref() != Some(&p.sha) {
return Err("The branch changed since this was drawn up. Press esc and start again".into());
}
if remote_tip(root, &p.remote, base)?.is_none() {
return Err(format!("The host has no branch `{base}` to merge into"));
}
let pushed = needs_push(root, &p.remote, head, &p.sha)?;
if pushed {
let refspec = format!("{}:refs/heads/{head}", p.sha);
git::output(root, &["push", "--porcelain", "--no-follow-tags", "--", &p.remote, &refspec])?;
if git::line(root, &["config", "--get", &format!("branch.{head}.merge")]).is_err() {
let upstream = format!("--set-upstream-to={}/{head}", p.remote);
let _ = git::output(root, &["branch", &upstream, head]);
}
}
forge::create(root, &p.pull).map_err(|e| if pushed { format!("The branch was pushed, but {e}") } else { e })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::review::git::testing::{commit, init, run};
use crate::review::testutil::Scratch;
#[test]
fn suggestions_come_from_the_commits() {
let one = read_log("Add search\u{1}Finds things.\r\nQuickly.\n\0");
assert_eq!(suggest("feature/x", &one), ("Add search".into(), "Finds things.\nQuickly.".into()));
let two = read_log("First\u{1}\0Second\u{1}body\n\0");
assert_eq!(suggest("feature/add-web_search", &two), ("Add web search".into(), "- First\n- Second".into()));
assert!(read_log("").is_empty());
assert_eq!(title_from_branch("árvíz"), "Árvíz");
}
#[test]
fn any_branch_can_be_named_and_not_only_the_one_checked_out() {
let s = Scratch::new("propose-names");
init(&s.0);
std::fs::write(s.0.join("file"), "1").unwrap();
commit(&s.0, "one");
run(&s.0, &["branch", "feature/other"]);
run(&s.0, &["update-ref", "refs/remotes/origin/fetched-only", "HEAD"]);
run(&s.0, &["update-ref", "refs/remotes/origin/main", "HEAD"]);
let named = |n: &str| resolve(&s.0, "origin", Some(n));
let local = ("refs/heads/feature/other".to_string(), "feature/other".to_string());
assert_eq!(named("feature/other").unwrap(), local);
assert_eq!(named("refs/heads/feature/other").unwrap(), local);
let fetched = ("refs/remotes/origin/fetched-only".to_string(), "fetched-only".to_string());
assert_eq!(named("origin/fetched-only").unwrap(), fetched);
assert_eq!(named("fetched-only").unwrap(), fetched);
assert!(named("nope").is_err());
assert!(named(&git::commit_id(&s.0, "HEAD").unwrap()).is_err(), "a commit is not a branch");
assert_eq!(base_branch(&s.0, "origin", "origin/main").as_deref(), Some("main"));
assert_eq!(base_branch(&s.0, "origin", "feature/other").as_deref(), Some("feature/other"));
assert_eq!(base_branch(&s.0, "origin", "0123abc"), None);
}
#[test]
fn a_push_is_only_offered_when_it_needs_no_force() {
let host = Scratch::new("propose-host");
run(&host.0, &["init", "--quiet", "--bare"]);
let s = Scratch::new("propose-work");
init(&s.0);
std::fs::write(s.0.join("file"), "1").unwrap();
commit(&s.0, "one");
run(&s.0, &["remote", "add", "origin", &host.0.to_string_lossy()]);
let first = git::commit_id(&s.0, "HEAD").unwrap();
assert!(needs_push(&s.0, "origin", "topic", &first).unwrap(), "the host has no such branch");
run(&s.0, &["push", "--quiet", "origin", "HEAD:refs/heads/topic"]);
assert!(!needs_push(&s.0, "origin", "topic", &first).unwrap());
std::fs::write(s.0.join("file"), "2").unwrap();
commit(&s.0, "two");
let second = git::commit_id(&s.0, "HEAD").unwrap();
assert!(needs_push(&s.0, "origin", "topic", &second).unwrap(), "it only adds commits");
run(&s.0, &["push", "--quiet", "origin", "HEAD:refs/heads/topic"]);
let refused = needs_push(&s.0, "origin", "topic", &first).unwrap_err();
assert!(refused.contains("has commits you don't have"), "{refused}");
}
}