1#![cfg(unix)]
19
20use super::git_system_config::with_real_git;
21use super::repo_read_config_list::list_config;
22use super::repo_read_config_scan::ScopeEnvironment;
23use super::repo_read_layout::{RepoLayout, read_layout_after_success};
24use super::repo_read_object::{ObjectKind, from_hex};
25use super::repo_read_odb::ObjectDatabase;
26use super::repo_read_query_refs::tracking_ref;
27use super::repo_read_refs::{RefValue, Refs};
28use super::repo_read_tree::parse_commit;
29use super::service_client::{Activation, COMMIT_WAIT, ClientConfig, START_WAIT};
30use super::service_handoff::{ServiceHandoff, hand_over_push};
31use super::service_messages::{ClientFailure, render};
32use super::push_trigger_log::{Outcome, record_decision};
33use super::service_provision::platform_without_manager;
34use super::service_route::{Route, route_from_environment};
35use std::collections::{HashSet, VecDeque};
36use std::ffi::OsString;
37use std::io::Write;
38use std::path::{Path, PathBuf};
39
40pub const WALK_BUDGET: usize = 4096;
43
44#[derive(Clone, Debug)]
51pub struct TipWatch {
52 layout: RepoLayout,
54 variables: Vec<(OsString, OsString)>,
56 real_git: PathBuf,
58 branch_ref: String,
60 before: String,
62}
63
64#[derive(Clone, Debug, Eq, PartialEq)]
74pub struct Declined {
75 pub reason: &'static str,
81 pub detail: String,
83}
84
85fn declined(reason: &'static str, detail: impl Into<String>) -> Declined {
87 return Declined { reason, detail: detail.into() };
88}
89
90impl TipWatch {
91 pub fn common_dir(&self) -> &Path {
94 return self.layout.common_dir.as_path();
95 }
96}
97
98fn current_branch(layout: &RepoLayout) -> Result<(String, String), Declined> {
109 let refs: Refs = Refs::new(layout.common_dir.as_path(), layout.object_format.hex_length());
110 let head: RefValue = refs
111 .lookup_head(layout.git_dir.as_path())
112 .ok_or_else(|| { return declined("head-unreadable", format!("HEAD in {} is not a plain symbolic or direct ref", layout.git_dir.display())); })?;
113 let RefValue::Symbolic(target) = head else {
114 return Err(declined("head-detached", "HEAD names a commit, not a branch"));
115 };
116 if !target.starts_with("refs/heads/") {
117 return Err(declined("head-not-a-branch", format!("HEAD names {target}")));
118 }
119 let tip: String = refs.resolve(target.as_str()).ok_or_else(|| { return declined("branch-has-no-tip", format!("{target} does not resolve")); })?;
120 return Ok((target, tip));
121}
122
123pub fn try_watch_tip(
135 worktree_root: &Path,
136 real_git: &Path,
137 overlay: &[(OsString, OsString)],
138 environment: &[(OsString, OsString)],
139) -> Result<TipWatch, Declined> {
140 let named: Vec<(OsString, OsString)> = with_real_git(overlay, real_git);
142 let layout: RepoLayout = read_layout_after_success(worktree_root, named.as_slice())
143 .ok_or_else(|| { return declined("layout-declined", format!("the files of {} are not a layout the reader takes", worktree_root.display())); })?;
144 let (branch_ref, before): (String, String) = current_branch(&layout)?;
145 let mut variables: Vec<(OsString, OsString)> = environment.to_vec();
146 variables.extend(named);
147 return Ok(TipWatch { layout, variables, real_git: real_git.to_path_buf(), branch_ref, before });
148}
149
150pub fn watch_tip(
153 worktree_root: &Path,
154 real_git: &Path,
155 overlay: &[(OsString, OsString)],
156 environment: &[(OsString, OsString)],
157) -> Option<TipWatch> {
158 return try_watch_tip(worktree_root, real_git, overlay, environment).ok();
159}
160
161fn upstream_tip(watch: &TipWatch, refs: &Refs) -> Result<String, Declined> {
169 let name: &str = watch.branch_ref.strip_prefix("refs/heads/").ok_or_else(|| { return declined("upstream-no-branch-name", watch.branch_ref.clone()); })?;
170 let scope: ScopeEnvironment = ScopeEnvironment::from_variables(watch.variables.as_slice());
171 let listed = list_config(watch.layout.common_dir.as_path(), watch.layout.git_dir.as_path(), &scope, watch.variables.as_slice())
172 .ok_or_else(|| { return declined("upstream-config-unreadable", "the configuration listing was declined by the reader"); })?;
173 let values = |suffix: &str| -> Vec<String> {
174 let key: String = format!("branch.{name}.{suffix}");
175 return listed
176 .iter()
177 .filter(|item| { return item.entry.key == key; })
178 .filter_map(|item| { return item.entry.value.as_deref().and_then(|bytes| { return std::str::from_utf8(bytes).ok().map(str::to_owned); }); })
179 .collect();
180 };
181 let remotes: Vec<String> = values("remote");
182 let merges: Vec<String> = values("merge");
183 let ([remote], [merge]) = (remotes.as_slice(), merges.as_slice()) else {
184 return Err(declined("upstream-not-single", format!("branch.{name}.remote has {} values and branch.{name}.merge has {}", remotes.len(), merges.len())));
185 };
186 if remote == "." {
187 return Err(declined("upstream-is-local", format!("branch.{name}.remote is the repository itself")));
188 }
189 let tracking: String = tracking_ref(listed.as_slice(), remote, merge)
190 .ok_or_else(|| { return declined("upstream-no-tracking-ref", format!("no remote.{remote}.fetch maps {merge}")); })?;
191 return refs.resolve(tracking.as_str()).ok_or_else(|| { return declined("upstream-tracking-ref-missing", tracking); });
192}
193
194pub fn reaches(database: &ObjectDatabase, layout: &RepoLayout, from: &str, target: &str, budget: usize) -> Option<bool> {
205 let start: Vec<u8> = from_hex(from.as_bytes(), layout.object_format)?;
206 let wanted: Vec<u8> = from_hex(target.as_bytes(), layout.object_format)?;
207 let mut seen: HashSet<Vec<u8>> = HashSet::new();
208 let mut queue: VecDeque<Vec<u8>> = VecDeque::new();
209 seen.insert(start.clone());
210 queue.push_back(start);
211 let mut read: usize = 0;
212 while let Some(name) = queue.pop_front() {
213 if name == wanted {
214 return Some(true);
215 }
216 if read >= budget {
217 return None;
218 }
219 read += 1;
220 let object = database.read(name.as_slice())?;
221 if object.kind != ObjectKind::Commit {
222 return None;
223 }
224 for parent in parse_commit(object.bytes.as_slice(), layout.object_format)?.parents {
225 if seen.insert(parent.clone()) {
226 queue.push_back(parent);
227 }
228 }
229 }
230 return Some(false);
231}
232
233pub fn tip_to_push_or_why(watch: &TipWatch) -> Result<String, Declined> {
245 let (branch_ref, after): (String, String) = current_branch(&watch.layout)?;
246 if branch_ref != watch.branch_ref {
247 return Err(declined("branch-changed", format!("the command started on {} and ended on {branch_ref}", watch.branch_ref)));
248 }
249 if after == watch.before {
250 return Err(declined("tip-unchanged", format!("{branch_ref} stayed at {after}")));
251 }
252 let refs: Refs = Refs::new(watch.layout.common_dir.as_path(), watch.layout.object_format.hex_length());
253 let upstream: String = upstream_tip(watch, &refs)?;
254 if upstream == after {
255 return Err(declined("upstream-equals-tip", format!("{after} is already the upstream tip")));
256 }
257 let database: ObjectDatabase = ObjectDatabase::open(watch.layout.common_dir.as_path(), None, watch.layout.object_format)
258 .ok_or_else(|| { return declined("object-database-unopened", watch.layout.common_dir.display().to_string()); })?;
259 let grew: bool = reaches(&database, &watch.layout, after.as_str(), watch.before.as_str(), WALK_BUDGET)
260 .ok_or_else(|| { return declined("walk-undecided-growth", format!("from {after} to the old tip {}", watch.before)); })?;
261 if !grew {
262 return Err(declined("not-grown", format!("the old tip {} is not an ancestor of {after}: a rewritten branch", watch.before)));
263 }
264 let ahead: bool = reaches(&database, &watch.layout, after.as_str(), upstream.as_str(), WALK_BUDGET)
265 .ok_or_else(|| { return declined("walk-undecided-ahead", format!("from {after} to the upstream tip {upstream}")); })?;
266 if !ahead {
267 return Err(declined("not-ahead", format!("the upstream tip {upstream} is not an ancestor of {after}: diverged")));
268 }
269 return Ok(after);
270}
271
272pub fn tip_to_push(watch: &TipWatch) -> Option<String> {
274 return tip_to_push_or_why(watch).ok();
275}
276
277pub fn hand_over_if_ahead(watch: &TipWatch, command: &str, stderr: &mut dyn Write) {
290 let common: &Path = watch.layout.common_dir.as_path();
291 let branch: &str = watch.branch_ref.as_str();
292 let tip: String = match tip_to_push_or_why(watch) {
293 Ok(tip) => tip,
294 Err(Declined { reason, detail }) => {
295 record_decision(Some(common), command, Outcome::Declined, reason, detail.as_str(), Some(branch));
296 return;
297 }
298 };
299 let Some(Route { address, .. }) = route_from_environment(watch.real_git.as_path(), watch.layout.git_dir.as_path()) else {
300 record_decision(Some(common), command, Outcome::Declined, "no-route", "no way to reach the commit service", Some(branch));
301 let _written = writeln!(stderr, "{}", render(&ClientFailure::NoActivation(platform_without_manager())));
303 return;
304 };
305 let handoff: ServiceHandoff = ServiceHandoff {
306 config: ClientConfig { address, activation: Activation::Managed, start_wait: START_WAIT, commit_wait: COMMIT_WAIT },
307 repository: watch.layout.worktree_root.clone(),
308 git_dir: watch.layout.git_dir.clone(),
309 reference: watch.branch_ref.clone(),
310 parent: watch.before.clone(),
311 };
312 if let Err(failure) = hand_over_push(&handoff, tip.as_str(), stderr) {
313 record_decision(Some(common), command, Outcome::Declined, "handover-failed", render(&failure).as_str(), Some(branch));
314 let _written = writeln!(stderr, "{}", render(&failure));
316 return;
317 }
318 record_decision(Some(common), command, Outcome::HandedOver, "ahead-of-upstream", format!("pushed {tip} of {branch}").as_str(), Some(branch));
319}
320
321#[cfg(test)]
323#[path = "auto_push_trigger_tests.rs"]
324mod tests;