Skip to main content

git_proc/
lib.rs

1#![doc = include_str!("../README.md")]
2
3/// Generate a pair of flag methods: unconditional and conditional.
4///
5/// The unconditional method calls the conditional one with `true`.
6///
7/// # Example
8///
9/// ```ignore
10/// flag_methods! {
11///     /// Enable foo mode.
12///     ///
13///     /// Corresponds to `--foo`.
14///     pub fn foo / foo_if, foo_field, "Conditionally enable foo mode."
15/// }
16/// ```
17///
18/// Generates:
19/// - `pub fn foo(self) -> Self` - calls `foo_if(true)`
20/// - `pub fn foo_if(mut self, value: bool) -> Self` - sets `self.foo_field = value`
21#[doc(hidden)]
22#[macro_export]
23macro_rules! flag_methods {
24    (
25        $(#[$attr:meta])*
26        $vis:vis fn $name:ident / $name_if:ident, $field:ident, $doc_if:literal
27    ) => {
28        $(#[$attr])*
29        #[must_use]
30        $vis fn $name(self) -> Self {
31            self.$name_if(true)
32        }
33
34        #[doc = $doc_if]
35        #[must_use]
36        $vis fn $name_if(mut self, value: bool) -> Self {
37            self.$field = value;
38            self
39        }
40    };
41}
42
43/// Generate inherent `repo_path` / `env_policy` methods and a `RepoPath` trait
44/// implementation for a builder that stores its repository context in a
45/// `base: RepoBase<'a>` field.
46///
47/// `repo_path` sets `-C <path>`; `env_policy` selects the [`EnvPolicy`] applied
48/// before spawning `git`. The inherent methods let callers use `.repo_path()` /
49/// `.env_policy()` without importing a trait, while the `RepoPath` trait remains
50/// available for generic bounds.
51#[doc(hidden)]
52#[macro_export]
53macro_rules! impl_repo_base {
54    ($ty:ident) => {
55        impl<'a> $ty<'a> {
56            /// Set the repository path (`-C <path>`).
57            #[must_use]
58            pub fn repo_path(mut self, path: &'a std::path::Path) -> Self {
59                self.base.repo_path = Some(path);
60                self
61            }
62
63            /// Set the [`EnvPolicy`](crate::EnvPolicy) controlling which inherited
64            /// `GIT_*` variables are cleared before spawning `git`.
65            #[must_use]
66            pub fn env_policy(mut self, policy: $crate::EnvPolicy) -> Self {
67                self.base.env_policy = policy;
68                self
69            }
70        }
71
72        impl<'a> $crate::RepoPath<'a> for $ty<'a> {
73            fn repo_path(self, path: &'a std::path::Path) -> Self {
74                self.repo_path(path)
75            }
76        }
77    };
78}
79
80/// Generate an inherent `env_policy` method for a builder that stores a
81/// `base: RepoBase<'a>` but takes no `-C <path>` (e.g. `init`, `clone`, which
82/// create rather than operate on a repository yet still must not be hijacked by
83/// an ambient git environment).
84#[doc(hidden)]
85#[macro_export]
86macro_rules! impl_env_policy {
87    ($ty:ident) => {
88        impl<'a> $ty<'a> {
89            /// Set the [`EnvPolicy`](crate::EnvPolicy) controlling which inherited
90            /// `GIT_*` variables are cleared before spawning `git`.
91            #[must_use]
92            pub fn env_policy(mut self, policy: $crate::EnvPolicy) -> Self {
93                self.base.env_policy = policy;
94                self
95            }
96        }
97    };
98}
99
100/// Generate a `Cow<'static, str>` tuple newtype with validation, plus a
101/// type-distinct error wrapper.
102///
103/// Invocation: `pub struct $name, $error($inner), "$invalid"`.
104///
105/// Generated:
106/// - `$vis struct $name(Cow<'static, str>)` with `as_str` / `from_static_or_panic`
107/// - `Display`, `AsRef<OsStr>`, `FromStr`, `TryFrom<String>`
108/// - `serde::Serialize` and `serde::Deserialize` (validating via `try_from = "String"`)
109/// - `$vis struct $error(pub $inner)` — a transparent `thiserror::Error`
110///   wrapper, so distinct newtypes can share an inner validation enum
111///   (e.g. `RefFormatError`) yet remain type-distinct
112///
113/// The user is expected to define
114/// `impl $name { const fn validate(input: &str) -> Result<(), $error> { ... } }`
115/// in the same module.
116#[doc(hidden)]
117#[macro_export]
118macro_rules! cow_str_newtype {
119    (
120        $(#[$attr:meta])*
121        $vis:vis struct $name:ident, $error:ident($inner:ty), $invalid:literal
122    ) => {
123        $(#[$attr])*
124        #[derive(Clone, Debug, Eq, PartialEq, ::serde::Deserialize)]
125        #[serde(try_from = "String")]
126        $vis struct $name(::std::borrow::Cow<'static, str>);
127
128        #[doc = concat!("Error returned when parsing an invalid `", stringify!($name), "`.")]
129        #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
130        #[error(transparent)]
131        $vis struct $error(pub $inner);
132
133        impl $name {
134            /// Returns the inner string slice.
135            #[must_use]
136            pub fn as_str(&self) -> &str {
137                &self.0
138            }
139
140            /// Constructs from a static string, panicking if invalid.
141            #[must_use]
142            pub const fn from_static_or_panic(input: &'static str) -> Self {
143                assert!(Self::validate(input).is_ok(), $invalid);
144                Self(::std::borrow::Cow::Borrowed(input))
145            }
146        }
147
148        impl ::std::fmt::Display for $name {
149            fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
150                write!(formatter, "{}", self.0)
151            }
152        }
153
154        impl ::std::convert::AsRef<::std::ffi::OsStr> for $name {
155            fn as_ref(&self) -> &::std::ffi::OsStr {
156                self.as_str().as_ref()
157            }
158        }
159
160        impl ::std::str::FromStr for $name {
161            type Err = $error;
162
163            fn from_str(input: &str) -> ::std::result::Result<Self, Self::Err> {
164                Self::validate(input)?;
165                Ok(Self(::std::borrow::Cow::Owned(input.to_string())))
166            }
167        }
168
169        impl ::std::convert::TryFrom<String> for $name {
170            type Error = $error;
171
172            fn try_from(value: String) -> ::std::result::Result<Self, Self::Error> {
173                value.parse()
174            }
175        }
176
177        impl ::serde::Serialize for $name {
178            fn serialize<S: ::serde::Serializer>(
179                &self,
180                serializer: S,
181            ) -> ::std::result::Result<S::Ok, S::Error> {
182                serializer.serialize_str(self.as_str())
183            }
184        }
185    };
186}
187
188pub mod add;
189pub mod branch;
190pub mod checkout;
191pub mod clean;
192pub mod clone;
193pub mod commit;
194pub mod commit_id;
195pub mod commit_ish;
196pub mod config;
197pub mod diff;
198pub mod fetch;
199pub mod init;
200pub mod ls_remote;
201pub mod push;
202pub mod ref_format;
203pub mod remote;
204pub mod repository;
205pub mod reset;
206pub mod rev_list;
207pub mod rev_parse;
208pub mod show;
209pub mod show_ref;
210pub mod status;
211pub mod symbolic_ref;
212pub mod tag;
213pub mod worktree;
214
215use std::path::Path;
216
217pub use cmd_proc::CommandError;
218
219/// Trait for git command builders that support porcelain output.
220///
221/// Provides the `porcelain` and `porcelain_if` methods to set `--porcelain`.
222pub trait Porcelain: Sized {
223    /// Conditionally enable porcelain output (`--porcelain`).
224    fn porcelain_if(self, value: bool) -> Self;
225
226    /// Enable porcelain output (`--porcelain`).
227    fn porcelain(self) -> Self {
228        self.porcelain_if(true)
229    }
230}
231
232/// Generate inherent `porcelain` / `porcelain_if` methods and a `Porcelain` trait implementation.
233///
234/// The inherent methods set the `porcelain` field.
235/// The trait implementation delegates to the inherent methods.
236///
237/// This ensures callers can use `.porcelain()` without importing the `Porcelain` trait,
238/// while the trait remains available for generic bounds.
239#[doc(hidden)]
240#[macro_export]
241macro_rules! impl_porcelain {
242    ($ty:ident) => {
243        impl<'a> $ty<'a> {
244            /// Give output in machine-parseable format.
245            ///
246            /// Corresponds to `--porcelain`.
247            #[must_use]
248            pub fn porcelain(self) -> Self {
249                self.porcelain_if(true)
250            }
251
252            /// Conditionally enable porcelain output.
253            #[must_use]
254            pub fn porcelain_if(mut self, value: bool) -> Self {
255                self.porcelain = value;
256                self
257            }
258        }
259
260        impl<'a> $crate::Porcelain for $ty<'a> {
261            fn porcelain_if(self, value: bool) -> Self {
262                self.porcelain_if(value)
263            }
264        }
265    };
266}
267
268/// Trait for git command builders that support a repository path.
269///
270/// Provides the `repo_path` method to set `-C <path>`.
271#[must_use = "repo_path returns a modified builder; the return value must be used"]
272pub trait RepoPath<'a>: Sized {
273    /// Set the repository path (`-C <path>`).
274    fn repo_path(self, path: &'a Path) -> Self;
275}
276
277/// Trait for building a command without executing it.
278///
279/// All git command builders implement this trait, allowing you to
280/// access the underlying `cmd_proc::Command` for custom execution.
281///
282/// # Example
283///
284/// ```ignore
285/// use git_proc::Build;
286///
287/// git_proc::fetch::new()
288///     .all()
289///     .build()
290///     .stderr_null()
291///     .status()
292///     .await?;
293/// ```
294pub trait Build {
295    /// Build the command without executing it.
296    ///
297    /// # Errors
298    ///
299    /// Returns [`EnvError`] if git's repository-local environment variables
300    /// could not be resolved (see [`EnvPolicy::ClearLocal`]).
301    fn build(self) -> Result<cmd_proc::Command, EnvError>;
302}
303
304/// Which inherited `GIT_*` environment variables a command clears before
305/// spawning `git`.
306///
307/// Composite operations (`git commit`, `git rebase`) and hooks export `GIT_*`
308/// variables to pin child git processes to *their* repository and index. A
309/// `git_proc` command spawned in that context — a hook, a `git rebase -x`, or a
310/// test launched from one — would otherwise be hijacked onto the ambient
311/// repository instead of the one named by `-C` or the positional directory; most
312/// dangerously `GIT_INDEX_FILE`, which no command-line flag can override.
313#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
314pub enum EnvPolicy {
315    /// Clear git's repository-local variables — `GIT_DIR`, `GIT_INDEX_FILE`,
316    /// `GIT_WORK_TREE`, and the rest of `git rev-parse --local-env-vars`, the
317    /// exact set `git` clears when entering another repository. Fixes the hijack
318    /// while leaving global config/auth (`GIT_SSH_COMMAND`, `GIT_ASKPASS`,
319    /// `GIT_CONFIG_GLOBAL`) intact. The default.
320    #[default]
321    ClearLocal,
322    /// Clear every inherited `GIT_*` variable. Maximally hermetic, but also drops
323    /// env-based auth/config.
324    ClearAll,
325    /// Inherit the ambient git environment unchanged.
326    Inherit,
327}
328
329/// Failure resolving git's repository-local environment variables via
330/// `git rev-parse --local-env-vars`.
331#[derive(Clone, Debug, thiserror::Error)]
332pub enum EnvError {
333    #[error("could not run `git rev-parse --local-env-vars`: {0:?}")]
334    Spawn(std::io::ErrorKind),
335    #[error("`git rev-parse --local-env-vars` exited unsuccessfully")]
336    ExitStatus,
337    #[error("`git rev-parse --local-env-vars` reported an invalid variable name: {0}")]
338    InvalidName(String),
339}
340
341/// Failure running a `git_proc` command: either resolving the git environment
342/// ([`EnvError`]) or executing the process ([`cmd_proc::CommandError`]).
343#[derive(Debug, thiserror::Error)]
344pub enum Error {
345    /// The git environment could not be resolved.
346    #[error(transparent)]
347    Env(#[from] EnvError),
348    /// The git process failed.
349    #[error(transparent)]
350    Command(#[from] cmd_proc::CommandError),
351}
352
353/// Git's repository-local environment variable names, queried once from
354/// `git rev-parse --local-env-vars` so the set always matches the installed git.
355/// The query is run lazily, on the first command built under
356/// [`EnvPolicy::ClearLocal`] that actually inherits a `GIT_*` variable.
357static LOCAL_GIT_ENV: std::sync::LazyLock<Result<Vec<cmd_proc::EnvVariableName>, EnvError>> =
358    std::sync::LazyLock::new(|| {
359        let output = std::process::Command::new("git")
360            .args(["rev-parse", "--local-env-vars"])
361            .output()
362            .map_err(|error| EnvError::Spawn(error.kind()))?;
363
364        if !output.status.success() {
365            return Err(EnvError::ExitStatus);
366        }
367
368        String::from_utf8_lossy(&output.stdout)
369            .lines()
370            .map(str::trim)
371            .filter(|line| !line.is_empty())
372            .map(|line| {
373                line.parse::<cmd_proc::EnvVariableName>()
374                    .map_err(|error| EnvError::InvalidName(error.to_string()))
375            })
376            .collect()
377    });
378
379/// Create a command builder with optional repository path under an explicit
380/// [`EnvPolicy`].
381///
382/// # Errors
383///
384/// Returns [`EnvError`] when the policy is [`EnvPolicy::ClearLocal`], an ambient
385/// `GIT_*` variable is present, and git's local-env-var set could not be
386/// resolved.
387fn base_command_with_policy(
388    repo_path: Option<&Path>,
389    policy: EnvPolicy,
390) -> Result<cmd_proc::Command, EnvError> {
391    let mut command = cmd_proc::Command::new("git");
392
393    for (name, _) in std::env::vars_os() {
394        let Some(name) = name.to_str() else { continue };
395        if !name.starts_with("GIT_") {
396            continue;
397        }
398        let Ok(env_name) = name.parse::<cmd_proc::EnvVariableName>() else {
399            continue;
400        };
401
402        let clear = match policy {
403            EnvPolicy::ClearAll => true,
404            EnvPolicy::Inherit => false,
405            EnvPolicy::ClearLocal => LOCAL_GIT_ENV
406                .as_ref()
407                .map_err(Clone::clone)?
408                .contains(&env_name),
409        };
410
411        if clear {
412            command = command.env_remove(&env_name);
413        }
414    }
415
416    Ok(command.optional_option("-C", repo_path))
417}
418
419/// Repository context threaded through every command builder: the optional
420/// `-C <path>` target and the [`EnvPolicy`] applied before spawning `git`.
421///
422/// Builders hold this as a `base` field (set via the `impl_repo_base!` /
423/// `impl_env_policy!` macros) and call [`RepoBase::command`] to begin their
424/// `git` invocation. Defaults to no `-C` and [`EnvPolicy::ClearLocal`].
425#[derive(Clone, Copy, Debug, Default)]
426pub(crate) struct RepoBase<'a> {
427    pub(crate) repo_path: Option<&'a Path>,
428    pub(crate) env_policy: EnvPolicy,
429}
430
431impl RepoBase<'_> {
432    /// Begin a `git` command: clear the inherited environment per the configured
433    /// [`EnvPolicy`], then apply the optional `-C <path>`.
434    ///
435    /// # Errors
436    ///
437    /// See [`base_command_with_policy`].
438    pub(crate) fn command(self) -> Result<cmd_proc::Command, EnvError> {
439        base_command_with_policy(self.repo_path, self.env_policy)
440    }
441}