#![doc = include_str!("../README.md")]
#[doc(hidden)]
#[macro_export]
macro_rules! flag_methods {
(
$(#[$attr:meta])*
$vis:vis fn $name:ident / $name_if:ident, $field:ident, $doc_if:literal
) => {
$(#[$attr])*
#[must_use]
$vis fn $name(self) -> Self {
self.$name_if(true)
}
#[doc = $doc_if]
#[must_use]
$vis fn $name_if(mut self, value: bool) -> Self {
self.$field = value;
self
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! impl_repo_base {
($ty:ident) => {
impl<'a> $ty<'a> {
#[must_use]
pub fn repo_path(mut self, path: &'a std::path::Path) -> Self {
self.base.repo_path = Some(path);
self
}
#[must_use]
pub fn env_policy(mut self, policy: $crate::EnvPolicy) -> Self {
self.base.env_policy = policy;
self
}
}
impl<'a> $crate::RepoPath<'a> for $ty<'a> {
fn repo_path(self, path: &'a std::path::Path) -> Self {
self.repo_path(path)
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! impl_env_policy {
($ty:ident) => {
impl<'a> $ty<'a> {
#[must_use]
pub fn env_policy(mut self, policy: $crate::EnvPolicy) -> Self {
self.base.env_policy = policy;
self
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! cow_str_newtype {
(
$(#[$attr:meta])*
$vis:vis struct $name:ident, $error:ident($inner:ty), $invalid:literal
) => {
$(#[$attr])*
#[derive(Clone, Debug, Eq, PartialEq, ::serde::Deserialize)]
#[serde(try_from = "String")]
$vis struct $name(::std::borrow::Cow<'static, str>);
#[doc = concat!("Error returned when parsing an invalid `", stringify!($name), "`.")]
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error(transparent)]
$vis struct $error(pub $inner);
impl $name {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub const fn from_static_or_panic(input: &'static str) -> Self {
assert!(Self::validate(input).is_ok(), $invalid);
Self(::std::borrow::Cow::Borrowed(input))
}
}
impl ::std::fmt::Display for $name {
fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(formatter, "{}", self.0)
}
}
impl ::std::convert::AsRef<::std::ffi::OsStr> for $name {
fn as_ref(&self) -> &::std::ffi::OsStr {
self.as_str().as_ref()
}
}
impl ::std::str::FromStr for $name {
type Err = $error;
fn from_str(input: &str) -> ::std::result::Result<Self, Self::Err> {
Self::validate(input)?;
Ok(Self(::std::borrow::Cow::Owned(input.to_string())))
}
}
impl ::std::convert::TryFrom<String> for $name {
type Error = $error;
fn try_from(value: String) -> ::std::result::Result<Self, Self::Error> {
value.parse()
}
}
impl ::serde::Serialize for $name {
fn serialize<S: ::serde::Serializer>(
&self,
serializer: S,
) -> ::std::result::Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
};
}
pub mod add;
pub mod branch;
pub mod checkout;
pub mod clean;
pub mod clone;
pub mod commit;
pub mod commit_id;
pub mod commit_ish;
pub mod config;
pub mod diff;
pub mod fetch;
pub mod init;
pub mod ls_remote;
pub mod push;
pub mod ref_format;
pub mod remote;
pub mod repository;
pub mod reset;
pub mod rev_list;
pub mod rev_parse;
pub mod show;
pub mod show_ref;
pub mod status;
pub mod symbolic_ref;
pub mod tag;
pub mod worktree;
use std::path::Path;
pub use cmd_proc::CommandError;
pub trait Porcelain: Sized {
fn porcelain_if(self, value: bool) -> Self;
fn porcelain(self) -> Self {
self.porcelain_if(true)
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! impl_porcelain {
($ty:ident) => {
impl<'a> $ty<'a> {
#[must_use]
pub fn porcelain(self) -> Self {
self.porcelain_if(true)
}
#[must_use]
pub fn porcelain_if(mut self, value: bool) -> Self {
self.porcelain = value;
self
}
}
impl<'a> $crate::Porcelain for $ty<'a> {
fn porcelain_if(self, value: bool) -> Self {
self.porcelain_if(value)
}
}
};
}
#[must_use = "repo_path returns a modified builder; the return value must be used"]
pub trait RepoPath<'a>: Sized {
fn repo_path(self, path: &'a Path) -> Self;
}
pub trait Build {
fn build(self) -> Result<cmd_proc::Command, EnvError>;
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum EnvPolicy {
#[default]
ClearLocal,
ClearAll,
Inherit,
}
#[derive(Clone, Debug, thiserror::Error)]
pub enum EnvError {
#[error("could not run `git rev-parse --local-env-vars`: {0:?}")]
Spawn(std::io::ErrorKind),
#[error("`git rev-parse --local-env-vars` exited unsuccessfully")]
ExitStatus,
#[error("`git rev-parse --local-env-vars` reported an invalid variable name: {0}")]
InvalidName(String),
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Env(#[from] EnvError),
#[error(transparent)]
Command(#[from] cmd_proc::CommandError),
}
static LOCAL_GIT_ENV: std::sync::LazyLock<Result<Vec<cmd_proc::EnvVariableName>, EnvError>> =
std::sync::LazyLock::new(|| {
let output = std::process::Command::new("git")
.args(["rev-parse", "--local-env-vars"])
.output()
.map_err(|error| EnvError::Spawn(error.kind()))?;
if !output.status.success() {
return Err(EnvError::ExitStatus);
}
String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(|line| {
line.parse::<cmd_proc::EnvVariableName>()
.map_err(|error| EnvError::InvalidName(error.to_string()))
})
.collect()
});
fn base_command_with_policy(
repo_path: Option<&Path>,
policy: EnvPolicy,
) -> Result<cmd_proc::Command, EnvError> {
let mut command = cmd_proc::Command::new("git");
for (name, _) in std::env::vars_os() {
let Some(name) = name.to_str() else { continue };
if !name.starts_with("GIT_") {
continue;
}
let Ok(env_name) = name.parse::<cmd_proc::EnvVariableName>() else {
continue;
};
let clear = match policy {
EnvPolicy::ClearAll => true,
EnvPolicy::Inherit => false,
EnvPolicy::ClearLocal => LOCAL_GIT_ENV
.as_ref()
.map_err(Clone::clone)?
.contains(&env_name),
};
if clear {
command = command.env_remove(&env_name);
}
}
Ok(command.optional_option("-C", repo_path))
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct RepoBase<'a> {
pub(crate) repo_path: Option<&'a Path>,
pub(crate) env_policy: EnvPolicy,
}
impl RepoBase<'_> {
pub(crate) fn command(self) -> Result<cmd_proc::Command, EnvError> {
base_command_with_policy(self.repo_path, self.env_policy)
}
}