git_policy_cli/
manual_push_probe.rs1use super::auto_push_single_flight::{PushGit, run_query};
19use super::lfs_upload_plan::resolve_push_remote;
21use super::manual_push_porcelain::{PorcelainUpdate, RemoteBefore, parse_porcelain};
22use super::command_push::push_shape;
24use std::ffi::OsString;
26
27#[derive(Clone, Debug, Eq, PartialEq)]
37pub struct ManualPushProbeError {
38 pub message: String,
40}
41
42impl std::fmt::Display for ManualPushProbeError {
43 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
51fn probe_error(message: String) -> ManualPushProbeError {
58 return ManualPushProbeError { message };
59}
60
61#[derive(Clone, Debug, Eq, PartialEq)]
71pub struct PushUpdate {
72 pub local_oid: Option<String>,
74 pub remote_oid: Option<String>,
76 pub remote_name: String,
78 pub remote_ref: String,
80}
81
82pub 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 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
119fn 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
128fn 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
139fn 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
166pub 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
229pub 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 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#[cfg(test)]
314#[path = "manual_push_probe_tests.rs"]
315mod tests;