git_policy_cli/repair/package_repair_command.rs
1//! What:
2//! Starting one package-manager program for a worktree repair: finding it on a search path, running it in a directory with
3//! its output captured and a quiet window, and saying how it ended.
4//! Why:
5//! The repairs of a new worktree (`package_repair.rs`) start tools the repository uses (pnpm, Cargo, mpm-shadow). Each one
6//! must end in a plain verdict the add can word for the person: the program is missing, it failed with a reason, it showed
7//! no sign of work for its window, or it worked. A tool that works is never ended for being slow (owner, 2026-11-03:
8//! "Install online during the add"; pick 9 of `doc/planning/cli-git-shipped-limits-audit.md`, the coordinator's under the
9//! owner's delegation and open to the owner's veto), with the signs of work the push reads (`push_progress.rs`). Nothing here decides which tool runs or what its output means.
10//!
11//! In TS you'd write (pseudocode):
12//! ```ts
13//! const program = findProgram('pnpm', process.env.PATH);
14//! const run = await runTool(program, { arguments: ['install'], directory, set: [] }, quietWindow);
15//! ```
16
17/// The patience of a run that ends on a stall.
18use crate::bounded_push::Patience;
19/// The clock that reads the signs of work of a process tree.
20use crate::push_progress::Clock;
21/// The longest quiet gap of each tool, kept for the timing records.
22use crate::quiet_ledger;
23use std::ffi::{OsStr, OsString};
24use std::path::{Path, PathBuf};
25use std::process::{Child, Command, Stdio};
26use std::time::{Duration, Instant};
27
28/// What:
29/// One program start: its arguments, the directory it runs in, and the variables added to its environment.
30/// Why:
31/// The program path is found separately, so a test can name a fixture and a person's search path is read once.
32///
33/// In TS you'd write (pseudocode):
34/// ```ts
35/// type ToolCommand = { arguments: string[]; directory: string; set: [string, string][] };
36/// ```
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct ToolCommand {
39 /// The arguments after the program name.
40 pub arguments: Vec<OsString>,
41 /// The working directory.
42 pub directory: PathBuf,
43 /// Variables added to the inherited environment.
44 pub set: Vec<(OsString, OsString)>,
45}
46
47/// What:
48/// How a started program ended.
49/// Why:
50/// The repair words each case differently, so they stay apart.
51///
52/// In TS you'd write (pseudocode):
53/// ```ts
54/// type ToolEnd = { kind: 'succeeded' } | { kind: 'failed'; reason: string } | { kind: 'timed-out' };
55/// ```
56#[derive(Clone, Debug, Eq, PartialEq)]
57pub enum ToolEnd {
58 /// Exit status zero.
59 Succeeded,
60 /// The program did not start, or ended with a failure status; the text names the status and the tail of its output.
61 Failed(String),
62 /// The program showed no sign of work for its window, and was stopped.
63 TimedOut,
64}
65
66/// What:
67/// The end of one run and how long it took.
68/// Why:
69/// The time is reported to the person and measured by the docs.
70///
71/// In TS you'd write (pseudocode):
72/// ```ts
73/// type ToolRun = { end: ToolEnd; millis: number; stdout: Uint8Array };
74/// ```
75#[derive(Clone, Debug, Eq, PartialEq)]
76pub struct ToolRun {
77 /// How the program ended.
78 pub end: ToolEnd,
79 /// Wall time from start to end, in milliseconds.
80 pub millis: u128,
81 /// What the program wrote to its standard output; empty when it did not run to its end.
82 pub stdout: Vec<u8>,
83}
84
85/// The most bytes of a program's output kept for its failure text.
86/// Exempt from a citation under `LQM` (class: display cap): it limits how much text a message, log field or record
87/// names, and no command result or duration depends on it. Classed once in `doc/planning/cli-git-shipped-limits-
88/// audit.md`, "Exempt limits"; the coordinator's pick under the owner's delegation, open to the owner's veto.
89const OUTPUT_TAIL_BYTES: usize = 600;
90
91/// How often a running program is looked at.
92const POLL_INTERVAL: Duration = Duration::from_millis(10);
93
94/// What:
95/// The first executable file named `name` in a search path.
96/// Why:
97/// The program is the one the person's environment resolves; a missing one is a verdict, not a failure to start.
98///
99/// In TS you'd write (pseudocode):
100/// ```ts
101/// function findProgram(name: string, searchPath?: string): string | undefined;
102/// ```
103pub fn find_program(name: &str, search_path: Option<&OsStr>) -> Option<PathBuf> {
104 use std::os::unix::fs::PermissionsExt;
105 let search: &OsStr = search_path?;
106 for directory in std::env::split_paths(search) {
107 // An empty entry means the current directory in a shell; a repair never runs a program found there.
108 if directory.as_os_str().is_empty() {
109 continue;
110 }
111 let candidate: PathBuf = directory.join(name);
112 let runnable: bool = std::fs::metadata(&candidate).is_ok_and(|found: std::fs::Metadata| { return found.is_file() && found.permissions().mode() & 0o111 != 0; });
113 if runnable {
114 return Some(candidate);
115 }
116 }
117 return None;
118}
119
120/// What:
121/// The last bytes of what a program printed, as text, with the cut ragged edge dropped.
122/// Why:
123/// A failure is worded with the end of the output, where tools print their reason; the start is progress noise.
124///
125/// In TS you'd write (pseudocode):
126/// ```ts
127/// function tailOf(bytes: Uint8Array): string;
128/// ```
129fn tail_of(bytes: &[u8]) -> String {
130 let cut: usize = bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
131 let text: String = String::from_utf8_lossy(&bytes[cut..]).into_owned();
132 // Lines that only say a tool waited for another process say nothing about why it failed.
133 let informative: String = text.lines().filter(|line: &&str| { return !line.trim_start().starts_with("Blocking waiting for file lock"); }).collect::<Vec<&str>>().join("\n");
134 let trimmed: &str = informative.trim();
135 if cut == 0 {
136 return trimmed.to_owned();
137 }
138 return trimmed.split_once('\n').map_or(trimmed, |(_ragged, rest): (&str, &str)| { return rest; }).trim().to_owned();
139}
140
141/// What:
142/// Read a pipe to its end on a thread of its own and hand back everything it carried.
143/// Why:
144/// A program that fills a pipe nobody reads stops; reading both of its pipes at once keeps it running.
145///
146/// In TS you'd write (pseudocode):
147/// ```ts
148/// const collected = collect(child.stdout);
149/// ```
150fn collect<R: std::io::Read + Send + 'static>(mut pipe: R) -> std::thread::JoinHandle<Vec<u8>> {
151 return std::thread::spawn(move || {
152 let mut bytes: Vec<u8> = Vec::new();
153 // A read that fails ends the collection; what was read before it is still the program's output.
154 let _ended = pipe.read_to_end(&mut bytes);
155 return bytes;
156 });
157}
158
159/// What:
160/// How a finished program's status is worded.
161/// Why:
162/// A signal has no code, and the person should see which of the two ended the program.
163///
164/// In TS you'd write (pseudocode):
165/// ```ts
166/// function describeStatus(status: ExitStatus): string;
167/// ```
168fn describe_status(status: std::process::ExitStatus) -> String {
169 use std::os::unix::process::ExitStatusExt;
170 return match (status.code(), status.signal()) {
171 (Some(code), _) => format!("exit status {code}"),
172 (None, Some(signal)) => format!("stopped by signal {signal}"),
173 (None, None) => String::from("ended without a status"),
174 };
175}
176
177/// What:
178/// Run a program to its end, or until it has shown no sign of work for `window`.
179/// Why:
180/// The add must not wait for a tool that does nothing, and must keep the tail of its output for the log. A tool that works is
181/// waited for however long it takes. The program leads a process group of its own, so the stop reaches the children it
182/// started too. Where the system counts nothing (no `/proc/<pid>/io`) the tool is never ended, because no wall-clock bound is
183/// the rule. The longest quiet gap of the run is kept in the ledger under the program's name and first argument.
184///
185/// In TS you'd write (pseudocode):
186/// ```ts
187/// async function runTool(program: string, command: ToolCommand, quietWindowMs: number): Promise<ToolRun>;
188/// ```
189pub fn run_tool(program: &Path, command: &ToolCommand, window: Duration) -> ToolRun {
190 use std::os::unix::process::CommandExt;
191 let started: Instant = Instant::now();
192 let mut starting: Command = Command::new(program);
193 starting.args(&command.arguments).current_dir(&command.directory).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0);
194 for (name, value) in &command.set {
195 starting.env(name, value);
196 }
197 let mut child: Child = match starting.spawn() {
198 Ok(running) => running,
199 Err(error) => return ToolRun { end: ToolEnd::Failed(format!("{} could not start: {error}", program.display())), millis: started.elapsed().as_millis(), stdout: Vec::new() },
200 };
201 let out_reader: Option<std::thread::JoinHandle<Vec<u8>>> = child.stdout.take().map(collect);
202 let error_reader: Option<std::thread::JoinHandle<Vec<u8>>> = child.stderr.take().map(collect);
203 let mut clock: Clock = Clock::start(child.id(), Patience::Progress { stall: window }).without_wall_fallback();
204 let status: Option<std::process::ExitStatus> = loop {
205 match child.try_wait() {
206 Ok(Some(done)) => break Some(done),
207 Ok(None) if clock.check().is_some() => break None,
208 Ok(None) => std::thread::sleep(POLL_INTERVAL),
209 Err(error) => return ToolRun { end: ToolEnd::Failed(format!("{} could not be waited for: {error}", program.display())), millis: started.elapsed().as_millis(), stdout: Vec::new() },
210 }
211 };
212 // A clock that reads nothing (no `/proc`) has no quiet gap to keep: its figure would be the elapsed time.
213 if clock.measures() {
214 quiet_ledger::note(tool_step(program, command).as_str(), clock.longest_quiet(), status.is_none());
215 }
216 let Some(finished) = status else {
217 stop_group(&child);
218 // The group is gone, so the pipes close and the readers end; the reaped child leaves no zombie.
219 let _reaped = child.wait();
220 for reader in [out_reader, error_reader].into_iter().flatten() {
221 let _output = reader.join();
222 }
223 return ToolRun { end: ToolEnd::TimedOut, millis: started.elapsed().as_millis(), stdout: Vec::new() };
224 };
225 let stdout: Vec<u8> = out_reader.map(|reader| { return reader.join().unwrap_or_default(); }).unwrap_or_default();
226 let errors: Vec<u8> = error_reader.map(|reader| { return reader.join().unwrap_or_default(); }).unwrap_or_default();
227 let millis: u128 = started.elapsed().as_millis();
228 if finished.success() {
229 return ToolRun { end: ToolEnd::Succeeded, millis, stdout };
230 }
231 let combined: Vec<u8> = [stdout.as_slice(), errors.as_slice()].concat();
232 let text: String = tail_of(combined.as_slice());
233 return ToolRun { end: ToolEnd::Failed(format!("{}: {text}", describe_status(finished))), millis, stdout: Vec::new() };
234}
235
236/// What:
237/// The name a tool's quiet gap is kept under: the program's file name and its first argument, as in `pnpm install`.
238/// Why:
239/// Two uses of one program (`cargo metadata`, `cargo clean`) have different gaps, and the arguments after the first are
240/// paths that would make a name for every worktree.
241///
242/// In TS you'd write (pseudocode):
243/// ```ts
244/// [basename(program), args[0]].filter(Boolean).join(' ')
245/// ```
246fn tool_step(program: &Path, command: &ToolCommand) -> String {
247 let name: String = program.file_name().map_or_else(String::new, |file| { return file.to_string_lossy().into_owned(); });
248 return match command.arguments.first() {
249 Some(first) => format!("{name} {}", first.to_string_lossy()),
250 None => name,
251 };
252}
253
254/// What:
255/// Stop the child's whole process group.
256/// Why:
257/// pnpm and Cargo start helpers; stopping only the leader would leave them running against the worktree.
258///
259/// In TS you'd write (pseudocode):
260/// ```ts
261/// process.kill(-child.pid, 'SIGKILL');
262/// ```
263fn stop_group(child: &Child) {
264 let Ok(leader) = libc::pid_t::try_from(child.id()) else { return };
265 // SAFETY: `kill` takes a process-group id and a signal number and touches no memory; the group was made by this process.
266 let _stopped = unsafe { libc::kill(-leader, libc::SIGKILL) };
267}
268
269/// Command controls stay out of the release executable.
270#[cfg(test)]
271#[path = "package_repair_command_tests.rs"]
272mod tests;