use crate::{Error, Git};
use jouet_output::exit::Exit;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layer {
pub branch: String,
pub parent: String,
pub merged: bool,
pub parent_merged: bool,
}
#[derive(Debug, Clone)]
pub struct Stack {
pub trunk: String,
pub remote: String,
pub layers: Vec<Layer>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Problem {
Reverted,
Missing,
Conflicting,
}
impl Problem {
pub fn describe(self) -> &'static str {
match self {
Self::Reverted => "reverted",
Self::Missing => "missing",
Self::Conflicting => "changed differently",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FileProblem {
pub path: String,
pub problem: Problem,
#[serde(skip_serializing_if = "Option::is_none")]
pub commit: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LayerState {
pub branch: String,
pub parent: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub local: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub remote: Option<String>,
#[serde(skip_serializing_if = "is_zero")]
pub unpushed: u32,
#[serde(skip_serializing_if = "is_zero")]
pub behind: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub contains_parent: Option<bool>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub content: Vec<FileProblem>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub needs_trunk: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub merged: bool,
}
fn is_zero(n: &u32) -> bool {
*n == 0
}
impl LayerState {
pub fn tip(&self) -> Option<&str> {
self.local.as_deref().or(self.remote.as_deref())
}
pub fn needs(&self) -> Vec<&'static str> {
let mut needs = Vec::new();
if self.merged {
return needs;
}
if self.tip().is_none() {
needs.push("missing_branch");
}
if !self.content.is_empty() {
needs.push("parent_changes_missing");
}
if self.behind > 0 {
needs.push("behind_remote");
}
if self.needs_trunk {
needs.push("needs_trunk");
} else if self.contains_parent == Some(false) {
needs.push("needs_parent");
}
needs
}
}
pub fn remote(git: &Git) -> String {
let remotes = git.line(&["remote"]).unwrap_or_default();
let mut names = remotes.lines();
let first = names.next();
match first {
Some(first) if first != "origin" && !remotes.lines().any(|r| r == "origin") => {
first.to_string()
}
_ => "origin".into(),
}
}
fn refs(git: &Git, remote: &str, branch: &str) -> (Option<String>, Option<String>) {
(
git.commit_sha(&format!("refs/heads/{branch}")),
git.commit_sha(&format!("refs/remotes/{remote}/{branch}")),
)
}
pub fn trunk_tip(git: &Git, stack: &Stack) -> Option<String> {
let (local, remote) = refs(git, &stack.remote, &stack.trunk);
remote.or(local)
}
pub fn branch_tip(git: &Git, remote: &str, branch: &str) -> Option<String> {
let (local, remote) = refs(git, remote, branch);
local.or(remote)
}
pub fn parent_tip(git: &Git, stack: &Stack, layer: &Layer) -> Option<String> {
if layer.parent == stack.trunk {
trunk_tip(git, stack)
} else {
branch_tip(git, &stack.remote, &layer.parent)
}
}
pub fn parent_base(git: &Git, stack: &Stack, index: usize, parent: &str) -> Option<String> {
let below = index.checked_sub(1).map(|i| &stack.layers[i])?;
if below.branch != stack.layers[index].parent {
return None;
}
let grandparent = parent_tip(git, stack, below)?;
git.line(&["merge-base", parent, &grandparent])
}
pub fn inspect(git: &Git, stack: &Stack) -> Result<Vec<LayerState>, Error> {
let mut out = Vec::new();
for (i, layer) in stack.layers.iter().enumerate() {
let (local, remote) = refs(git, &stack.remote, &layer.branch);
let mut state = LayerState {
branch: layer.branch.clone(),
parent: layer.parent.clone(),
local,
remote,
unpushed: 0,
behind: 0,
contains_parent: None,
content: Vec::new(),
needs_trunk: false,
merged: layer.merged,
};
if let (Some(local), Some(remote)) = (&state.local, &state.remote) {
state.unpushed = git.count(&format!("{remote}..{local}")).unwrap_or(0);
state.behind = git.count(&format!("{local}..{remote}")).unwrap_or(0);
} else if let (Some(local), false) = (&state.local, layer.merged) {
if let Some(parent) = parent_tip(git, stack, layer) {
state.unpushed = git.count(&format!("{parent}..{local}")).unwrap_or(0);
}
}
let tip = state.tip().map(str::to_string);
if let (false, Some(tip)) = (layer.merged, tip) {
if layer.parent_merged
&& let Some(trunk) = trunk_tip(git, stack)
{
state.needs_trunk = !git.is_ancestor(&trunk, &tip);
}
if let Some(parent) = parent_tip(git, stack, layer) {
let contains = git.is_ancestor(&parent, &tip);
state.contains_parent = Some(contains);
if contains && let Some(base) = parent_base(git, stack, i, &parent) {
state.content = missing_changes(git, &base, &parent, &tip)?;
}
}
}
out.push(state);
}
Ok(out)
}
pub fn missing_changes(
git: &Git,
from: &str,
to: &str,
tip: &str,
) -> Result<Vec<FileProblem>, Error> {
let changed = names(git, from, to)?;
if changed.is_empty() {
return Ok(Vec::new());
}
let differs = names(git, to, tip)?;
let mut problems = Vec::new();
for path in changed.iter().filter(|p| differs.contains(p)) {
let change = Change {
path,
base: blob(git, from, path),
theirs: blob(git, to, path),
};
let mine = blob(git, tip, path);
let problem = change.lacked_by(git, mine.as_deref())?;
if problem.is_some() && own_edit(git, &change, to, tip)? {
continue;
}
if let Some(problem) = problem {
let undone = undone_commit(git, from, to, path, mine.as_deref());
problems.push(FileProblem {
path: path.clone(),
problem: if undone.is_some() {
Problem::Reverted
} else {
problem
},
commit: undone,
});
}
}
Ok(problems)
}
struct Change<'a> {
path: &'a str,
base: Option<String>,
theirs: Option<String>,
}
impl Change<'_> {
fn lacked_by(&self, git: &Git, mine: Option<&str>) -> Result<Option<Problem>, Error> {
if mine == self.base.as_deref() {
return Ok(Some(Problem::Reverted));
}
Ok(match (self.theirs.as_deref(), mine) {
(Some(_), None) | (None, Some(_)) => Some(Problem::Missing),
(Some(theirs), Some(mine)) => merge_check(git, mine, self.base.as_deref(), theirs)?,
(None, None) => None,
})
}
}
fn own_edit(git: &Git, change: &Change<'_>, to: &str, tip: &str) -> Result<bool, Error> {
let mut at = tip.to_string();
loop {
let Ok(log) = git.text(&[
"log",
"-1",
"--topo-order",
"--full-history",
"--format=%H %P",
&format!("{to}..{at}"),
"--",
change.path,
]) else {
return Ok(false);
};
let mut fields = log.split_whitespace();
let (Some(_), Some(before), None) = (fields.next(), fields.next(), fields.next()) else {
return Ok(false);
};
let version = blob(git, before, change.path);
if change.lacked_by(git, version.as_deref())?.is_none() {
return Ok(true);
}
at = before.to_string();
}
}
fn undone_commit(
git: &Git,
from: &str,
to: &str,
path: &str,
mine: Option<&str>,
) -> Option<String> {
let log = git
.text(&[
"log",
"--format=%H %h %s",
"--no-merges",
&format!("{from}..{to}"),
"--",
path,
])
.ok()?;
log.lines().find_map(|line| {
let (sha, short) = line.split_once(' ')?;
(blob(git, &format!("{sha}^"), path).as_deref() == mine).then(|| short.to_string())
})
}
fn names(git: &Git, a: &str, b: &str) -> Result<Vec<String>, Error> {
let out = git.text(&["diff", "--name-only", "-z", "--no-renames", a, b])?;
Ok(crate::nul_fields(&out).map(str::to_string).collect())
}
fn blob(git: &Git, commit: &str, path: &str) -> Option<String> {
git.line(&[
"rev-parse",
"--verify",
"--quiet",
&format!("{commit}:{path}"),
])
}
fn merge_check(
git: &Git,
mine: &str,
base: Option<&str>,
theirs: &str,
) -> Result<Option<Problem>, Error> {
let dir = tempfile::tempdir()
.map_err(|e| Error::new(Exit::Failed, format!("creating a temporary directory: {e}")))?;
let write = |name: &str, oid: Option<&str>| -> Result<(PathBuf, Vec<u8>), Error> {
let path = dir.path().join(name);
let bytes = match oid {
Some(oid) => cat(git, oid)?,
None => Vec::new(),
};
std::fs::write(&path, &bytes)
.map_err(|e| Error::new(Exit::Failed, format!("writing {}: {e}", path.display())))?;
Ok((path, bytes))
};
let (mine_path, mine_bytes) = write("mine", Some(mine))?;
let (base_path, _) = write("base", base)?;
let (theirs_path, _) = write("theirs", Some(theirs))?;
let out = git
.command(&[
Path::new("merge-file"),
Path::new("-p"),
Path::new("--quiet"),
&mine_path,
&base_path,
&theirs_path,
])
.output()
.map_err(|e| Error::new(Exit::Failed, format!("running git merge-file: {e}")))?;
Ok(match out.status.code() {
Some(0) if out.stdout == mine_bytes => None,
Some(0) => Some(Problem::Missing),
_ => Some(Problem::Conflicting),
})
}
fn cat(git: &Git, oid: &str) -> Result<Vec<u8>, Error> {
let out = git
.command(&["cat-file", "blob", oid])
.output()
.map_err(|e| Error::new(Exit::Failed, format!("running git cat-file: {e}")))?;
if !out.status.success() {
return Err(Error::new(Exit::Failed, format!("reading blob {oid}")));
}
Ok(out.stdout)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GhStack {
pub trunk: String,
pub branches: Vec<(String, Option<u64>)>,
}
#[derive(Deserialize)]
struct GhStackFile {
#[serde(default)]
stacks: Vec<GhStackEntry>,
}
#[derive(Deserialize)]
struct GhStackEntry {
trunk: GhBranch,
#[serde(default)]
branches: Vec<GhBranch>,
}
#[derive(Deserialize)]
struct GhBranch {
branch: String,
#[serde(default, rename = "pullRequest")]
pull_request: Option<GhPr>,
}
#[derive(Deserialize)]
struct GhPr {
number: u64,
}
pub fn gh_stack(git: &Git, branch: &str) -> Option<GhStack> {
let dirs = [
git.git_dir().ok(),
git.line(&["rev-parse", "--path-format=absolute", "--git-common-dir"])
.map(PathBuf::from),
];
dirs.into_iter().flatten().find_map(|dir| {
let text = std::fs::read_to_string(dir.join("gh-stack")).ok()?;
parse_gh_stack(&text, branch)
})
}
pub fn parse_gh_stack(text: &str, branch: &str) -> Option<GhStack> {
let file: GhStackFile = serde_json::from_str(text).ok()?;
let entry = file
.stacks
.into_iter()
.find(|s| s.branches.iter().any(|b| b.branch == branch))?;
Some(GhStack {
trunk: entry.trunk.branch,
branches: entry
.branches
.into_iter()
.map(|b| (b.branch, b.pull_request.map(|p| p.number)))
.collect(),
})
}
pub mod sync;
#[cfg(test)]
mod tests;