Skip to main content

processkit/
client.rs

1//! [`CliClient`] — a small, reusable core for building typed wrappers around an
2//! external CLI tool (`git`, `jj`, `gh`, …).
3//!
4//! It owns the program name, a [`ProcessRunner`], and an optional default
5//! timeout; hands back preconfigured [`Command`]s; and provides the terminal
6//! run/parse helpers a wrapper otherwise repeats. A wrapper then reduces to a
7//! typed facade over its parsers, with no process plumbing — and is mockable by
8//! construction, since the runner is injectable (pass a
9//! [`ScriptedRunner`](crate::testing::ScriptedRunner) in tests).
10//!
11//! The [`cli_client!`](crate::cli_client) macro scaffolds the wrapper struct and
12//! its constructors.
13
14use std::ffi::{OsStr, OsString};
15use std::path::Path;
16use std::sync::Arc;
17use std::time::Duration;
18
19use crate::command::Command;
20use crate::error::{Error, Result};
21use crate::result::ProcessResult;
22use crate::retry::{RetryConfig, RetryPolicy};
23use crate::runner::{JobRunner, ProcessRunner, ProcessRunnerExt};
24
25mod sealed {
26    use std::ffi::OsStr;
27    pub trait Sealed {}
28    impl Sealed for crate::Command {}
29    impl<S: AsRef<OsStr>, const N: usize> Sealed for [S; N] {}
30    impl<S: AsRef<OsStr>, const N: usize> Sealed for &[S; N] {}
31    impl<S: AsRef<OsStr>> Sealed for Vec<S> {}
32    impl<S: AsRef<OsStr>> Sealed for &[S] {}
33}
34
35/// What a [`CliClient`] verb accepts: either an **argument list** — built
36/// into a [`Command`] for the client's program with its defaults (timeout, env,
37/// cancellation) applied — or a ready-made `Command`, run as-is.
38///
39/// This lets one verb serve both the common `git.run(["status"])` and the
40/// customized `git.run(git.command(["push"]).timeout(d))`, removing the
41/// double-mention of the older `git.run(git.command([…]))` form. Implemented for
42/// argument containers (`[S; N]`, `Vec<S>`, `&[S]` where `S: AsRef<OsStr>`) and
43/// for [`Command`]; **sealed** (not implementable downstream).
44///
45/// Either form receives the client's defaults (timeout / env /
46/// [`default_cancel_on`](CliClient::default_cancel_on)): an argument list builds a
47/// fresh command with them, and a ready-made [`Command`] has them **filled into
48/// the gaps it left** — its own explicit settings win, but a client-wide cancel
49/// token / timeout / env still reaches a per-call-customized command rather than
50/// being silently dropped.
51///
52/// **Program note:** a ready-made [`Command`] keeps *its own* `program` — the
53/// client fills only defaults, it does **not** substitute its program. So
54/// `git_client.run(Command::new("rsync"))` runs `rsync`, but with git's
55/// env/timeout/cancel defaults grafted on (e.g. `GIT_TERMINAL_PROMPT=0` on an
56/// rsync process). Pass a [`Command`] to a client's verb only when you want *that
57/// client's* defaults on it; otherwise build from an argument list (which uses
58/// the client's own program) or run the command through its own client.
59pub trait IntoCommand<R: ProcessRunner>: sealed::Sealed {
60    /// Build the [`Command`] to run for `client` — used by the verbs.
61    #[doc(hidden)]
62    fn into_command(self, client: &CliClient<R>) -> Command;
63}
64
65impl<R: ProcessRunner> IntoCommand<R> for Command {
66    fn into_command(self, client: &CliClient<R>) -> Command {
67        // Fill defaults into the caller-supplied command's gaps; its explicit
68        // settings win. Idempotent if `command()` already applied them.
69        client.apply_defaults(self)
70    }
71}
72
73impl<R: ProcessRunner, S: AsRef<OsStr>, const N: usize> IntoCommand<R> for [S; N] {
74    fn into_command(self, client: &CliClient<R>) -> Command {
75        client.command(self)
76    }
77}
78
79impl<R: ProcessRunner, S: AsRef<OsStr>, const N: usize> IntoCommand<R> for &[S; N] {
80    fn into_command(self, client: &CliClient<R>) -> Command {
81        client.command(self)
82    }
83}
84
85impl<R: ProcessRunner, S: AsRef<OsStr>> IntoCommand<R> for Vec<S> {
86    fn into_command(self, client: &CliClient<R>) -> Command {
87        client.command(self)
88    }
89}
90
91impl<R: ProcessRunner, S: AsRef<OsStr>> IntoCommand<R> for &[S] {
92    fn into_command(self, client: &CliClient<R>) -> Command {
93        client.command(self)
94    }
95}
96
97/// Owns a CLI tool's program name, [`ProcessRunner`], and default timeout, and
98/// builds + runs [`Command`]s against them.
99///
100/// Generic over the runner so tests inject a fake; [`new`](Self::new) uses the
101/// real job-backed [`JobRunner`].
102///
103/// `Clone` when the runner is `Clone` — the default [`JobRunner`] is, as are
104/// [`Command`] and [`Pipeline`](crate::Pipeline), so the whole CLI-wrapper family
105/// clones uniformly (e.g. to hand an owned, `'static` value to a spawned task or
106/// an async-runtime bridge). A clone copies the program, timeout, and env
107/// defaults and **shares the same default cancellation token**
108/// ([`default_cancel_on`](Self::default_cancel_on)): cancelling via one clone
109/// cancels every command built from any of them, as a shared token should.
110#[derive(Clone)]
111pub struct CliClient<R: ProcessRunner = JobRunner> {
112    program: OsString,
113    runner: R,
114    timeout: Option<Duration>,
115    /// Environment overrides applied to every built command (`None` = remove),
116    /// in registration order — e.g. `GIT_TERMINAL_PROMPT=0` set once instead of
117    /// on every probe.
118    envs: Vec<(OsString, Option<OsString>)>,
119    /// A cancellation token applied to every built command (see
120    /// [`default_cancel_on`](Self::default_cancel_on)).
121    cancel: Option<tokio_util::sync::CancellationToken>,
122    /// A retry policy + classifier applied to every built command (see
123    /// [`default_retry`](Self::default_retry)).
124    retry: Option<RetryConfig>,
125    /// Per-build env resolvers — `(key, resolver)`, evaluated once when each
126    /// command is built and baked into it (see
127    /// [`default_env_fn`](Self::default_env_fn)).
128    env_fns: Vec<(OsString, EnvResolver)>,
129}
130
131/// A closure that computes an environment value when a command is built — backs
132/// [`CliClient::default_env_fn`]. `Arc`-shared so a `CliClient` stays `Clone`.
133type EnvResolver = Arc<dyn Fn() -> OsString + Send + Sync>;
134
135// Manual Debug: no `Debug` bound on R; env values omitted per secret-safety rule.
136impl<R: ProcessRunner> std::fmt::Debug for CliClient<R> {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        let mut d = f.debug_struct("CliClient");
139        d.field("program", &self.program)
140            .field("timeout", &self.timeout)
141            .field("env_names", &crate::command::redacted_env_names(&self.envs));
142        d.field("has_default_cancel", &self.cancel.is_some());
143        d.field("has_default_retry", &self.retry.is_some());
144        // Dynamic-env *keys* only (names aren't secret; the resolved values are).
145        if !self.env_fns.is_empty() {
146            let keys: Vec<&OsString> = self.env_fns.iter().map(|(key, _)| key).collect();
147            d.field("dynamic_env_keys", &keys);
148        }
149        d.finish_non_exhaustive()
150    }
151}
152
153impl CliClient<JobRunner> {
154    /// A client driving `program` through the real job-backed runner.
155    pub fn new(program: impl AsRef<OsStr>) -> Self {
156        Self {
157            program: program.as_ref().to_os_string(),
158            runner: JobRunner,
159            timeout: None,
160            envs: Vec::new(),
161            cancel: None,
162            retry: None,
163            env_fns: Vec::new(),
164        }
165    }
166}
167
168impl<R: ProcessRunner> CliClient<R> {
169    /// A client driving `program` through `runner` — pass a fake in tests.
170    pub fn with_runner(program: impl AsRef<OsStr>, runner: R) -> Self {
171        Self {
172            program: program.as_ref().to_os_string(),
173            runner,
174            timeout: None,
175            envs: Vec::new(),
176            cancel: None,
177            retry: None,
178            env_fns: Vec::new(),
179        }
180    }
181
182    /// Apply a default timeout to every command this client builds.
183    #[must_use]
184    pub fn default_timeout(mut self, timeout: Duration) -> Self {
185        self.timeout = Some(timeout);
186        self
187    }
188
189    /// Set an environment variable on every command this client builds — e.g.
190    /// `GIT_TERMINAL_PROMPT=0` so a probe can never block on a credential
191    /// prompt. Per-command [`Command::env`] still works and is layered after.
192    ///
193    /// **Duplicate keys: last registration wins** among the *static* env ops
194    /// (`default_env`/[`default_env_remove`](Self::default_env_remove)), matching
195    /// [`Command::env`]'s later-wins: `default_env("K","a").default_env("K","b")`
196    /// yields `K=b`, and a later `default_env_remove("K")` supersedes an earlier
197    /// set. This is *within* the static channel only — a static `default_env`
198    /// always beats a [`default_env_fn`](Self::default_env_fn) for the same key
199    /// regardless of registration order (the resolver is a fallback, never run when
200    /// a static value is present).
201    #[must_use]
202    pub fn default_env(mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> Self {
203        let key = key.as_ref().to_os_string();
204        self.envs
205            .retain(|(k, _)| !crate::command::env_key_eq(k, &key));
206        self.envs.push((key, Some(value.as_ref().to_os_string())));
207        self
208    }
209
210    /// Remove an inherited environment variable on every command this client
211    /// builds. Last registration wins for a repeated key (see
212    /// [`default_env`](Self::default_env)).
213    #[must_use]
214    pub fn default_env_remove(mut self, key: impl AsRef<OsStr>) -> Self {
215        let key = key.as_ref().to_os_string();
216        self.envs
217            .retain(|(k, _)| !crate::command::env_key_eq(k, &key));
218        self.envs.push((key, None));
219        self
220    }
221
222    /// Set an environment variable on every command this client builds to a value
223    /// **computed once per built command** by `resolver` — the dynamic companion to
224    /// [`default_env`](Self::default_env), for a value that must be refreshed for
225    /// each new operation rather than frozen at client construction (a rotating
226    /// token, a per-invocation request id, the current trace span). `resolver` runs
227    /// when each command is built — i.e. once per `command()` / verb call — and the
228    /// value is gap-filled like the other defaults: a per-command
229    /// [`env`](Command::env) / [`env_remove`](Command::env_remove) for the same key
230    /// wins, and an explicit static [`default_env`](Self::default_env) /
231    /// [`default_env_remove`](Self::default_env_remove) for the same key takes
232    /// precedence over the resolver (in which case the resolver is not run at all).
233    /// Lets a typed wrapper
234    /// drop the boilerplate of re-implementing every verb just to inject the value
235    /// first.
236    ///
237    /// **Scope of "fresh":** the value is resolved when the command is built and
238    /// then **baked into that command** — it is *not* re-resolved per process
239    /// spawn. A built command that is retried (via [`default_retry`] /
240    /// [`Command::retry`]) or run more than once reuses the value captured at build
241    /// time on every attempt. So this refreshes per *operation*, not per *attempt*:
242    /// suitable for a credential whose lifetime comfortably exceeds the retry
243    /// window, not for a strictly single-use token that must differ between two
244    /// attempts of the same command.
245    ///
246    /// `resolver` runs synchronously on the thread building the command (typically
247    /// an async runtime worker), once per build — keep it cheap and non-blocking;
248    /// cache or fall back inside it rather than blocking on I/O. It is infallible
249    /// (returns a value, not a `Result`): do any fallible resolution inside and have
250    /// it fall back. A panic propagates out of the build like any other; it does not
251    /// corrupt the client. The resolved value lands in the command's env exactly
252    /// like a static [`default_env`](Self::default_env) — and is never logged (env
253    /// values are redacted from `Debug`/tracing). See [`Command::env`]'s **Secrets**
254    /// note for typing/zeroizing a secret value at the call site.
255    ///
256    /// [`default_retry`]: Self::default_retry
257    /// [`Command::env`]: crate::Command::env
258    #[must_use]
259    pub fn default_env_fn<V, F>(mut self, key: impl AsRef<OsStr>, resolver: F) -> Self
260    where
261        V: Into<OsString>,
262        F: Fn() -> V + Send + Sync + 'static,
263    {
264        let key = key.as_ref().to_os_string();
265        // Last registration wins for a repeated key, like `default_env`.
266        self.env_fns
267            .retain(|(k, _)| !crate::command::env_key_eq(k, &key));
268        self.env_fns
269            .push((key, Arc::new(move || resolver().into())));
270        self
271    }
272
273    /// Cancel every command this client builds when `token` fires: each built
274    /// command gets [`cancel_on(token.clone())`](Command::cancel_on), so
275    /// cancelling the token kills every in-flight run of **this client** (the
276    /// whole tree, surfacing [`Error::Cancelled`](crate::Error::Cancelled) on
277    /// the awaiting call — same semantics as the per-command builder).
278    ///
279    /// **Precedence:** a per-command [`Command::cancel_on`] chained on a built
280    /// command *replaces* the default (an explicit setting beats a default,
281    /// like a per-command [`timeout`](Command::timeout) after
282    /// [`default_timeout`](Self::default_timeout)). When both sources should
283    /// fire, wire it explicitly — derive a child of the default
284    /// (`let c = default.child_token()`), hand the command `cancel_on(c.clone())`,
285    /// and have the second source call `c.cancel()` — or simply build a
286    /// dedicated client per scope.
287    ///
288    /// Scope cancellation by client, not by call: clients are cheap — build
289    /// one per cancellable scope and hand each its own token.
290    #[must_use]
291    pub fn default_cancel_on(mut self, token: tokio_util::sync::CancellationToken) -> Self {
292        self.cancel = Some(token);
293        self
294    }
295
296    /// Retry **every** verb of this client whose failure surfaces as an [`Error`]
297    /// the classifier accepts, on a shared [`RetryPolicy`] (exponential backoff +
298    /// cap + jitter) — the client-wide analogue of the per-call
299    /// [`Command::retry`](crate::Command::retry), filled into each built command
300    /// the same way [`default_timeout`](Self::default_timeout) is. A per-command
301    /// [`Command::retry`] / [`retry_with`](crate::Command::retry_with) **wins**
302    /// (gap-fill, not override); this takes the same [`RetryPolicy`] as
303    /// [`Command::retry_with`](crate::Command::retry_with), applied to every verb.
304    ///
305    /// Honored by the success-checking verbs — [`run`](Self::run) /
306    /// [`run_unit`](Self::run_unit) / [`checked`](Self::checked) /
307    /// [`exit_code`](Self::exit_code) / [`probe`](Self::probe) /
308    /// [`parse`](Self::parse) / [`try_parse`](Self::try_parse) — the ones that
309    /// surface failure as an [`Error`] the classifier can inspect
310    /// (read it via [`is_transient`](crate::Error::is_transient) /
311    /// [`is_timeout`](crate::Error::is_timeout) / [`combined`](crate::Error::combined)).
312    /// The non-erroring `output_string`/`output_bytes` paths don't retry.
313    ///
314    /// **Each attempt re-executes the whole command** — a fresh process. Gate
315    /// retries on a classifier that matches *pre-effect* failures; see
316    /// [`Command::retry`]'s caveats on replayed side effects and one-shot stdin.
317    #[must_use]
318    pub fn default_retry(
319        mut self,
320        policy: RetryPolicy,
321        retry_if: impl Fn(&Error) -> bool + Send + Sync + 'static,
322    ) -> Self {
323        self.retry = Some(RetryConfig::new(policy, retry_if));
324        self
325    }
326
327    /// The injected runner — for direct [`ProcessRunner`]/[`ProcessRunnerExt`] use.
328    pub fn runner(&self) -> &R {
329        &self.runner
330    }
331
332    /// The default timeout, if one was set.
333    pub fn timeout(&self) -> Option<Duration> {
334        self.timeout
335    }
336
337    /// A [`Command`] for `program <args>` in the current directory, defaults
338    /// (timeout, env) pre-applied. Chain more builders (`.arg`, `.stdin`, …) for
339    /// dynamic-argument commands.
340    pub fn command<I, S>(&self, args: I) -> Command
341    where
342        I: IntoIterator<Item = S>,
343        S: AsRef<OsStr>,
344    {
345        self.apply_defaults(Command::new(&self.program).args(args))
346    }
347
348    /// A [`Command`] for `program <args>` run in `dir`, defaults (timeout, env)
349    /// pre-applied.
350    pub fn command_in<I, S>(&self, dir: &Path, args: I) -> Command
351    where
352        I: IntoIterator<Item = S>,
353        S: AsRef<OsStr>,
354    {
355        self.apply_defaults(Command::new(&self.program).current_dir(dir).args(args))
356    }
357
358    /// Resolve this client's `program` to a concrete executable path **without
359    /// spawning it** — the client-level preflight, for a *doctor* /
360    /// early-diagnosis check ("is this tool installed?") before running any
361    /// command, with **no** side effects (no process is started).
362    ///
363    /// Builds a command for the client's program with the client's defaults
364    /// applied — so a [`default_env`](Self::default_env) that relocates `PATH`
365    /// (or a [`default_env_fn`](Self::default_env_fn) that does) is honored
366    /// exactly as it would be at launch — then resolves it via
367    /// [`Command::resolve_program`](crate::Command::resolve_program), reusing the
368    /// **same** internal PATH/PATHEXT/execute-bit resolution the real spawn uses.
369    /// The preflight therefore never disagrees with what an actual run of this
370    /// client would find.
371    ///
372    /// Returns the resolved **absolute** path on success. A synchronous, cheap
373    /// filesystem probe — no async runtime is required.
374    ///
375    /// # Errors
376    ///
377    /// [`Error::NotFound`](crate::Error::NotFound) when the program can't be
378    /// located — see [`Command::resolve_program`] for the full contract
379    /// (`searched` diagnostic, [`is_not_found`](crate::Error::is_not_found)
380    /// classification).
381    pub fn resolve_program(&self) -> Result<std::path::PathBuf> {
382        self.command(std::iter::empty::<&OsStr>()).resolve_program()
383    }
384
385    /// Fill the client's defaults into `command`, but only where the command has
386    /// not set them itself — so a fresh [`command()`](Self::command) (no settings)
387    /// gets every default, while a caller-supplied [`Command`] passed straight to
388    /// a verb keeps its own explicit timeout/cancel/env and only fills the gaps
389    /// (so a client-wide cancel token / timeout / env is not silently dropped
390    /// when you customize a single call). Idempotent — running it twice (a verb
391    /// applies it to a command that `command()` already defaulted) is a no-op
392    /// the second time.
393    fn apply_defaults(&self, mut command: Command) -> Command {
394        if command.accepts_default_timeout()
395            && let Some(timeout) = self.timeout
396        {
397            command = command.timeout(timeout);
398        }
399        if command.cancel_token().is_none()
400            && let Some(token) = &self.cancel
401        {
402            command = command.cancel_on(token.clone());
403        }
404        command.fill_default_envs(&self.envs);
405        // Dynamic env defaults, applied after the static ones: resolve and set each
406        // only when the key is still absent — so a per-command `env` or an explicit
407        // `default_env` wins, AND a resolver (which may do real work — read a vault)
408        // never runs when the key is already set at the moment defaults are applied.
409        for (key, resolver) in &self.env_fns {
410            if !command.has_env_override(key) {
411                command = command.env(key, resolver());
412            }
413        }
414        command.fill_default_retry(&self.retry);
415        command
416    }
417
418    /// Run, returning stdout (trailing whitespace trimmed) on success (errors on
419    /// a non-zero exit) — the same verb, with the same semantics, as
420    /// [`Command::run`](crate::Command::run) and
421    /// [`ProcessRunnerExt::run`](crate::ProcessRunnerExt::run). Trims with
422    /// `trim_end`: the trailing newline is noise, but leading whitespace can be
423    /// significant.
424    ///
425    /// Accepts an argument list (`git.run(["status"])`) or a customized
426    /// [`Command`] (`git.run(git.command(["push"]).timeout(d))`) — see
427    /// [`IntoCommand`].
428    ///
429    /// # Errors
430    ///
431    /// The same surface as [`Command::run`](crate::Command::run): a launch
432    /// failure ([`Error::NotFound`] / [`Error::Spawn`] / [`Error::Unsupported`] /
433    /// [`Error::Io`], and — via the client's runner — [`Error::Cancelled`] on a
434    /// pre-cancelled token), a non-accepted exit ([`Error::Exit`]),
435    /// [`Error::Signalled`], [`Error::Timeout`], [`Error::Cancelled`],
436    /// [`Error::OutputTooLarge`] (a fail-loud buffer truncated the presented
437    /// stdout), or [`Error::Stdin`].
438    pub async fn run(&self, call: impl IntoCommand<R>) -> Result<String> {
439        self.runner.run(&call.into_command(self)).await
440    }
441
442    /// Run, requiring an accepted exit, and return the full
443    /// [`ProcessResult`] (untrimmed) — the [`CliClient`] analogue of
444    /// [`ProcessRunnerExt::checked`](crate::ProcessRunnerExt::checked); the
445    /// building block when you need the whole result after success-checking.
446    ///
447    /// # Errors
448    ///
449    /// The same surface as [`Command::checked`](crate::Command::checked): the
450    /// launch failures, plus [`Error::Exit`] / [`Error::Signalled`] /
451    /// [`Error::Timeout`] / [`Error::Cancelled`] / [`Error::Stdin`]. Being the
452    /// lenient building block, it does not fail loud on a bounded-buffer
453    /// truncation, so it never returns [`Error::OutputTooLarge`].
454    pub async fn checked(&self, call: impl IntoCommand<R>) -> Result<ProcessResult<String>> {
455        self.runner.checked(&call.into_command(self)).await
456    }
457
458    /// Run, capturing the full result without erroring on a non-zero exit — the
459    /// same verb as [`ProcessRunner::output_string`].
460    ///
461    /// # Errors
462    ///
463    /// The same surface as
464    /// [`Command::output_string`](crate::Command::output_string): a non-zero
465    /// exit, a timeout, and a signal-kill are *captured* in the returned
466    /// [`ProcessResult`], not raised; beyond the launch failures, only
467    /// [`Error::Cancelled`], [`Error::OutputTooLarge`] (a fail-loud overflow),
468    /// [`Error::Stdin`], and [`Error::Io`] surface.
469    pub async fn output_string(&self, call: impl IntoCommand<R>) -> Result<ProcessResult<String>> {
470        self.runner.output_string(&call.into_command(self)).await
471    }
472
473    /// Run, capturing stdout as **raw bytes** (stderr as text), without erroring
474    /// on a non-zero exit — the same verb as [`ProcessRunner::output_bytes`].
475    /// For binary tools whose stdout is not UTF-8.
476    ///
477    /// # Errors
478    ///
479    /// Identical to [`output_string`](Self::output_string), except a fail-loud
480    /// [`Error::OutputTooLarge`] applies to the raw stdout *byte* ceiling. Note
481    /// that a runner that only implements
482    /// [`output_string`](crate::ProcessRunner::output_string) surfaces
483    /// [`Error::Unsupported`] here (byte capture routes through
484    /// [`start`](crate::ProcessRunner::start)).
485    pub async fn output_bytes(&self, call: impl IntoCommand<R>) -> Result<ProcessResult<Vec<u8>>> {
486        self.runner.output_bytes(&call.into_command(self)).await
487    }
488
489    /// Run for the side effect, discarding stdout (errors on a non-zero exit) —
490    /// the same verb as
491    /// [`ProcessRunnerExt::run_unit`](crate::ProcessRunnerExt::run_unit).
492    ///
493    /// # Errors
494    ///
495    /// The same surface as [`checked`](Self::checked) (launch failures plus
496    /// [`Error::Exit`] / [`Error::Signalled`] / [`Error::Timeout`] /
497    /// [`Error::Cancelled`] / [`Error::Stdin`]); only the output is discarded.
498    pub async fn run_unit(&self, call: impl IntoCommand<R>) -> Result<()> {
499        self.runner.run_unit(&call.into_command(self)).await
500    }
501
502    /// Run and return the exit code (e.g. `git diff --quiet`, `gh auth status`)
503    /// — never errors on a non-zero exit. The same verb as
504    /// [`Command::exit_code`](crate::Command::exit_code).
505    ///
506    /// # Errors
507    ///
508    /// The launch failures, plus — when the run produced no code —
509    /// [`Error::Timeout`], [`Error::Signalled`], or [`Error::Cancelled`]. A
510    /// non-zero exit is returned as the code, not raised.
511    pub async fn exit_code(&self, call: impl IntoCommand<R>) -> Result<i32> {
512        self.runner.exit_code(&call.into_command(self)).await
513    }
514
515    /// Run a predicate and read its exit code as a boolean: exit `0` →
516    /// `Ok(true)`, exit `1` → `Ok(false)`, anything else → `Err`. Collapses the
517    /// `match code { 0 => …, 1 => …, _ => Err }` idiom for commands whose exit
518    /// code is the answer (`git diff --quiet`, `git show-ref --verify --quiet`,
519    /// `grep -q`, …); other codes / timeout / signal-kill all error.
520    ///
521    /// # Errors
522    ///
523    /// Any exit code other than `0`/`1` becomes [`Error::Exit`], and — atop the
524    /// launch failures — a run with no code errors as [`Error::Timeout`],
525    /// [`Error::Signalled`], or [`Error::Cancelled`].
526    pub async fn probe(&self, call: impl IntoCommand<R>) -> Result<bool> {
527        self.runner.probe(&call.into_command(self)).await
528    }
529
530    /// Stream stdout and return the first line matching `predicate` (`None` if
531    /// the stream ends first) — the [`CliClient`] analogue of
532    /// [`ProcessRunnerExt::first_line`](crate::ProcessRunnerExt::first_line),
533    /// bounded by the command's [`timeout`](crate::Command::timeout).
534    ///
535    /// # Errors
536    ///
537    /// The launch failures, plus [`Error::Timeout`] when a command
538    /// [`timeout`](crate::Command::timeout) is set and its deadline elapses
539    /// mid-stream (tearing the process down), [`Error::Cancelled`], or
540    /// [`Error::Io`] while streaming. A stream that ends with no match is
541    /// `Ok(None)`, not an error.
542    pub async fn first_line<F>(
543        &self,
544        call: impl IntoCommand<R>,
545        predicate: F,
546    ) -> Result<Option<String>>
547    where
548        F: Fn(&str) -> bool + Send,
549    {
550        self.runner
551            .first_line(&call.into_command(self), predicate)
552            .await
553    }
554
555    /// Run (errors on a non-zero exit) and feed stdout to an infallible
556    /// `parse` — the shape of git/jj struct-returning commands. Fails loud on a
557    /// bounded-buffer truncation. Delegates to
558    /// [`ProcessRunnerExt::parse`](crate::ProcessRunnerExt::parse).
559    ///
560    /// # Errors
561    ///
562    /// The success-checking surface of [`run`](Self::run) (launch failures plus
563    /// [`Error::Exit`] / [`Error::Signalled`] / [`Error::Timeout`] /
564    /// [`Error::Cancelled`] / [`Error::Stdin`]), plus [`Error::OutputTooLarge`]
565    /// when a fail-loud buffer truncated the stdout the parser would see. The
566    /// `parse` closure is infallible, so it adds no error.
567    pub async fn parse<T, F>(&self, call: impl IntoCommand<R>, parse: F) -> Result<T>
568    where
569        T: Send,
570        F: FnOnce(&str) -> T + Send,
571    {
572        self.runner.parse(&call.into_command(self), parse).await
573    }
574
575    /// Run (errors on a non-zero exit) and feed stdout to a *fallible* `parse` —
576    /// the shape of JSON deserialization, where a parse failure becomes
577    /// [`Error::Parse`](crate::Error::Parse). Fails loud on a bounded-buffer
578    /// truncation. Delegates to
579    /// [`ProcessRunnerExt::try_parse`](crate::ProcessRunnerExt::try_parse).
580    ///
581    /// # Errors
582    ///
583    /// Everything [`parse`](Self::parse) can return, plus whatever the fallible
584    /// `parse` closure yields on malformed output — typically
585    /// [`Error::Parse`](crate::Error::Parse).
586    pub async fn try_parse<T, F>(&self, call: impl IntoCommand<R>, parse: F) -> Result<T>
587    where
588        T: Send,
589        F: FnOnce(&str) -> Result<T> + Send,
590    {
591        self.runner.try_parse(&call.into_command(self), parse).await
592    }
593}
594
595/// Scaffold a typed CLI-wrapper struct around a [`CliClient`].
596///
597/// Expands `cli_client!(pub struct Git => "git");` into a
598/// `struct Git<R: ProcessRunner = JobRunner> { core: CliClient<R> }` with
599/// `new()` (real runner), a `Default` impl, `with_runner(runner)`, and
600/// `default_timeout(d)`. Implement the tool's typed methods on it, delegating to
601/// `self.core` — see the *Wrapping a CLI tool* section of the crate's
602/// `docs/testing.md` guide for a worked example.
603///
604/// This macro is **committed public API**. Because it is `#[macro_export]`,
605/// it lives at the crate root and is a stable part of the surface — the
606/// supported scaffold for typed CLI wrappers. The hand-rolled equivalent (a
607/// struct wrapping [`CliClient`]) remains valid and interchangeable.
608#[macro_export]
609macro_rules! cli_client {
610    ($(#[$meta:meta])* $vis:vis struct $name:ident => $binary:expr) => {
611        $(#[$meta])*
612        $vis struct $name<R: $crate::ProcessRunner = $crate::JobRunner> {
613            core: $crate::CliClient<R>,
614        }
615
616        impl $name<$crate::JobRunner> {
617            /// Create a client driving the real job-backed runner.
618            pub fn new() -> Self {
619                Self { core: $crate::CliClient::new($binary) }
620            }
621        }
622
623        impl ::core::default::Default for $name<$crate::JobRunner> {
624            fn default() -> Self {
625                Self::new()
626            }
627        }
628
629        impl<R: $crate::ProcessRunner> $name<R> {
630            /// Create a client driving `runner` — inject a fake in tests.
631            pub fn with_runner(runner: R) -> Self {
632                Self { core: $crate::CliClient::with_runner($binary, runner) }
633            }
634
635            /// Apply a default timeout to every command this client builds.
636            pub fn default_timeout(mut self, timeout: ::core::time::Duration) -> Self {
637                self.core = self.core.default_timeout(timeout);
638                self
639            }
640
641            /// Set an environment variable on every command this client builds
642            /// (e.g. `GIT_TERMINAL_PROMPT=0`).
643            pub fn default_env(
644                mut self,
645                key: impl ::core::convert::AsRef<::std::ffi::OsStr>,
646                value: impl ::core::convert::AsRef<::std::ffi::OsStr>,
647            ) -> Self {
648                self.core = self.core.default_env(key, value);
649                self
650            }
651
652            /// Remove an inherited environment variable on every command this
653            /// client builds.
654            pub fn default_env_remove(
655                mut self,
656                key: impl ::core::convert::AsRef<::std::ffi::OsStr>,
657            ) -> Self {
658                self.core = self.core.default_env_remove(key);
659                self
660            }
661
662            /// Set an env variable on every command to a value computed per built
663            /// command (see `CliClient::default_env_fn`).
664            pub fn default_env_fn<V, F>(
665                mut self,
666                key: impl ::core::convert::AsRef<::std::ffi::OsStr>,
667                resolver: F,
668            ) -> Self
669            where
670                V: ::core::convert::Into<::std::ffi::OsString>,
671                F: ::core::ops::Fn() -> V
672                    + ::core::marker::Send
673                    + ::core::marker::Sync
674                    + 'static,
675            {
676                self.core = self.core.default_env_fn(key, resolver);
677                self
678            }
679        }
680
681        impl<R: $crate::ProcessRunner> $name<R> {
682            /// Cancel every command this client builds when `token` fires (a
683            /// per-command `cancel_on` replaces the default — see
684            /// `CliClient::default_cancel_on`).
685            pub fn default_cancel_on(mut self, token: $crate::CancellationToken) -> Self {
686                self.core = self.core.default_cancel_on(token);
687                self
688            }
689
690            /// Retry every verb on a shared `RetryPolicy` + classifier
691            /// (see `CliClient::default_retry`).
692            pub fn default_retry(
693                mut self,
694                policy: $crate::RetryPolicy,
695                retry_if: impl Fn(&$crate::Error) -> bool
696                    + ::core::marker::Send
697                    + ::core::marker::Sync
698                    + 'static,
699            ) -> Self {
700                self.core = self.core.default_retry(policy, retry_if);
701                self
702            }
703        }
704    };
705}
706
707#[cfg(test)]
708mod tests {
709    use std::path::Path;
710    use std::time::Duration;
711
712    use super::*;
713    use crate::Error;
714    use crate::testing::{RecordingRunner, Reply, ScriptedRunner};
715
716    #[test]
717    fn debug_redacts_default_env_values_keeping_names() {
718        let client = CliClient::new("git")
719            .default_env("API_TOKEN", "topsecret-value")
720            .default_env_remove("GIT_PAGER");
721        let dbg = format!("{client:?}");
722        assert!(
723            !dbg.contains("topsecret-value"),
724            "env value must not appear in Debug: {dbg}"
725        );
726        assert!(
727            dbg.contains("API_TOKEN") && dbg.contains("GIT_PAGER"),
728            "env names should appear: {dbg}"
729        );
730    }
731
732    #[test]
733    fn client_is_clone_with_the_default_runner() {
734        // `Command`/`Pipeline` are `Clone`; so is the default-runner `CliClient`,
735        // so the whole CLI-wrapper family clones uniformly (e.g. to own a `'static`
736        // value for a spawned task or an async-runtime bridge).
737        fn assert_clone<T: Clone>() {}
738        assert_clone::<CliClient>();
739
740        let client = CliClient::new("git")
741            .default_timeout(Duration::from_secs(3))
742            .default_env("GIT_TERMINAL_PROMPT", "0")
743            .default_cancel_on(tokio_util::sync::CancellationToken::new());
744        let clone = client.clone();
745        // Every field (program, timeout, env defaults, and the presence of a
746        // shared cancel token) survives the clone verbatim.
747        assert_eq!(format!("{client:?}"), format!("{clone:?}"));
748    }
749
750    crate::cli_client!(struct Demo => "git");
751
752    impl<R: ProcessRunner> Demo<R> {
753        async fn head(&self, dir: &Path) -> Result<String> {
754            self.core
755                .run(self.core.command_in(dir, ["rev-parse", "HEAD"]))
756                .await
757        }
758        async fn is_clean(&self, dir: &Path) -> Result<bool> {
759            Ok(self
760                .core
761                .exit_code(self.core.command_in(dir, ["diff", "--quiet"]))
762                .await?
763                == 0)
764        }
765        async fn branches(&self, dir: &Path) -> Result<Vec<String>> {
766            self.core
767                .parse(self.core.command_in(dir, ["branch"]), |s| {
768                    s.lines().map(|l| l.trim().to_owned()).collect()
769                })
770                .await
771        }
772    }
773
774    #[tokio::test]
775    async fn run_trims_trailing_whitespace_only() {
776        let demo = Demo::with_runner(
777            ScriptedRunner::new().on(["git", "rev-parse"], Reply::ok("  abc123 \n")),
778        );
779        assert_eq!(demo.head(Path::new(".")).await.unwrap(), "  abc123");
780    }
781
782    #[tokio::test]
783    async fn exit_code_maps_exit_status() {
784        let demo = Demo::with_runner(ScriptedRunner::new().on(["git", "diff"], Reply::fail(1, "")));
785        assert!(!demo.is_clean(Path::new(".")).await.unwrap());
786    }
787
788    #[tokio::test]
789    async fn parse_builds_a_typed_value() {
790        let demo = Demo::with_runner(
791            ScriptedRunner::new().on(["git", "branch"], Reply::ok("main\nfeature\n")),
792        );
793        assert_eq!(
794            demo.branches(Path::new(".")).await.unwrap(),
795            vec!["main", "feature"]
796        );
797    }
798
799    #[tokio::test]
800    async fn try_parse_maps_failure_to_parse_error() {
801        let client = CliClient::with_runner(
802            "gh",
803            ScriptedRunner::new().fallback(Reply::ok("not a number")),
804        );
805        let err = client
806            .try_parse::<u32, _>(client.command(["x"]), |s| {
807                s.trim().parse::<u32>().map_err(|e| Error::Parse {
808                    program: "gh".into(),
809                    message: e.to_string(),
810                })
811            })
812            .await
813            .unwrap_err();
814        assert!(matches!(err, Error::Parse { .. }), "got {err:?}");
815    }
816
817    #[tokio::test]
818    async fn verbs_accept_args_directly_or_a_customized_command() {
819        use std::time::Duration;
820        let runner = ScriptedRunner::new().on(["git", "status"], Reply::ok("clean"));
821        let client = CliClient::with_runner("git", runner);
822
823        // Argument list — the program comes from the client, defaults applied.
824        assert_eq!(client.run(["status"]).await.unwrap(), "clean");
825        assert_eq!(client.run(vec!["status"]).await.unwrap(), "clean");
826        // A customized Command runs through the same verb (pass-through).
827        let custom = client.command(["status"]).timeout(Duration::from_secs(3));
828        assert_eq!(custom.configured_timeout(), Some(Duration::from_secs(3)));
829        assert_eq!(client.run(custom).await.unwrap(), "clean");
830        let args = ["status"];
831        assert_eq!(client.run(&args).await.unwrap(), "clean");
832        assert_eq!(client.run(&args[..]).await.unwrap(), "clean");
833        let result = client.checked(["status"]).await.unwrap();
834        assert_eq!(result.stdout(), "clean");
835    }
836
837    #[tokio::test]
838    async fn first_line_verb_streams_and_matches() {
839        let runner =
840            ScriptedRunner::new().on(["git", "log"], Reply::lines(["one", "two", "three"]));
841        let client = CliClient::with_runner("git", runner);
842        let found = client
843            .first_line(["log"], |line| line.starts_with('t'))
844            .await
845            .unwrap();
846        assert_eq!(found.as_deref(), Some("two"));
847    }
848
849    #[tokio::test]
850    async fn when_predicate_reads_public_command_accessors() {
851        // Proves `Command`'s accessors are public enough for an external
852        // `ScriptedRunner::when` predicate to inspect the command.
853        let runner = ScriptedRunner::new()
854            .when(
855                |c| c.working_dir() == Some(Path::new("/repo")),
856                Reply::ok("in-repo"),
857            )
858            .fallback(Reply::ok("elsewhere"));
859        let client = CliClient::with_runner("git", runner);
860        assert_eq!(
861            client
862                .run(client.command_in(Path::new("/repo"), ["status"]))
863                .await
864                .unwrap(),
865            "in-repo"
866        );
867        assert_eq!(
868            client.run(client.command(["status"])).await.unwrap(),
869            "elsewhere"
870        );
871    }
872
873    #[tokio::test]
874    async fn recording_runner_captures_args_cwd_and_absence() {
875        let rec = RecordingRunner::replying(Reply::ok("https://gh/pr/2\n"));
876        let client = CliClient::with_runner("gh", &rec);
877        let _ = client
878            .run(client.command_in(Path::new("/repo"), ["pr", "create", "--title", "T"]))
879            .await
880            .unwrap();
881
882        let call = rec.only_call();
883        assert_eq!(call.cwd.as_deref(), Some(std::path::Path::new("/repo")));
884        assert_eq!(call.args_str(), ["pr", "create", "--title", "T"]);
885        assert!(!call.has_flag("--base"), "no --base flag was passed");
886    }
887
888    #[tokio::test]
889    async fn exit_code_errors_on_timeout() {
890        let client = CliClient::with_runner("gh", ScriptedRunner::new().fallback(Reply::timeout()));
891        assert!(matches!(
892            client
893                .exit_code(client.command(["auth", "status"]))
894                .await
895                .unwrap_err(),
896            Error::Timeout { .. }
897        ));
898    }
899
900    #[tokio::test]
901    async fn default_timeout_is_applied() {
902        let client = CliClient::new("git").default_timeout(Duration::from_secs(7));
903        assert_eq!(
904            client.command(["status"]).configured_timeout(),
905            Some(Duration::from_secs(7))
906        );
907    }
908
909    #[tokio::test]
910    async fn probe_maps_exit_code_to_bool() {
911        let client = CliClient::with_runner(
912            "git",
913            ScriptedRunner::new()
914                .on(["git", "diff"], Reply::fail(1, ""))
915                .fallback(Reply::ok("")),
916        );
917        // `git diff --quiet` exits 1 (dirty) -> false; anything else (0) -> true.
918        assert!(
919            !client
920                .probe(client.command(["diff", "--quiet"]))
921                .await
922                .unwrap()
923        );
924        assert!(client.probe(client.command(["status"])).await.unwrap());
925    }
926
927    #[tokio::test]
928    async fn default_env_is_applied_to_every_command() {
929        use std::ffi::OsString;
930        let client = CliClient::new("git").default_env("GIT_TERMINAL_PROMPT", "0");
931        for cmd in [
932            client.command(["status"]),
933            client.command_in(Path::new("."), ["fetch"]),
934        ] {
935            assert!(
936                cmd.env_overrides()
937                    .iter()
938                    .any(|(k, v)| k == "GIT_TERMINAL_PROMPT"
939                        && v.as_deref() == Some(OsString::from("0").as_os_str())),
940                "default env missing on built command",
941            );
942        }
943    }
944
945    #[tokio::test]
946    async fn default_env_reaches_the_invocation() {
947        let rec = RecordingRunner::replying(Reply::ok("ok\n"));
948        let client = CliClient::with_runner("git", &rec).default_env("GIT_TERMINAL_PROMPT", "0");
949        let _ = client.run(client.command(["status"])).await.unwrap();
950        let call = rec.only_call();
951        assert!(
952            call.envs
953                .iter()
954                .any(|(k, v)| k == "GIT_TERMINAL_PROMPT" && v.is_some()),
955            "env override did not reach the runner: {:?}",
956            call.envs
957        );
958    }
959
960    #[test]
961    fn duplicate_default_env_is_last_registration_wins() {
962        use std::ffi::OsString;
963        // G3: matches Command::env's later-wins (was first-wins).
964        let client = CliClient::new("tool")
965            .default_env("K", "a")
966            .default_env("K", "b");
967        let cmd = client.command(["x"]);
968        let vals: Vec<_> = cmd
969            .env_overrides()
970            .iter()
971            .filter(|(k, _)| k == "K")
972            .collect();
973        assert_eq!(
974            vals.len(),
975            1,
976            "duplicate default_env collapses to one entry"
977        );
978        assert_eq!(
979            vals[0].1.as_deref(),
980            Some(OsString::from("b").as_os_str()),
981            "last registration wins"
982        );
983        // A later remove of the same key supersedes an earlier set.
984        let removed = CliClient::new("tool")
985            .default_env("K", "a")
986            .default_env_remove("K")
987            .command(["x"]);
988        let k: Vec<_> = removed
989            .env_overrides()
990            .iter()
991            .filter(|(k, _)| k == "K")
992            .collect();
993        assert_eq!(k.len(), 1);
994        assert_eq!(k[0].1, None, "the later remove wins");
995
996        // Cross-channel: last-wins is *within* a channel. A static `default_env`
997        // beats a `default_env_fn` for the same key EVEN when the fn is registered
998        // later — the resolver is a fallback, so static-beats-dynamic is orthogonal
999        // to registration order.
1000        let static_wins = CliClient::new("tool")
1001            .default_env("K", "static")
1002            .default_env_fn("K", || "dynamic")
1003            .command(["x"]);
1004        assert!(
1005            static_wins.env_overrides().iter().any(
1006                |(k, v)| k == "K" && v.as_deref() == Some(OsString::from("static").as_os_str())
1007            ),
1008            "a static default_env beats a later-registered default_env_fn"
1009        );
1010    }
1011
1012    #[test]
1013    fn no_timeout_command_ignores_a_client_default_timeout() {
1014        // G4: an explicitly-unbounded command opts out of the client gap-fill.
1015        let client = CliClient::new("tail").default_timeout(Duration::from_secs(9));
1016        let bounded = Command::new("tail").into_command(&client);
1017        assert_eq!(
1018            bounded.configured_timeout(),
1019            Some(Duration::from_secs(9)),
1020            "the default fills an unset command"
1021        );
1022        let unbounded = Command::new("tail").no_timeout().into_command(&client);
1023        assert_eq!(
1024            unbounded.configured_timeout(),
1025            None,
1026            "no_timeout opts out of the client default_timeout"
1027        );
1028    }
1029
1030    #[test]
1031    fn env_isolation_ignores_client_env_defaults() {
1032        // G2: a client default_env must not pierce env_clear/inherit_env isolation.
1033        let client = CliClient::new("tool").default_env("LANG", "C");
1034        let isolated = Command::new("tool").env_clear().into_command(&client);
1035        assert!(
1036            !isolated.env_overrides().iter().any(|(k, _)| k == "LANG"),
1037            "env_clear isolates from a client default_env"
1038        );
1039        let plain = Command::new("tool").into_command(&client);
1040        assert!(
1041            plain.env_overrides().iter().any(|(k, _)| k == "LANG"),
1042            "a non-isolated command still gets the client default"
1043        );
1044    }
1045
1046    #[tokio::test]
1047    async fn a_prebuilt_command_passed_to_a_verb_still_gets_client_defaults() {
1048        let token = crate::CancellationToken::new();
1049        let client = CliClient::new("git")
1050            .default_timeout(Duration::from_secs(9))
1051            .default_env("GIT_TERMINAL_PROMPT", "0")
1052            .default_cancel_on(token);
1053
1054        // Built WITHOUT the client (no defaults applied yet).
1055        let raw = Command::new("git").args(["push"]);
1056        let filled = raw.into_command(&client);
1057        assert_eq!(
1058            filled.configured_timeout(),
1059            Some(Duration::from_secs(9)),
1060            "the client default timeout fills the gap"
1061        );
1062        assert!(
1063            filled.cancel_token().is_some(),
1064            "the client cancel token reaches it"
1065        );
1066        assert!(
1067            filled
1068                .env_overrides()
1069                .iter()
1070                .any(|(k, _)| k == "GIT_TERMINAL_PROMPT"),
1071            "the client default env reaches it"
1072        );
1073
1074        let explicit = Command::new("git")
1075            .args(["push"])
1076            .timeout(Duration::from_secs(2))
1077            .env("GIT_TERMINAL_PROMPT", "1");
1078        let filled = explicit.into_command(&client);
1079        assert_eq!(
1080            filled.configured_timeout(),
1081            Some(Duration::from_secs(2)),
1082            "an explicit per-command timeout wins"
1083        );
1084        let prompt: Vec<_> = filled
1085            .env_overrides()
1086            .iter()
1087            .filter(|(k, _)| k == "GIT_TERMINAL_PROMPT")
1088            .collect();
1089        assert_eq!(prompt.len(), 1, "no duplicate env op for the same key");
1090        assert_eq!(
1091            prompt[0].1.as_deref(),
1092            Some(std::ffi::OsStr::new("1")),
1093            "the per-command env value wins over the client default"
1094        );
1095    }
1096
1097    #[tokio::test]
1098    async fn prebuilt_command_env_wins_over_a_case_differing_client_default() {
1099        let client = CliClient::new("git").default_env("Path", "from-client");
1100        let cmd = Command::new("git").env("PATH", "from-command");
1101        let filled = cmd.into_command(&client);
1102        let path_ops: Vec<_> = filled
1103            .env_overrides()
1104            .iter()
1105            .filter(|(k, _)| k.to_str().is_some_and(|k| k.eq_ignore_ascii_case("PATH")))
1106            .collect();
1107        #[cfg(windows)]
1108        {
1109            assert_eq!(
1110                path_ops.len(),
1111                1,
1112                "the case-differing client default for the same var is skipped"
1113            );
1114            assert_eq!(
1115                path_ops[0].1.as_deref(),
1116                Some(std::ffi::OsStr::new("from-command")),
1117                "the explicit per-command value wins"
1118            );
1119        }
1120        #[cfg(not(windows))]
1121        {
1122            assert_eq!(
1123                path_ops.len(),
1124                2,
1125                "on Unix PATH and Path are distinct variables — both kept"
1126            );
1127        }
1128    }
1129
1130    #[tokio::test]
1131    async fn default_cancel_on_is_applied_to_every_command() {
1132        let token = crate::CancellationToken::new();
1133        let client = CliClient::new("git").default_cancel_on(token);
1134        for cmd in [
1135            client.command(["status"]),
1136            client.command_in(Path::new("."), ["fetch"]),
1137        ] {
1138            assert!(
1139                cmd.cancel_token().is_some(),
1140                "default token missing on built command"
1141            );
1142        }
1143        assert!(format!("{client:?}").contains("has_default_cancel: true"));
1144    }
1145
1146    #[tokio::test(start_paused = true)]
1147    async fn per_command_cancel_on_overrides_the_default() {
1148        use crate::CancellationToken;
1149        let default_token = CancellationToken::new();
1150        let explicit = CancellationToken::new();
1151        let client = CliClient::with_runner("gh", ScriptedRunner::new().fallback(Reply::pending()))
1152            .default_cancel_on(default_token.clone());
1153        let cmd = client.command(["run", "watch"]).cancel_on(explicit.clone());
1154
1155        let call = client.output_string(cmd);
1156        tokio::pin!(call);
1157        default_token.cancel();
1158        assert!(
1159            tokio::time::timeout(Duration::from_secs(3600), &mut call)
1160                .await
1161                .is_err(),
1162            "the replaced default token must not cancel the call"
1163        );
1164        explicit.cancel();
1165        let err = tokio::time::timeout(Duration::from_secs(3600), call)
1166            .await
1167            .expect("the explicit token must resolve the call")
1168            .expect_err("explicit token cancels");
1169        assert!(matches!(err, Error::Cancelled { .. }), "got {err:?}");
1170    }
1171
1172    #[tokio::test(start_paused = true)]
1173    async fn acceptance_pending_reply_with_client_default_cancel() {
1174        use crate::CancellationToken;
1175        let token = CancellationToken::new();
1176        let rec = RecordingRunner::new(
1177            ScriptedRunner::new().on(["gh", "run", "watch"], Reply::pending()),
1178        );
1179        let client = CliClient::with_runner("gh", &rec).default_cancel_on(token.clone());
1180
1181        let call = client.output_string(client.command(["run", "watch", "123"]));
1182        tokio::pin!(call);
1183        assert!(
1184            tokio::time::timeout(Duration::from_secs(3600), &mut call)
1185                .await
1186                .is_err(),
1187            "must not resolve before the token fires"
1188        );
1189        token.cancel();
1190        match tokio::time::timeout(Duration::from_secs(3600), call)
1191            .await
1192            .expect("the cancelled token must resolve the call")
1193        {
1194            Err(Error::Cancelled { program }) => assert_eq!(program, "gh"),
1195            other => panic!("expected Error::Cancelled, got {other:?}"),
1196        }
1197        assert_eq!(rec.only_call().args_str(), ["run", "watch", "123"]);
1198    }
1199
1200    #[tokio::test(start_paused = true)]
1201    async fn clone_shares_the_default_cancel_token() {
1202        // The load-bearing half of `CliClient: Clone`'s doc: a clone shares the
1203        // SAME default cancel token, not a copy. A command built from the *clone*
1204        // must therefore respond to the token the *original* was built with —
1205        // parking until it fires, then resolving as `Cancelled`.
1206        use crate::CancellationToken;
1207        let token = CancellationToken::new();
1208        let rec = RecordingRunner::new(
1209            ScriptedRunner::new().on(["gh", "run", "watch"], Reply::pending()),
1210        );
1211        let original = CliClient::with_runner("gh", &rec).default_cancel_on(token.clone());
1212        let clone = original.clone();
1213
1214        let call = clone.output_string(clone.command(["run", "watch", "123"]));
1215        tokio::pin!(call);
1216        assert!(
1217            tokio::time::timeout(Duration::from_secs(3600), &mut call)
1218                .await
1219                .is_err(),
1220            "the clone's command must park on the shared token, not resolve early"
1221        );
1222        token.cancel();
1223        match tokio::time::timeout(Duration::from_secs(3600), call)
1224            .await
1225            .expect("cancelling the shared token must resolve the clone's call")
1226        {
1227            Err(Error::Cancelled { program }) => assert_eq!(program, "gh"),
1228            other => panic!("expected Error::Cancelled, got {other:?}"),
1229        }
1230    }
1231
1232    #[test]
1233    fn macro_emits_default_cancel_on() {
1234        let _client = Demo::with_runner(ScriptedRunner::new())
1235            .default_cancel_on(crate::CancellationToken::new());
1236    }
1237
1238    #[test]
1239    fn macro_emits_default_env_fn() {
1240        let _client = Demo::with_runner(ScriptedRunner::new()).default_env_fn("TOKEN", || "x");
1241    }
1242
1243    #[test]
1244    fn default_env_fn_resolves_per_build_and_respects_precedence() {
1245        use crate::testing::Invocation;
1246        use std::sync::Arc;
1247        use std::sync::atomic::{AtomicU32, Ordering};
1248
1249        let counter = Arc::new(AtomicU32::new(0));
1250        let c = Arc::clone(&counter);
1251        let client = CliClient::new("git").default_env_fn("TOKEN", move || {
1252            format!("t{}", c.fetch_add(1, Ordering::SeqCst))
1253        });
1254
1255        // Each built command resolves a FRESH value.
1256        let inv1 = Invocation::from_command(&client.command(["status"]));
1257        let inv2 = Invocation::from_command(&client.command(["status"]));
1258        assert!(inv1.env_is("TOKEN", "t0"));
1259        assert!(inv2.env_is("TOKEN", "t1"));
1260
1261        // A pre-built command that sets TOKEN keeps its own value, and the resolver
1262        // is NOT invoked for it (the counter stays at the 2 resolves above).
1263        let filled = client.apply_defaults(Command::new("git").env("TOKEN", "explicit"));
1264        assert!(Invocation::from_command(&filled).env_is("TOKEN", "explicit"));
1265        assert_eq!(
1266            counter.load(Ordering::SeqCst),
1267            2,
1268            "the resolver must be skipped when the key is already set"
1269        );
1270    }
1271
1272    #[test]
1273    fn default_env_fn_precedence_against_static_and_self() {
1274        use crate::testing::Invocation;
1275        use std::sync::Arc;
1276        use std::sync::atomic::{AtomicU32, Ordering};
1277
1278        // (a) A static `default_env` for the same key wins, and the resolver is
1279        //     skipped entirely (the doc's stated precedence).
1280        let calls = Arc::new(AtomicU32::new(0));
1281        let c = Arc::clone(&calls);
1282        let client = CliClient::new("git")
1283            .default_env("TOKEN", "static")
1284            .default_env_fn("TOKEN", move || {
1285                c.fetch_add(1, Ordering::SeqCst);
1286                "dynamic"
1287            });
1288        let inv = Invocation::from_command(&client.command(["status"]));
1289        assert!(inv.env_is("TOKEN", "static"));
1290        assert_eq!(
1291            calls.load(Ordering::SeqCst),
1292            0,
1293            "a static default_env must shadow the resolver, which then never runs"
1294        );
1295
1296        // (b) A per-command `env_remove` for the key suppresses the resolver too —
1297        //     an explicit unset beats the dynamic default, like the static one.
1298        let calls = Arc::new(AtomicU32::new(0));
1299        let c = Arc::clone(&calls);
1300        let client = CliClient::new("git").default_env_fn("TOKEN", move || {
1301            c.fetch_add(1, Ordering::SeqCst);
1302            "dynamic"
1303        });
1304        let removed = client.apply_defaults(Command::new("git").env_remove("TOKEN"));
1305        assert!(matches!(
1306            Invocation::from_command(&removed).env("TOKEN"),
1307            Some(None)
1308        ));
1309        assert_eq!(calls.load(Ordering::SeqCst), 0);
1310
1311        // (c) Two resolvers for the same key: the LAST registered wins (G3 —
1312        //     consistent with `default_env`'s later-wins), and the superseded
1313        //     first resolver never runs (it is dropped at registration time).
1314        let first_ran = Arc::new(AtomicU32::new(0));
1315        let f = Arc::clone(&first_ran);
1316        let client = CliClient::new("git")
1317            .default_env_fn("TOKEN", move || {
1318                f.fetch_add(1, Ordering::SeqCst);
1319                "first"
1320            })
1321            .default_env_fn("TOKEN", || "second");
1322        let inv = Invocation::from_command(&client.command(["status"]));
1323        assert!(
1324            inv.env_is("TOKEN", "second"),
1325            "the last-registered resolver wins"
1326        );
1327        assert_eq!(
1328            first_ran.load(Ordering::SeqCst),
1329            0,
1330            "the superseded resolver never runs"
1331        );
1332    }
1333
1334    #[test]
1335    fn default_env_fn_value_is_baked_in_and_stable_across_clone_and_reuse() {
1336        use crate::testing::Invocation;
1337        use std::sync::Arc;
1338        use std::sync::atomic::{AtomicU32, Ordering};
1339
1340        let counter = Arc::new(AtomicU32::new(0));
1341        let c = Arc::clone(&counter);
1342        let client = CliClient::new("git").default_env_fn("TOKEN", move || {
1343            format!("t{}", c.fetch_add(1, Ordering::SeqCst))
1344        });
1345
1346        // A built command captures its value; re-running it (here: re-deriving the
1347        // Invocation) does not re-resolve — the retry loop reuses this same value.
1348        let built = client.command(["status"]);
1349        assert!(Invocation::from_command(&built).env_is("TOKEN", "t0"));
1350        assert!(Invocation::from_command(&built).env_is("TOKEN", "t0"));
1351
1352        // A clone shares the resolver's state (Arc), so it continues the sequence
1353        // rather than restarting it — documents the shared-state semantics.
1354        let clone = client.clone();
1355        assert!(Invocation::from_command(&clone.command(["status"])).env_is("TOKEN", "t1"));
1356        assert_eq!(counter.load(Ordering::SeqCst), 2);
1357    }
1358
1359    #[tokio::test]
1360    async fn default_retry_retries_client_verbs() {
1361        use crate::RetryPolicy;
1362        // on_sequence: a retryable failure then success — the client-wide retry
1363        // re-runs the verb. Exercises the macro-generated `default_retry`, the
1364        // apply_defaults gap-fill, and the retry loop end-to-end.
1365        let demo = Demo::with_runner(ScriptedRunner::new().on_sequence(
1366            ["git", "rev-parse"],
1367            [
1368                Reply::fail(128, "could not read from remote"),
1369                Reply::ok("abc123\n"),
1370            ],
1371        ))
1372        .default_retry(RetryPolicy::new().initial_backoff(Duration::ZERO), |_e| {
1373            true
1374        });
1375        // `head` runs `git rev-parse HEAD`: attempt 1 fails, the retry succeeds.
1376        assert_eq!(demo.head(Path::new(".")).await.unwrap(), "abc123");
1377    }
1378
1379    #[tokio::test]
1380    async fn default_retry_classifier_can_decline() {
1381        use crate::RetryPolicy;
1382        // A classifier that rejects the error → no retry; the first failure surfaces.
1383        let demo = Demo::with_runner(ScriptedRunner::new().on_sequence(
1384            ["git", "rev-parse"],
1385            [Reply::fail(128, "fatal"), Reply::ok("abc\n")],
1386        ))
1387        .default_retry(RetryPolicy::new().initial_backoff(Duration::ZERO), |_e| {
1388            false
1389        });
1390        assert!(demo.head(Path::new(".")).await.is_err());
1391    }
1392
1393    #[test]
1394    fn resolve_program_locates_the_clients_program_or_reports_not_found() {
1395        // A path-form program that exists (an executable temp file) resolves to
1396        // its own path, without spawning — the client-level preflight delegating
1397        // to `Command::resolve_program`.
1398        let dir = tempfile::tempdir().expect("temp dir");
1399        let exe = {
1400            #[cfg(unix)]
1401            {
1402                use std::os::unix::fs::PermissionsExt;
1403                let p = dir.path().join("pk-client-doctor");
1404                std::fs::write(&p, b"#!/bin/sh\nexit 0\n").expect("write stub");
1405                std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755))
1406                    .expect("chmod +x");
1407                p
1408            }
1409            #[cfg(not(unix))]
1410            {
1411                let p = dir.path().join("pk-client-doctor.exe");
1412                std::fs::write(&p, b"stub").expect("write stub");
1413                p
1414            }
1415        };
1416        let resolved = CliClient::new(&exe)
1417            .resolve_program()
1418            .expect("an existing program resolves via the client preflight");
1419        assert!(
1420            resolved
1421                .to_string_lossy()
1422                .eq_ignore_ascii_case(&exe.to_string_lossy()),
1423            "expected {exe:?}, got {resolved:?}"
1424        );
1425
1426        // A missing bare program surfaces the typed NotFound, attributed to the
1427        // client's program.
1428        let err = CliClient::new("pk-client-absent-tool-101")
1429            .resolve_program()
1430            .expect_err("a missing program must not resolve");
1431        assert!(err.is_not_found(), "must classify as not-found: {err:?}");
1432        assert_eq!(err.program(), Some("pk-client-absent-tool-101"));
1433    }
1434
1435    #[test]
1436    fn macro_generates_all_constructors() {
1437        let _real = Demo::new();
1438        let _default = Demo::default();
1439        let _fake = Demo::with_runner(ScriptedRunner::new())
1440            .default_timeout(Duration::from_secs(1))
1441            .default_env("GIT_TERMINAL_PROMPT", "0")
1442            .default_env_remove("GIT_PAGER");
1443    }
1444}