1use super::auto_push_single_flight::{PushGit, git_command};
16use super::random_id::random_uuid;
18use std::ffi::OsString;
20use std::fs;
22use std::path::{Path, PathBuf};
24use std::process::Stdio;
26
27pub const CAPTURE_DIRECTORY_ENV: &str = "CLI_GIT_PUSH_FACTS_DIRECTORY";
29
30pub const PRE_PUSH_FIELD_COUNT: usize = 4;
32
33pub const MAX_HOOK_INPUT_BYTES: u64 = 16 * 1024 * 1024;
35
36const PRIVATE_DIRECTORY_MODE: u32 = 0o700;
38
39const HOOK_NAME: &str = "pre-push";
41
42const CAPTURE_SUFFIX: &str = ".capture";
44
45#[derive(Clone, Debug, Eq, PartialEq)]
55pub struct ManualPushProbeError {
56 pub message: String,
58}
59
60impl std::fmt::Display for ManualPushProbeError {
61 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 return formatter.write_str(&self.message);
64 }
65}
66
67impl std::error::Error for ManualPushProbeError {}
68
69fn probe_error(message: String) -> ManualPushProbeError {
76 return ManualPushProbeError { message };
77}
78
79#[derive(Clone, Debug, Eq, PartialEq)]
89pub struct ProbedUpdate {
90 pub local_ref: String,
92 pub local_oid: String,
94 pub remote_name: String,
96 pub remote_location: String,
98 pub remote_ref: String,
100 pub advertised_remote_oid: String,
102}
103
104#[derive(Clone, Debug, Eq, PartialEq)]
114pub struct PushUpdate {
115 pub local_oid: Option<String>,
117 pub remote_oid: Option<String>,
119 pub remote_name: String,
121 pub remote_ref: String,
123}
124
125pub fn is_zero_oid(oid: &str) -> bool {
133 return !oid.is_empty()
134 && oid.bytes().all(|byte| {
135 return byte == b'0';
136 });
137}
138
139pub fn parse_update_records(
149 input: &str,
150 remote_name: &str,
151 remote_location: &str,
152) -> Result<Vec<ProbedUpdate>, ManualPushProbeError> {
153 let mut updates: Vec<ProbedUpdate> = Vec::new();
154 for line in input.split('\n').filter(|line| {
155 return !line.is_empty();
156 }) {
157 let parts: Vec<&str> = line.split(' ').collect();
158 if parts.len() != PRE_PUSH_FIELD_COUNT {
159 return Err(probe_error(format!(
160 "Malformed pre-push update record: {line}"
161 )));
162 }
163 updates.push(ProbedUpdate {
164 local_ref: parts[0].to_owned(),
165 local_oid: parts[1].to_owned(),
166 remote_name: remote_name.to_owned(),
167 remote_location: remote_location.to_owned(),
168 remote_ref: parts[2].to_owned(),
169 advertised_remote_oid: parts[3].to_owned(),
170 });
171 }
172 return Ok(updates);
173}
174
175pub fn probe_arguments(
186 global_prefix: &[OsString],
187 post_subcommand: &[OsString],
188 hooks_directory: &Path,
189) -> Vec<OsString> {
190 let separator = post_subcommand.iter().position(|argument| {
191 return argument.as_os_str() == "--";
192 });
193 let insertion = separator.unwrap_or(post_subcommand.len());
194 let mut arguments: Vec<OsString> = global_prefix.to_vec();
195 arguments.push(OsString::from("-c"));
196 arguments.push(OsString::from(format!(
197 "core.hooksPath={}",
198 hooks_directory.display()
199 )));
200 arguments.push(OsString::from("push"));
201 arguments.extend(post_subcommand[..insertion].iter().cloned());
202 arguments.push(OsString::from("--dry-run"));
203 arguments.push(OsString::from("--verify"));
204 arguments.extend(post_subcommand[insertion..].iter().cloned());
205 return arguments;
206}
207
208pub fn hook_source() -> String {
219 return format!(
220 "#!/bin/sh\nset -C\n{{ printf '%s\\n%s\\n' \"$1\" \"$2\"; head -c {}; }} > \"${CAPTURE_DIRECTORY_ENV}/$$.capture\" || exit 1\n",
221 MAX_HOOK_INPUT_BYTES + 1
222 );
223}
224
225fn create_private_directory(path: &Path) -> std::io::Result<()> {
233 use std::os::unix::fs::DirBuilderExt;
234 return fs::DirBuilder::new()
235 .mode(PRIVATE_DIRECTORY_MODE)
236 .create(path);
237}
238
239pub fn capture_probed_updates(
250 git: &PushGit,
251 global_prefix: &[OsString],
252 post_subcommand: &[OsString],
253 scratch: &Path,
254) -> Result<Vec<ProbedUpdate>, ManualPushProbeError> {
255 let hooks = scratch.join("hooks");
256 let captures = scratch.join("captures");
257 for directory in [scratch, hooks.as_path(), captures.as_path()] {
258 create_private_directory(directory).map_err(|error| {
259 return probe_error(format!(
260 "private probe directory {} could not be created: {error}",
261 directory.display()
262 ));
263 })?;
264 }
265 let hook_path = hooks.join(HOOK_NAME);
266 fs::write(&hook_path, hook_source()).map_err(|error| {
267 return probe_error(format!("hook write failed: {error}"));
268 })?;
269 set_executable(&hook_path)?;
270 let arguments = probe_arguments(global_prefix, post_subcommand, &hooks);
271 let mut command = git_command(git, &arguments);
272 command
273 .stdin(Stdio::null())
274 .env(CAPTURE_DIRECTORY_ENV, &captures);
275 let probe = command.output().map_err(|error| {
276 return probe_error(format!("probe push could not start: {error}"));
277 })?;
278 let mut names: Vec<PathBuf> = fs::read_dir(&captures)
279 .map_err(|error| {
280 return probe_error(format!("captures unreadable: {error}"));
281 })?
282 .map(|entry| {
283 return entry.map(|found| {
284 return found.path();
285 });
286 })
287 .collect::<Result<Vec<PathBuf>, std::io::Error>>()
288 .map_err(|error| {
289 return probe_error(format!("captures unreadable: {error}"));
290 })?;
291 names.retain(|path| {
292 return path.to_string_lossy().ends_with(CAPTURE_SUFFIX);
293 });
294 names.sort();
295 if names.is_empty() {
296 return Err(probe_error(format!(
297 "Git could not determine push updates: {}",
298 String::from_utf8_lossy(&probe.stderr).trim_end()
299 )));
300 }
301 let mut updates: Vec<ProbedUpdate> = Vec::new();
302 let _scratch_guard = ScratchGuard(scratch.to_path_buf());
303 for path in names {
304 let bytes = fs::read(&path).map_err(|error| {
305 return probe_error(format!("capture unreadable: {error}"));
306 })?;
307 let text = String::from_utf8_lossy(&bytes);
308 let mut lines = text.splitn(3, '\n');
309 let remote_name = lines.next().unwrap_or_default();
310 let remote_location = lines.next().unwrap_or_default();
311 let input = lines.next().unwrap_or_default();
312 if input.len() as u64 > MAX_HOOK_INPUT_BYTES {
313 return Err(probe_error(
314 "Pre-push input exceeded capture limit.".to_owned(),
315 ));
316 }
317 updates.extend(parse_update_records(input, remote_name, remote_location)?);
318 }
319 return Ok(updates);
320}
321
322struct ScratchGuard(PathBuf);
332
333impl Drop for ScratchGuard {
334 fn drop(&mut self) {
336 let _removed = fs::remove_dir_all(&self.0);
337 }
338}
339
340fn set_executable(path: &Path) -> Result<(), ManualPushProbeError> {
347 use std::os::unix::fs::PermissionsExt;
348 return fs::set_permissions(path, fs::Permissions::from_mode(PRIVATE_DIRECTORY_MODE)).map_err(
349 |error| {
350 return probe_error(format!("hook mode failed: {error}"));
351 },
352 );
353}
354
355pub fn parse_remote_refs(output: &str) -> Result<Vec<(String, String)>, ManualPushProbeError> {
362 let mut refs: Vec<(String, String)> = Vec::new();
363 for line in output.split('\n').filter(|line| {
364 return !line.is_empty();
365 }) {
366 let Some((oid, name)) = line.split_once('\t') else {
367 return Err(probe_error(format!("Malformed ls-remote record: {line}")));
368 };
369 refs.push((name.to_owned(), oid.to_owned()));
370 }
371 return Ok(refs);
372}
373
374pub fn confirm_group(
385 git: &PushGit,
386 remote_location: &str,
387 updates: &[ProbedUpdate],
388) -> Result<Vec<PushUpdate>, ManualPushProbeError> {
389 let mut arguments: Vec<OsString> = vec![
390 OsString::from("ls-remote"),
391 OsString::from("--refs"),
392 OsString::from(remote_location),
393 ];
394 arguments.extend(updates.iter().map(|update| {
395 return OsString::from(&update.remote_ref);
396 }));
397 let output = git_command(git, &arguments)
398 .stdin(Stdio::null())
399 .output()
400 .map_err(|error| {
401 return probe_error(format!("ls-remote could not start: {error}"));
402 })?;
403 if !output.status.success() {
404 return Err(probe_error(format!(
405 "ls-remote of {remote_location} failed: {}",
406 String::from_utf8_lossy(&output.stderr).trim_end()
407 )));
408 }
409 let remote_refs = parse_remote_refs(&String::from_utf8_lossy(&output.stdout))?;
410 let mut confirmed: Vec<PushUpdate> = Vec::new();
411 for update in updates {
412 let authoritative: Option<&String> = remote_refs
413 .iter()
414 .find(|(name, _oid)| {
415 return name == &update.remote_ref;
416 })
417 .map(|(_name, oid)| {
418 return oid;
419 });
420 let advertised_absent = is_zero_oid(&update.advertised_remote_oid);
421 if authoritative.is_none() != advertised_absent {
422 return Err(probe_error(format!(
423 "Remote ref changed during manual-push discovery: {}",
424 update.remote_ref
425 )));
426 }
427 if let Some(oid) = authoritative
428 && *oid != update.advertised_remote_oid
429 {
430 return Err(probe_error(format!(
431 "Remote ref changed during manual-push discovery: {}",
432 update.remote_ref
433 )));
434 }
435 confirmed.push(PushUpdate {
436 local_oid: if is_zero_oid(&update.local_oid) {
437 None
438 } else {
439 Some(update.local_oid.clone())
440 },
441 remote_oid: authoritative.cloned(),
442 remote_name: update.remote_name.clone(),
443 remote_ref: update.remote_ref.clone(),
444 });
445 }
446 return Ok(confirmed);
447}
448
449pub fn probe_manual_push_updates(
459 git: &PushGit,
460 global_prefix: &[OsString],
461 post_subcommand: &[OsString],
462) -> Result<Vec<PushUpdate>, ManualPushProbeError> {
463 let scratch = std::env::temp_dir().join(format!(
464 "cli-git-push-facts-{}",
465 random_uuid().map_err(|error| {
466 return probe_error(format!("random source failed: {}", error.0));
467 })?
468 ));
469 let probed = capture_probed_updates(git, global_prefix, post_subcommand, &scratch)?;
470 let mut locations: Vec<String> = Vec::new();
471 for update in &probed {
472 if !locations.contains(&update.remote_location) {
473 locations.push(update.remote_location.clone());
474 }
475 }
476 let mut confirmed: Vec<PushUpdate> = Vec::new();
477 for location in &locations {
478 let group: Vec<ProbedUpdate> = probed
479 .iter()
480 .filter(|update| {
481 return &update.remote_location == location;
482 })
483 .cloned()
484 .collect();
485 confirmed.extend(confirm_group(git, location, &group)?);
486 }
487 return Ok(confirmed);
488}
489
490#[cfg(test)]
492#[path = "manual_push_probe_tests.rs"]
493mod tests;