#![cfg(unix)]
use super::git_system_config::with_real_git;
use super::repo_read_config_list::list_config;
use super::repo_read_config_scan::ScopeEnvironment;
use super::repo_read_layout::{RepoLayout, read_layout_after_success};
use super::repo_read_object::{ObjectKind, from_hex};
use super::repo_read_odb::ObjectDatabase;
use super::repo_read_query_refs::tracking_ref;
use super::repo_read_refs::{RefValue, Refs};
use super::repo_read_tree::parse_commit;
use super::service_client::{Activation, COMMIT_WAIT, ClientConfig, START_WAIT};
use super::service_handoff::{ServiceHandoff, hand_over_push};
use super::service_messages::{ClientFailure, render};
use super::push_trigger_log::{Decision, Origin, Outcome, record_decision};
use super::service_provision::platform_without_manager;
use super::service_route::{Route, route_from_environment};
use std::collections::{HashSet, VecDeque};
use std::ffi::OsString;
use std::io::Write;
use std::path::{Path, PathBuf};
pub const WALK_BUDGET: usize = 4096;
#[derive(Clone, Debug)]
pub struct TipWatch {
layout: RepoLayout,
variables: Vec<(OsString, OsString)>,
real_git: PathBuf,
branch_ref: String,
before: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Declined {
pub reason: &'static str,
pub detail: String,
}
fn declined(reason: &'static str, detail: impl Into<String>) -> Declined {
return Declined { reason, detail: detail.into() };
}
impl TipWatch {
pub fn common_dir(&self) -> &Path {
return self.layout.common_dir.as_path();
}
pub fn origin(&self) -> Origin<'_> {
return Origin { worktree: self.layout.worktree_root.as_path(), git_dir: self.layout.git_dir.as_path() };
}
pub fn branch_ref(&self) -> &str {
return self.branch_ref.as_str();
}
pub fn tip_before(&self) -> &str {
return self.before.as_str();
}
}
fn current_branch(layout: &RepoLayout) -> Result<(String, String), Declined> {
let refs: Refs = Refs::new(layout.common_dir.as_path(), layout.object_format.hex_length());
let head: RefValue = refs
.lookup_head(layout.git_dir.as_path())
.ok_or_else(|| { return declined("head-unreadable", format!("HEAD in {} is not a plain symbolic or direct ref", layout.git_dir.display())); })?;
let RefValue::Symbolic(target) = head else {
return Err(declined("head-detached", "HEAD names a commit, not a branch"));
};
if !target.starts_with("refs/heads/") {
return Err(declined("head-not-a-branch", format!("HEAD names {target}")));
}
let tip: String = refs.resolve(target.as_str()).ok_or_else(|| { return declined("branch-has-no-tip", format!("{target} does not resolve")); })?;
return Ok((target, tip));
}
pub fn try_watch_tip(
worktree_root: &Path,
real_git: &Path,
overlay: &[(OsString, OsString)],
environment: &[(OsString, OsString)],
) -> Result<TipWatch, Declined> {
let named: Vec<(OsString, OsString)> = with_real_git(overlay, real_git);
let layout: RepoLayout = read_layout_after_success(worktree_root, named.as_slice())
.ok_or_else(|| { return declined("layout-declined", format!("the files of {} are not a layout the reader takes", worktree_root.display())); })?;
let (branch_ref, before): (String, String) = current_branch(&layout)?;
let mut variables: Vec<(OsString, OsString)> = environment.to_vec();
variables.extend(named);
return Ok(TipWatch { layout, variables, real_git: real_git.to_path_buf(), branch_ref, before });
}
pub fn watch_tip(
worktree_root: &Path,
real_git: &Path,
overlay: &[(OsString, OsString)],
environment: &[(OsString, OsString)],
) -> Option<TipWatch> {
return try_watch_tip(worktree_root, real_git, overlay, environment).ok();
}
fn upstream_tip(watch: &TipWatch, refs: &Refs) -> Result<String, Declined> {
let name: &str = watch.branch_ref.strip_prefix("refs/heads/").ok_or_else(|| { return declined("upstream-no-branch-name", watch.branch_ref.clone()); })?;
let scope: ScopeEnvironment = ScopeEnvironment::from_variables(watch.variables.as_slice());
let listed = list_config(watch.layout.common_dir.as_path(), watch.layout.git_dir.as_path(), &scope, watch.variables.as_slice())
.ok_or_else(|| { return declined("upstream-config-unreadable", "the configuration listing was declined by the reader"); })?;
let values = |suffix: &str| -> Vec<String> {
let key: String = format!("branch.{name}.{suffix}");
return listed
.iter()
.filter(|item| { return item.entry.key == key; })
.filter_map(|item| { return item.entry.value.as_deref().and_then(|bytes| { return std::str::from_utf8(bytes).ok().map(str::to_owned); }); })
.collect();
};
let remotes: Vec<String> = values("remote");
let merges: Vec<String> = values("merge");
let ([remote], [merge]) = (remotes.as_slice(), merges.as_slice()) else {
return Err(declined("upstream-not-single", format!("branch.{name}.remote has {} values and branch.{name}.merge has {}", remotes.len(), merges.len())));
};
if remote == "." {
return Err(declined("upstream-is-local", format!("branch.{name}.remote is the repository itself")));
}
let tracking: String = tracking_ref(listed.as_slice(), remote, merge)
.ok_or_else(|| { return declined("upstream-no-tracking-ref", format!("no remote.{remote}.fetch maps {merge}")); })?;
return refs.resolve(tracking.as_str()).ok_or_else(|| { return declined("upstream-tracking-ref-missing", tracking); });
}
pub fn reaches(database: &ObjectDatabase, layout: &RepoLayout, from: &str, target: &str, budget: usize) -> Option<bool> {
let start: Vec<u8> = from_hex(from.as_bytes(), layout.object_format)?;
let wanted: Vec<u8> = from_hex(target.as_bytes(), layout.object_format)?;
let mut seen: HashSet<Vec<u8>> = HashSet::new();
let mut queue: VecDeque<Vec<u8>> = VecDeque::new();
seen.insert(start.clone());
queue.push_back(start);
let mut read: usize = 0;
while let Some(name) = queue.pop_front() {
if name == wanted {
return Some(true);
}
if read >= budget {
return None;
}
read += 1;
let object = database.read(name.as_slice())?;
if object.kind != ObjectKind::Commit {
return None;
}
for parent in parse_commit(object.bytes.as_slice(), layout.object_format)?.parents {
if seen.insert(parent.clone()) {
queue.push_back(parent);
}
}
}
return Some(false);
}
pub fn tip_to_push_or_why(watch: &TipWatch) -> Result<String, Declined> {
let (branch_ref, after): (String, String) = current_branch(&watch.layout)?;
if branch_ref != watch.branch_ref {
return Err(declined("branch-changed", format!("the command started on {} and ended on {branch_ref}", watch.branch_ref)));
}
if after == watch.before {
return Err(declined("tip-unchanged", format!("{branch_ref} stayed at {after}")));
}
let refs: Refs = Refs::new(watch.layout.common_dir.as_path(), watch.layout.object_format.hex_length());
let upstream: String = upstream_tip(watch, &refs)?;
if upstream == after {
return Err(declined("upstream-equals-tip", format!("{after} is already the upstream tip")));
}
let database: ObjectDatabase = ObjectDatabase::open(watch.layout.common_dir.as_path(), None, watch.layout.object_format)
.ok_or_else(|| { return declined("object-database-unopened", watch.layout.common_dir.display().to_string()); })?;
let grew: bool = reaches(&database, &watch.layout, after.as_str(), watch.before.as_str(), WALK_BUDGET)
.ok_or_else(|| { return declined("walk-undecided-growth", format!("from {after} to the old tip {}", watch.before)); })?;
if !grew {
return Err(declined("not-grown", format!("the old tip {} is not an ancestor of {after}: a rewritten branch", watch.before)));
}
let ahead: bool = reaches(&database, &watch.layout, after.as_str(), upstream.as_str(), WALK_BUDGET)
.ok_or_else(|| { return declined("walk-undecided-ahead", format!("from {after} to the upstream tip {upstream}")); })?;
if !ahead {
return Err(declined("not-ahead", format!("the upstream tip {upstream} is not an ancestor of {after}: diverged")));
}
return Ok(after);
}
pub fn tip_to_push(watch: &TipWatch) -> Option<String> {
return tip_to_push_or_why(watch).ok();
}
pub fn hand_over_if_ahead(watch: &TipWatch, command: &str, stderr: &mut dyn Write) {
let common: &Path = watch.layout.common_dir.as_path();
let branch: &str = watch.branch_ref.as_str();
let decide = |outcome: Outcome, reason: &str, detail: &str| {
record_decision(&Decision { common_dir: Some(common), origin: Some(watch.origin()), command, outcome, reason, detail, branch: Some(branch) });
};
let tip: String = match tip_to_push_or_why(watch) {
Ok(tip) => tip,
Err(Declined { reason, detail }) => {
decide(Outcome::Declined, reason, detail.as_str());
return;
}
};
let Some(Route { address, .. }) = route_from_environment(watch.real_git.as_path(), watch.layout.git_dir.as_path()) else {
decide(Outcome::Declined, "no-route", "no way to reach the commit service");
let _written = writeln!(stderr, "{}", render(&ClientFailure::NoActivation(platform_without_manager())));
return;
};
let handoff: ServiceHandoff = ServiceHandoff {
config: ClientConfig { address, activation: Activation::Managed, start_wait: START_WAIT, commit_wait: COMMIT_WAIT },
repository: watch.layout.worktree_root.clone(),
git_dir: watch.layout.git_dir.clone(),
reference: watch.branch_ref.clone(),
parent: watch.before.clone(),
};
if let Err(failure) = hand_over_push(&handoff, tip.as_str(), stderr) {
decide(Outcome::Declined, "handover-failed", render(&failure).as_str());
let _written = writeln!(stderr, "{}", render(&failure));
return;
}
decide(Outcome::HandedOver, "ahead-of-upstream", format!("pushed {tip} of {branch}").as_str());
}
#[cfg(test)]
#[path = "auto_push_trigger_tests.rs"]
mod tests;