Skip to main content

workyard_git/
process.rs

1mod capture;
2mod supervision;
3
4use std::{
5	ffi::{OsStr, OsString},
6	path::{Path, PathBuf},
7	process::ExitStatus,
8};
9use supervision::supervise;
10use workyard_core::{Control, Problem};
11
12/// Exit status and bounded captured streams from a managed Git subprocess.
13pub struct CommandOutput {
14	/// Exit status returned by Git.
15	pub status: ExitStatus,
16	/// Captured standard output bytes.
17	pub stdout: Vec<u8>,
18	/// Captured diagnostic bytes.
19	pub stderr: Vec<u8>,
20	/// Whether output exceeded the capture budget.
21	pub truncated: bool,
22	/// Whether supervision interrupted the command.
23	pub interrupted: bool,
24}
25
26impl CommandOutput {
27	/// Build a diagnostic from the exit status, captured stderr and invocation.
28	pub fn problem(&self, directory: &Path, arguments: &[OsString]) -> Problem {
29		let diagnostic = String::from_utf8_lossy(&self.stderr);
30		let truncation = if self.truncated {
31			" [output truncated]"
32		} else {
33			""
34		};
35		let message = format!(
36			"git {arguments:?} in {directory:?} exited {}: {diagnostic}{truncation}",
37			self.status
38		);
39		let remedy = format!(
40			"Inspect `git -C {directory:?} status` and \
41			`git -C {directory:?} worktree list --porcelain`. \
42			Preserve successful worktrees and resolve the reported Git problem."
43		);
44		let mut problem = Problem::new(workyard_core::ProblemCode::GitFailed, message)
45			.remedy(remedy)
46			.in_repository(directory);
47		problem.detail = Some(Box::new(workyard_core::ProblemDetail::GitDiagnostic(
48			diagnostic.into_owned(),
49		)));
50		problem
51	}
52}
53
54/// Launch and supervise Git commands with bounded output capture.
55#[derive(Clone)]
56pub struct Runner {
57	executable: PathBuf,
58}
59
60impl Default for Runner {
61	fn default() -> Self {
62		Self::new("git")
63	}
64}
65
66impl Runner {
67	/// Select the Git executable to run.
68	pub fn new(executable: impl Into<PathBuf>) -> Self {
69		Self {
70			executable: executable.into(),
71		}
72	}
73
74	/// Execute native arguments in the supplied directory under the cancellation policy.
75	pub async fn run(
76		&self,
77		directory: &Path,
78		arguments: &[OsString],
79		control: &Control,
80	) -> Result<CommandOutput, Problem> {
81		control.check()?;
82		let executable = self.executable.clone();
83		let directory = directory.to_path_buf();
84		let arguments = arguments.to_vec();
85		let control = control.clone();
86		smol::unblock(move || supervise(&executable, &directory, &arguments, &control)).await
87	}
88
89	/// Execute Git with UTF-8 arguments.
90	pub async fn git(
91		&self,
92		directory: &Path,
93		arguments: &[&str],
94		control: &Control,
95	) -> Result<CommandOutput, Problem> {
96		let arguments = args(arguments);
97		self.run(directory, &arguments, control).await
98	}
99
100	pub(crate) async fn effect(
101		&self,
102		directory: &Path,
103		arguments: &[OsString],
104		control: &Control,
105	) -> Result<(), Problem> {
106		let output = self.run(directory, arguments, control).await?;
107		if !output.status.success() {
108			return Err(output.problem(directory, arguments));
109		}
110		// Truncated diagnostics must not discard an observed successful effect.
111		Ok(())
112	}
113
114	/// Return stdout after checking process status and capture completeness.
115	pub async fn checked(
116		&self,
117		directory: &Path,
118		arguments: &[OsString],
119		control: &Control,
120	) -> Result<Vec<u8>, Problem> {
121		let output = self.run(directory, arguments, control).await?;
122		if !output.status.success() {
123			return Err(output.problem(directory, arguments));
124		}
125
126		if output.truncated {
127			return Err(Problem::new(
128				workyard_core::ProblemCode::GitOutputLimit,
129				"Git output exceeded the inspection limit.",
130			));
131		}
132
133		Ok(output.stdout)
134	}
135}
136
137pub(crate) fn args(items: &[impl AsRef<OsStr>]) -> Vec<OsString> {
138	items
139		.iter()
140		.map(|item| item.as_ref().to_os_string())
141		.collect()
142}