Skip to main content

git_policy_cli/
manual_push_probe.rs

1//! What:
2//!  The authoritative ref updates a `git push` would send, discovered by a dry-run push whose report Git writes itself.
3//! Why:
4//!  The manual-push policies must scan exactly what Git would publish, so the probe asks Git:
5//!  `git push --dry-run --porcelain` reports each destination and ref update (`manual_push_porcelain`), the local
6//!  objects come from that report or from one `rev-parse`, and `git ls-remote --refs` confirms each destination value.
7//!  A remote ref that changed between negotiation and confirmation stops the probe.
8//!  No program of ours is started for this, and no hook or shell text is written: an earlier version recorded Git's
9//!  update lines with a `#!/bin/sh` hook (`doc/planning/cli-git-no-self-invocation.md`).
10//!  Every Git child here is bounded by the query deadline, so a remote that never answers cannot hold the push.
11//!
12//! In TS you'd write (pseudocode):
13//! ```ts
14//! const updates = await probeManualPushUpdates({ gitPath, cwd, args });
15//! ```
16
17/// The probe's Git runner, its bounded queries and its environment.
18use super::auto_push_single_flight::{PushGit, run_query};
19/// The destination Git would pick for a bare push, and the porcelain report's parser.
20use super::lfs_upload_plan::resolve_push_remote;
21use super::manual_push_porcelain::{PorcelainUpdate, RemoteBefore, parse_porcelain};
22/// The push's own reading of its destination.
23use super::command_push::push_shape;
24/// Owned OS strings for the probe's Git arguments.
25use std::ffi::OsString;
26
27/// What:
28///  Why the probe could not establish the updates Git would push.
29/// Why:
30///   Every variant stops the policy lifecycle with a content-unavailable failure; none guesses an update.
31///
32/// In TS you'd write (pseudocode):
33/// ```ts
34/// class ManualPushProbeError extends Error {}
35/// ```
36#[derive(Clone, Debug, Eq, PartialEq)]
37pub struct ManualPushProbeError {
38    /// Diagnostic naming what could not be established.
39    pub message: String,
40}
41
42impl std::fmt::Display for ManualPushProbeError {
43    /// Writes the diagnostic text.
44    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        return formatter.write_str(&self.message);
46    }
47}
48
49impl std::error::Error for ManualPushProbeError {}
50
51/// Build a probe error from text.
52///
53/// In TS you'd write (pseudocode):
54/// ```ts
55/// new ManualPushProbeError(message)
56/// ```
57fn probe_error(message: String) -> ManualPushProbeError {
58    return ManualPushProbeError { message };
59}
60
61/// What:
62///  One confirmed push update, the public fact the policies read.
63/// Why:
64///   An absent value is `None`, which replaces the incumbent's `ABSENT_GIT_VALUE` sentinel.
65///
66/// In TS you'd write (pseudocode):
67/// ```ts
68/// type PushUpdate = { localOid: string | typeof ABSENT_GIT_VALUE; remoteOid: string | typeof ABSENT_GIT_VALUE; remoteName; remoteRef };
69/// ```
70#[derive(Clone, Debug, Eq, PartialEq)]
71pub struct PushUpdate {
72    /// Local object name; `None` for a deletion.
73    pub local_oid: Option<String>,
74    /// Destination object name confirmed by `ls-remote`; `None` when the ref is absent.
75    pub remote_oid: Option<String>,
76    /// Destination remote name.
77    pub remote_name: String,
78    /// Destination ref.
79    pub remote_ref: String,
80}
81
82/// What:
83///  The probe's Git arguments: the invocation's global options, the switches that keep every hook and full object
84///  names, then `push` with `--dry-run --porcelain` placed before any `--` terminator.
85/// Why:
86///   The `--` terminator is the user's; the options Git interprets must stay before it. The probe publishes nothing and
87///  must not run the upload hook of the caller's configuration, so configured `pre-push` hooks are off and the
88///  traditional hooks directory is one that never exists.
89///
90/// In TS you'd write (pseudocode):
91/// ```ts
92/// probeArgs({ globalPrefix, args });
93/// ```
94pub fn probe_arguments(global_prefix: &[OsString], post_subcommand: &[OsString]) -> Vec<OsString> {
95    let separator = post_subcommand.iter().position(|argument| {
96        return argument.as_os_str() == "--";
97    });
98    let insertion = separator.unwrap_or(post_subcommand.len());
99    let mut arguments: Vec<OsString> = global_prefix.to_vec();
100    for setting in [
101        format!("core.hooksPath={}", super::hooks_off::NO_HOOKS_DIRECTORY),
102        String::from("hook.pre-push.enabled=false"),
103        String::from("core.abbrev=no"),
104    ] {
105        arguments.push(OsString::from("-c"));
106        arguments.push(OsString::from(setting));
107    }
108    arguments.push(OsString::from("push"));
109    arguments.extend(post_subcommand[..insertion].iter().cloned());
110    // A `-q` written by the caller silences the report this probe reads, so it is cancelled here; the caller's own
111    //  push keeps its `-q`.
112    arguments.push(OsString::from("--no-quiet"));
113    arguments.push(OsString::from("--dry-run"));
114    arguments.push(OsString::from("--porcelain"));
115    arguments.extend(post_subcommand[insertion..].iter().cloned());
116    return arguments;
117}
118
119/// One Git query of the probe: its trimmed standard output when it exits with status zero.
120fn answer(git: &PushGit, arguments: &[OsString]) -> Option<String> {
121    let output = run_query(git, arguments).ok()?;
122    if output.code != Some(0) {
123        return None;
124    }
125    return Some(String::from_utf8_lossy(output.stdout.as_slice()).trim().to_owned());
126}
127
128/// The destination locations of a remote name, one per `To` block Git printed: the push URLs of a configured remote,
129///  or the name itself when it is not one (a URL or a path typed in place of a remote).
130fn locations_of(git: &PushGit, global_prefix: &[OsString], remote: &str) -> Vec<String> {
131    let mut arguments: Vec<OsString> = global_prefix.to_vec();
132    arguments.extend(["remote", "get-url", "--push", "--all", remote].map(OsString::from));
133    return match answer(git, arguments.as_slice()) {
134        Some(listing) if !listing.is_empty() => listing.lines().map(str::to_owned).collect(),
135        Some(_) | None => vec![remote.to_owned()],
136    };
137}
138
139/// What:
140///  The object names of local refs, in order, from one `rev-parse`.
141/// Why:
142///   A new ref's report line has no object name; the ref's own value is what the push sends.
143///
144/// In TS you'd write (pseudocode):
145/// ```ts
146/// (await git(['rev-parse', ...names])).split('\n')
147/// ```
148fn local_objects(git: &PushGit, global_prefix: &[OsString], names: &[&str]) -> Result<Vec<String>, ManualPushProbeError> {
149    if names.is_empty() {
150        return Ok(Vec::new());
151    }
152    let mut arguments: Vec<OsString> = global_prefix.to_vec();
153    arguments.push(OsString::from("rev-parse"));
154    arguments.extend(names.iter().map(OsString::from));
155    let listing: String = answer(git, arguments.as_slice())
156        .ok_or_else(|| {
157            return probe_error(format!("the local objects of {names:?} could not be read"));
158        })?;
159    let objects: Vec<String> = listing.lines().map(str::to_owned).collect();
160    if objects.len() != names.len() {
161        return Err(probe_error(format!("rev-parse answered {} names for {}", objects.len(), names.len())));
162    }
163    return Ok(objects);
164}
165
166/// What:
167///  Confirm one destination's values with `git ls-remote --refs` and turn each reported update into a public update.
168/// Why:
169///   A destination that changed after the dry run reported would publish something the scan did not see, so a
170///  mismatch between the report and the confirmation is an error, never a silent repair. A report that did not state the
171///  remote's value (a deletion, a refusal) is taken from the confirmation alone.
172///
173/// In TS you'd write (pseudocode):
174/// ```ts
175/// async function resolveRemoteGroup({ gitPath, cwd, remoteLocation, updates }): Promise<PushUpdate[]>;
176/// ```
177pub fn confirm_group(
178    git: &PushGit,
179    remote_location: &str,
180    remote_name: &str,
181    updates: &[(PorcelainUpdate, Option<String>)],
182) -> Result<Vec<PushUpdate>, ManualPushProbeError> {
183    let mut arguments: Vec<OsString> = vec![
184        OsString::from("ls-remote"),
185        OsString::from("--refs"),
186        OsString::from(remote_location),
187    ];
188    arguments.extend(updates.iter().map(|(update, _local)| {
189        return OsString::from(&update.to);
190    }));
191    let output = run_query(git, arguments.as_slice())
192        .map_err(|error| {
193            return probe_error(format!("ls-remote of {remote_location} failed: {error}"));
194        })?;
195    if output.code != Some(0) {
196        return Err(probe_error(format!(
197            "ls-remote of {remote_location} failed: {}",
198            String::from_utf8_lossy(&output.stderr).trim_end()
199        )));
200    }
201    let listing: String = String::from_utf8_lossy(&output.stdout).into_owned();
202    let mut confirmed: Vec<PushUpdate> = Vec::new();
203    for (update, local) in updates {
204        let authoritative: Option<String> = listing.lines().find_map(|line| {
205            return line.split_once('\t').filter(|(_oid, name)| {
206                return *name == update.to;
207            }).map(|(oid, _name)| {
208                return oid.to_owned();
209            });
210        });
211        let changed: bool = match &update.before {
212            RemoteBefore::Absent => authoritative.is_some(),
213            RemoteBefore::Known(reported) => authoritative.as_ref() != Some(reported),
214            RemoteBefore::Unknown => false,
215        };
216        if changed {
217            return Err(probe_error(format!("Remote ref changed during manual-push discovery: {}", update.to)));
218        }
219        confirmed.push(PushUpdate {
220            local_oid: local.clone(),
221            remote_oid: authoritative,
222            remote_name: remote_name.to_owned(),
223            remote_ref: update.to.clone(),
224        });
225    }
226    return Ok(confirmed);
227}
228
229/// What:
230///  Discover the exact updates the push would send, confirmed against each destination.
231/// Why:
232///   The lifecycle's candidates and published-set reads both start from these updates.
233///
234/// In TS you'd write (pseudocode):
235/// ```ts
236/// async function probeManualPushUpdates({ gitPath, cwd, args }): Promise<PushUpdate[]>;
237/// ```
238pub fn probe_manual_push_updates(
239    git: &PushGit,
240    global_prefix: &[OsString],
241    post_subcommand: &[OsString],
242) -> Result<Vec<PushUpdate>, ManualPushProbeError> {
243    let arguments: Vec<OsString> = probe_arguments(global_prefix, post_subcommand);
244    let output = run_query(git, arguments.as_slice()).map_err(|error| {
245        return probe_error(format!("probe push could not run: {error}"));
246    })?;
247    let report: String = String::from_utf8_lossy(output.stdout.as_slice()).into_owned();
248    let blocks = parse_porcelain(report.as_str()).map_err(probe_error)?;
249    if blocks.is_empty() {
250        if output.code == Some(0) {
251            return Ok(Vec::new());
252        }
253        return Err(probe_error(format!(
254            "Git could not determine push updates: {}",
255            String::from_utf8_lossy(&output.stderr).trim_end()
256        )));
257    }
258    let named = push_shape(post_subcommand).and_then(|shape| {
259        return shape.repository;
260    });
261    let mut asking = |query: &[&str]| -> Option<String> {
262        let mut owned: Vec<OsString> = global_prefix.to_vec();
263        owned.extend(query.iter().map(OsString::from));
264        return answer(git, owned.as_slice());
265    };
266    let remote_name: String = resolve_push_remote(named, &mut asking).to_string_lossy().into_owned();
267    // The location Git printed for a single destination is the push URL after every rewrite; it is used as it is
268    //  unless it could have had credentials removed (an `@` in a URL is where they were), which costs one query.
269    let locations: Vec<String> = match blocks.as_slice() {
270        [only] if !only.shown.contains('@') => vec![only.shown.clone()],
271        _ => locations_of(git, global_prefix, remote_name.as_str()),
272    };
273    if locations.len() != blocks.len() {
274        return Err(probe_error(format!(
275            "Git reported {} destinations but {remote_name} has {} push locations",
276            blocks.len(),
277            locations.len()
278        )));
279    }
280    let mut confirmed: Vec<PushUpdate> = Vec::new();
281    for (block, location) in blocks.iter().zip(locations.iter()) {
282        let unnamed: Vec<&str> = block
283            .updates
284            .iter()
285            .filter(|update| {
286                return !update.from.is_empty() && update.after.is_none();
287            })
288            .map(|update| {
289                return update.from.as_str();
290            })
291            .collect();
292        let mut resolved = local_objects(git, global_prefix, unnamed.as_slice())?.into_iter();
293        let group: Vec<(PorcelainUpdate, Option<String>)> = block
294            .updates
295            .iter()
296            .map(|update| {
297                let local: Option<String> = if update.from.is_empty() {
298                    None
299                } else {
300                    update.after.clone().or_else(|| {
301                        return resolved.next();
302                    })
303                };
304                return (update.clone(), local);
305            })
306            .collect();
307        confirmed.extend(confirm_group(git, location.as_str(), remote_name.as_str(), group.as_slice())?);
308    }
309    return Ok(confirmed);
310}
311
312/// The probe's arguments and its confirmation rules are controlled in the test module.
313#[cfg(test)]
314#[path = "manual_push_probe_tests.rs"]
315mod tests;