use std::collections::{BTreeSet, HashMap};
use std::ffi::OsStr;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use duct::Expression;
use eyre::{Result, WrapErr, eyre};
use gix::{self};
use once_cell::sync::OnceCell;
use xx::file;
use crate::cmd::CmdLineRunner;
use crate::file::touch_dir;
use crate::progress::SingleReport;
use mise_settings::Settings;
use std::ffi::OsString;
pub struct Git {
pub dir: PathBuf,
pub repo: OnceCell<gix::Repository>,
}
macro_rules! git_cmd {
( @worktree $dir:expr $(, $arg:expr )* $(,)? ) => {
{
let safe = format!("safe.directory={}", $dir.display());
sanitize_git_env(cmd!("git", "-c", $crate::git::github_credential_config("github.com"), "-c", $crate::git::github_credential_config("github.com:443"), "-C", $dir, "-c", safe $(, $arg)*))
}
};
( $dir:expr $(, $arg:expr )* $(,)? ) => {
{
let safe = format!("safe.directory={}", $dir.display());
sanitize_git_env(cmd!("git", "-c", $crate::git::github_credential_config("github.com"), "-c", $crate::git::github_credential_config("github.com:443"), "-C", $dir, "-c", safe, "-c", "core.autocrlf=false" $(, $arg)*))
}
}
}
macro_rules! git_cmd_read {
( $dir:expr $(, $arg:expr )* $(,)? ) => {
{
git_cmd!($dir $(, $arg)*).read().wrap_err_with(|| {
let args = [$($arg,)*].join(" ");
format!("git {args} failed")
})
}
}
}
impl Git {
pub fn new<P: AsRef<Path>>(dir: P) -> Self {
Self {
dir: dir.as_ref().to_path_buf(),
repo: OnceCell::new(),
}
}
pub fn repo(&self) -> Result<&gix::Repository> {
self.repo.get_or_try_init(|| {
trace!("opening git repository via gix at {:?}", self.dir);
gix::open(&self.dir)
.wrap_err_with(|| format!("failed to open git repository at {:?}", self.dir))
.inspect_err(|err| warn!("{err:#}"))
})
}
fn remote_name(&self) -> String {
let remotes = match self.repo() {
Ok(repo) => repo
.remote_names()
.iter()
.map(|name| name.to_string())
.collect::<Vec<_>>()
.join("\n"),
Err(_) => git_cmd_read!(&self.dir, "remote").unwrap_or_default(),
};
pick_remote_name(&remotes)
}
pub fn is_repo(&self) -> bool {
self.dir.join(".git").is_dir()
}
pub fn update(&self, gitref: Option<String>) -> Result<(String, String)> {
match gitref {
Some(gitref) => {
let remote_ref_kind = self.remote_ref_kind(&gitref)?;
if remote_ref_kind.is_none() && looks_like_abbreviated_sha(&gitref) {
return Err(eyre!(
"{gitref} is not a branch or tag on the remote, and abbreviated commit SHAs are not supported; use the full commit SHA"
));
}
self.update_ref(gitref, remote_ref_kind)
}
None => self.update_ref(self.current_branch()?, None),
}
}
pub fn update_tag(&self, gitref: String) -> Result<(String, String)> {
self.update_ref(gitref, Some(RemoteRefKind::Tag))
}
fn remote_ref_kind(&self, gitref: &str) -> Result<Option<RemoteRefKind>> {
if gitref.starts_with("refs/") || looks_like_sha(gitref) {
return Ok(None);
}
let branch_ref = format!("refs/heads/{gitref}");
let tag_ref = format!("refs/tags/{gitref}");
let output = git_cmd_read!(
&self.dir,
"ls-remote",
"--refs",
&self.remote_name(),
&branch_ref,
&tag_ref
)?;
Ok(remote_ref_kind(&output, &branch_ref, &tag_ref))
}
fn checkout(&self, gitref: &str) -> Result<()> {
validate_revision("revision", gitref)?;
let target = checkout_target(gitref);
let cmd = git_cmd!(
&self.dir,
"-c",
"advice.detachedHead=false",
"-c",
"advice.objectNameWarning=false",
"checkout",
"--force",
&target,
);
let res = cmd
.stderr_to_stdout()
.stdout_capture()
.unchecked()
.run()
.map_err(|err| eyre!("git failed: {cmd:?} {err:#}"))?;
if !res.status.success() {
return Err(eyre!(
"git failed: {cmd:?} {}",
String::from_utf8_lossy(&res.stdout)
));
}
self.ensure_pinned_commit_checked_out(gitref)?;
touch_dir(&self.dir)?;
Ok(())
}
fn ensure_pinned_commit_checked_out(&self, gitref: &str) -> Result<()> {
if !looks_like_sha(gitref) {
return Ok(());
}
let head = self.current_sha()?;
if !head.eq_ignore_ascii_case(gitref) {
return Err(eyre!(
"{gitref} is not a commit in {}: git checked out {head}",
self.dir.display()
));
}
Ok(())
}
fn update_ref(
&self,
gitref: String,
remote_ref_kind: Option<RemoteRefKind>,
) -> Result<(String, String)> {
debug!("updating {} to {}", self.dir.display(), gitref);
let exec = |cmd: Expression| match cmd.stderr_to_stdout().stdout_capture().unchecked().run()
{
Ok(res) => {
if res.status.success() {
Ok(())
} else {
Err(eyre!(
"git failed: {cmd:?} {}",
String::from_utf8_lossy(&res.stdout)
))
}
}
Err(err) => Err(eyre!("git failed: {cmd:?} {err:#}")),
};
debug!("updating {} to {} with git", self.dir.display(), gitref);
let qualified_ref = remote_ref_kind.map(|kind| qualify_remote_ref(&gitref, kind));
let refspec = qualified_ref
.as_ref()
.map_or_else(|| format!("{gitref}:{gitref}"), |r| format!("{r}:{r}"));
exec(git_cmd!(
&self.dir,
"fetch",
"--prune",
"--update-head-ok",
&self.remote_name(),
&refspec
))?;
let prev_rev = self.current_sha()?;
let checkout_ref = match (remote_ref_kind, qualified_ref.as_deref()) {
(Some(RemoteRefKind::Tag), Some(tag_ref)) => tag_ref.to_string(),
(None, _) => checkout_target(&gitref),
_ => gitref.clone(),
};
exec(git_cmd!(
&self.dir,
"-c",
"advice.detachedHead=false",
"-c",
"advice.objectNameWarning=false",
"checkout",
"--force",
&checkout_ref
))?;
if remote_ref_kind.is_none() {
self.ensure_pinned_commit_checked_out(&gitref)?;
}
let post_rev = self.current_sha()?;
touch_dir(&self.dir)?;
Ok((prev_rev, post_rev))
}
pub fn clone(&self, url: &str, options: CloneOptions) -> Result<()> {
if let Some(parent) = self.dir.parent() {
file::mkdirp(parent)?;
}
let sha_branch = options.branch.as_deref().filter(|b| looks_like_sha(b));
let revision = options.revision.as_deref().or(sha_branch);
let named_branch = options
.branch
.as_deref()
.filter(|b| !looks_like_sha(b) && revision.is_none());
if (Settings::get().libgit2 || Settings::get().gix)
&& std::env::var_os("MISE_GITHUB_RELAY_SOCKET").is_none()
{
debug!("cloning {} to {} with gix", url, self.dir.display());
let mut prepare_clone = gix::prepare_clone(url, &self.dir)?
.with_in_memory_config_overrides([
github_credential_config("github.com"),
github_credential_config("github.com:443"),
]);
if let Some(branch) = named_branch {
prepare_clone = prepare_clone.with_ref_name(Some(branch))?;
}
let (mut prepare_checkout, _) = prepare_clone
.fetch_then_checkout(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)?;
prepare_checkout
.main_worktree(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)?;
if let Some(revision) = revision {
self.checkout(revision)?;
}
return Ok(());
}
debug!("cloning {} to {} with git", url, self.dir.display());
match get_git_version() {
Ok(version) => trace!("git version: {}", version),
Err(err) => warn!(
"failed to get git version: {:#}\n Git is required to use mise.",
err
),
}
if let Some(pr) = &options.pr {
pr.abandon();
}
let mut cmd = sanitize_git_cmd_runner(
CmdLineRunner::new("git")
.arg("-c")
.arg(github_credential_config("github.com"))
.arg("-c")
.arg(github_credential_config("github.com:443"))
.arg("clone")
.arg("-q")
.arg("-o")
.arg("origin")
.arg("-c")
.arg("core.autocrlf=false"),
);
if revision.is_none() {
cmd = cmd.arg("--depth").arg("1");
}
cmd = cmd.arg(url).arg(&self.dir);
if let Some(branch) = named_branch {
cmd = cmd.args([
"-b",
branch,
"--single-branch",
"-c",
"advice.detachedHead=false",
]);
}
cmd.execute()?;
if let Some(revision) = revision {
self.checkout(revision)?;
}
Ok(())
}
pub fn update_submodules(&self) -> Result<()> {
debug!("updating submodules in {}", self.dir.display());
let exec = |cmd: Expression| match cmd.stderr_to_stdout().stdout_capture().unchecked().run()
{
Ok(res) => {
if res.status.success() {
Ok(())
} else {
Err(eyre!(
"git failed: {cmd:?} {}",
String::from_utf8_lossy(&res.stdout)
))
}
}
Err(err) => Err(eyre!("git failed: {cmd:?} {err:#}")),
};
exec(
git_cmd!(&self.dir, "submodule", "update", "--init", "--recursive")
.env("GIT_TERMINAL_PROMPT", "0"),
)?;
Ok(())
}
pub fn current_branch(&self) -> Result<String> {
let dir = &self.dir;
if let Ok(repo) = self.repo() {
let head = repo.head()?;
let branch = head
.referent_name()
.map(|name| name.shorten().to_string())
.unwrap_or_else(|| head.id().unwrap().to_string());
debug!("current branch for {dir:?}: {branch}");
return Ok(branch);
}
let branch = git_cmd_read!(&self.dir, "branch", "--show-current")?;
debug!("current branch for {}: {}", self.dir.display(), branch);
Ok(branch)
}
pub fn current_sha(&self) -> Result<String> {
let dir = &self.dir;
if let Ok(repo) = self.repo() {
let head = repo.head()?;
let sha = head
.id()
.ok_or_else(|| eyre::eyre!("repository {} has no commit at HEAD", dir.display()))?
.to_string();
debug!("current sha for {dir:?}: {sha}");
return Ok(sha);
}
let sha = git_cmd_read!(&self.dir, "rev-parse", "HEAD")?;
debug!("current sha for {}: {}", self.dir.display(), sha);
Ok(sha)
}
pub fn current_sha_short(&self) -> Result<String> {
let dir = &self.dir;
if let Ok(repo) = self.repo() {
let head = repo.head()?;
let id = head
.id()
.ok_or_else(|| eyre::eyre!("repository {} has no commit at HEAD", dir.display()))?;
let sha = id.to_string()[..7].to_string();
debug!("current sha for {dir:?}: {sha}");
return Ok(sha);
}
let sha = git_cmd_read!(&self.dir, "rev-parse", "--short", "HEAD")?;
debug!("current sha for {dir:?}: {sha}");
Ok(sha)
}
pub fn current_abbrev_ref(&self) -> Result<String> {
let dir = &self.dir;
if let Ok(repo) = self.repo() {
let head = repo.head()?;
let head = head.name().shorten().to_string();
debug!("current abbrev ref for {dir:?}: {head}");
return Ok(head);
}
let aref = git_cmd_read!(&self.dir, "rev-parse", "--abbrev-ref", "HEAD")?;
debug!("current abbrev ref for {}: {}", self.dir.display(), aref);
Ok(aref)
}
pub fn get_remote_url(&self) -> Option<String> {
let dir = &self.dir;
if !self.exists() {
return None;
}
let remote_name = self.remote_name();
if let Ok(repo) = self.repo()
&& let Ok(remote) = repo.find_remote(remote_name.as_str())
&& let Some(url) = remote.url(gix::remote::Direction::Fetch)
{
trace!("remote url for {dir:?}: {url}");
return Some(url.to_string());
}
let res = git_cmd_read!(
&self.dir,
"config",
"--get",
&format!("remote.{remote_name}.url")
);
match res {
Ok(url) => {
debug!("remote url for {dir:?}: {url}");
Some(url)
}
Err(err) => {
warn!("failed to get remote url for {dir:?}: {err:#}");
None
}
}
}
pub fn split_url_and_ref(url: &str) -> (String, Option<String>) {
match url.split_once('#') {
Some((url, _ref)) => (url.to_string(), Some(_ref.to_string())),
None => (url.to_string(), None),
}
}
pub fn resolve_commit(&self, rev: &str) -> Result<Option<String>> {
validate_revision("revision", rev)?;
let spec = format!("{rev}^{{commit}}");
let output = git_cmd!(&self.dir, "rev-parse", "--verify", "--quiet", &spec)
.stdout_capture()
.stderr_null()
.unchecked()
.run()
.wrap_err_with(|| format!("git rev-parse {spec} failed"))?;
if !output.status.success() {
return Ok(None);
}
let sha = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok((!sha.is_empty()).then_some(sha))
}
pub fn remote_sha(&self, branch: &str) -> Result<Option<String>> {
let output = git_cmd_read!(&self.dir, "ls-remote", &self.remote_name(), branch)?;
Ok(output
.lines()
.next()
.and_then(|line| line.split_whitespace().next())
.map(|sha| sha.to_string()))
}
pub fn exists(&self) -> bool {
self.dir.join(".git").is_dir()
}
pub fn get_root() -> eyre::Result<PathBuf> {
Ok(cmd!("git", "rev-parse", "--show-toplevel")
.read()?
.trim()
.into())
}
pub fn object_at(&self, revision: &str, path: &Path) -> Result<Option<String>> {
validate_revision("revision", revision)?;
let path = path
.components()
.map(|component| component.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
let spec = format!("{revision}:{path}");
let output = git_cmd!(&self.dir, "rev-parse", "--verify", "--quiet", &spec)
.stdout_capture()
.stderr_null()
.unchecked()
.run()
.wrap_err_with(|| format!("git rev-parse {spec} failed"))?;
if !output.status.success() {
return Ok(None);
}
let id = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok((!id.is_empty()).then_some(id))
}
pub fn superproject(&self) -> Result<Option<PathBuf>> {
let output = git_cmd_read!(&self.dir, "rev-parse", "--show-superproject-working-tree")?;
let output = output.trim_end_matches(['\r', '\n']);
Ok((!output.is_empty()).then(|| output.into()))
}
pub fn submodule_paths(&self) -> Result<Vec<PathBuf>> {
let output = git_cmd_read!(&self.dir, "submodule", "status")?;
Ok(output
.lines()
.filter_map(|line| {
let (_, rest) = line.get(1..)?.split_once(' ')?;
let path = match rest.rsplit_once(" (") {
Some((path, describe)) if describe.ends_with(')') => path,
_ => rest,
};
Some(PathBuf::from(path))
})
.collect())
}
pub fn toplevel(&self) -> Result<PathBuf> {
Ok(git_cmd_read!(&self.dir, "rev-parse", "--show-toplevel")?
.trim_end_matches(['\r', '\n'])
.into())
}
pub fn changed_paths(&self, base: &str, head: &str) -> Result<BTreeSet<PathBuf>> {
validate_revisions(base, head)?;
let range = format!("{base}...{head}");
let output = git_cmd!(
&self.dir,
"diff",
"--name-only",
"-z",
"--no-renames",
"--relative",
&range,
"--",
"."
)
.stdout_capture()
.run()
.wrap_err_with(|| format!("git diff for {range} failed"))?;
parse_nul_paths(&output.stdout)
}
pub fn diff_paths(&self, from: &str, to: &str) -> Result<BTreeSet<PathBuf>> {
validate_revisions(from, to)?;
let output = git_cmd!(
&self.dir,
"diff",
"--name-only",
"-z",
"--no-renames",
"--relative",
from,
to,
"--",
"."
)
.stdout_capture()
.run()
.wrap_err_with(|| format!("git diff {from} {to} failed"))?;
parse_nul_paths(&output.stdout)
}
pub fn uncommitted_paths(&self) -> Result<BTreeSet<PathBuf>> {
let output = git_cmd!(
@worktree
&self.dir,
"diff",
"--name-only",
"-z",
"--no-renames",
"--relative",
"HEAD",
"--",
"."
)
.stdout_capture()
.run()
.wrap_err("git diff for uncommitted changes failed")?;
parse_nul_paths(&output.stdout)
}
pub fn untracked_paths(&self) -> Result<BTreeSet<PathBuf>> {
let output = git_cmd!(
&self.dir,
"ls-files",
"--others",
"--exclude-standard",
"-z",
"--",
"."
)
.stdout_capture()
.run()
.wrap_err("git ls-files for untracked files failed")?;
parse_nul_paths(&output.stdout)
}
pub fn same_commit(&self, left: &str, right: &str) -> Result<bool> {
Ok(self.commit_id(left)? == self.commit_id(right)?)
}
fn commit_id(&self, revision: &str) -> Result<String> {
validate_revision("revision", revision)?;
let spec = format!("{revision}^{{commit}}");
Ok(git_cmd_read!(
&self.dir,
"rev-parse",
"--verify",
"--end-of-options",
spec.as_str()
)?
.trim()
.to_string())
}
pub fn file_in_worktree(&self, path: &Path) -> Result<Option<String>> {
match std::fs::read(self.dir.join(path)) {
Ok(bytes) => {
Ok(Some(String::from_utf8(bytes).wrap_err_with(|| {
format!("Working tree file {path:?} is not UTF-8")
})?))
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err).wrap_err_with(|| format!("failed to read {path:?}")),
}
}
pub fn merge_base(&self, base: &str, head: &str) -> Result<String> {
validate_revisions(base, head)?;
Ok(git_cmd_read!(&self.dir, "merge-base", "--", base, head)?
.trim()
.to_string())
}
pub fn file_at_revision(&self, revision: &str, path: &Path) -> Result<Option<String>> {
validate_revision("revision", revision)?;
let Some(path) = path.to_str() else {
return Ok(None);
};
let object = format!("{revision}:{}", path.replace('\\', "/"));
let output = git_cmd!(&self.dir, "show", "--no-textconv", &object)
.stdout_capture()
.stderr_capture()
.unchecked()
.run()
.wrap_err_with(|| format!("git show for {object:?} failed"))?;
if !output.status.success() {
return Ok(None);
}
Ok(Some(String::from_utf8(output.stdout).wrap_err_with(
|| format!("Git file {path:?} at {revision:?} is not UTF-8"),
)?))
}
pub fn get_path<P: AsRef<Path>>(path: P) -> eyre::Result<PathBuf> {
let root = Self::get_root()?;
let path = cmd!("git", "-C", &root, "rev-parse", "--git-path", path.as_ref()).read()?;
let path = PathBuf::from(path.trim());
Ok(if path.is_absolute() {
path
} else {
root.join(path)
})
}
}
fn validate_revisions(base: &str, head: &str) -> Result<()> {
validate_revision("base", base)?;
validate_revision("head", head)
}
fn validate_revision(name: &str, revision: &str) -> Result<()> {
if revision.is_empty() || revision.starts_with('-') || revision.contains('\0') {
return Err(eyre!("invalid Git {name} revision {revision:?}"));
}
Ok(())
}
fn parse_nul_paths(stdout: &[u8]) -> Result<BTreeSet<PathBuf>> {
stdout
.split(|byte| *byte == 0)
.filter(|path| !path.is_empty())
.map(path_from_git_bytes)
.collect()
}
fn path_from_git_bytes(path: &[u8]) -> Result<PathBuf> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
Ok(OsString::from_vec(path.to_vec()).into())
}
#[cfg(not(unix))]
{
Ok(String::from_utf8(path.to_vec())
.wrap_err("Git returned a non-UTF-8 path")?
.into())
}
}
pub fn github_credential_config(host: &str) -> String {
let executable = crate::env::MISE_BIN.to_string_lossy();
#[cfg(windows)]
let executable = std::borrow::Cow::Owned(executable.replace('\\', "/"));
let executable = shell_escape::unix::escape(executable);
format!("credential.https://{host}.helper=!{executable} token github --git-credential")
}
fn get_git_version() -> Result<String> {
let version = cmd!("git", "--version").read()?;
Ok(version.trim().into())
}
fn sanitize_git_env(cmd: Expression) -> Expression {
GIT_CONTEXT_ENV
.iter()
.fold(cmd, |cmd, env| cmd.env_remove(env))
}
fn sanitize_git_cmd_runner<'a>(cmd: CmdLineRunner<'a>) -> CmdLineRunner<'a> {
GIT_CONTEXT_ENV
.iter()
.fold(cmd, |cmd, env| cmd.env_remove(env))
}
pub fn sanitize_git_command(cmd: &mut std::process::Command) {
for env in GIT_CONTEXT_ENV {
cmd.env_remove(env);
}
}
pub fn detach_git_command(cmd: &mut std::process::Command) {
cmd.current_dir(detached_git_dir());
sanitize_git_command(cmd);
}
fn detached_git_dir() -> &'static Path {
let home: &'static Path = crate::env::HOME.as_path();
if home.is_absolute() && home.is_dir() {
home
} else {
Path::new(std::path::MAIN_SEPARATOR_STR)
}
}
pub async fn ls_remote(options: &[&str], remote: &str, patterns: &[&str]) -> Result<String> {
let mut cmd = tokio::process::Command::new("git");
detach_git_command(cmd.as_std_mut());
let args = ls_remote_args(options, remote, patterns);
crate::cmd::cmd_read_async_command(cmd, "git", &args).await
}
pub fn ls_remote_args<'a>(
options: &[&'a str],
remote: &'a str,
patterns: &[&'a str],
) -> Vec<&'a str> {
let mut args = vec!["ls-remote"];
args.extend_from_slice(options);
args.push("--");
args.push(remote);
args.extend_from_slice(patterns);
args
}
const GIT_CONTEXT_ENV: &[&str] = &[
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_COMMON_DIR",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_NAMESPACE",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RemoteRefKind {
Branch,
Tag,
}
fn pick_remote_name(remotes: &str) -> String {
let mut names = remotes.lines().map(str::trim).filter(|l| !l.is_empty());
let first = names.next();
if first == Some("origin") || names.any(|n| n == "origin") {
return "origin".to_string();
}
first.unwrap_or("origin").to_string()
}
fn qualify_remote_ref(gitref: &str, kind: RemoteRefKind) -> String {
let prefix = match kind {
RemoteRefKind::Branch => "refs/heads/",
RemoteRefKind::Tag => "refs/tags/",
};
if gitref.starts_with(prefix) {
gitref.to_string()
} else {
format!("{prefix}{gitref}")
}
}
fn remote_ref_kind(output: &str, branch_ref: &str, tag_ref: &str) -> Option<RemoteRefKind> {
let has_ref = |expected: &str| {
output.lines().any(|line| {
line.split_once(char::is_whitespace)
.is_some_and(|(_, name)| name == expected)
})
};
if has_ref(branch_ref) {
Some(RemoteRefKind::Branch)
} else if has_ref(tag_ref) {
Some(RemoteRefKind::Tag)
} else {
None
}
}
fn looks_like_sha(s: &str) -> bool {
matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
}
fn checkout_target(gitref: &str) -> String {
if looks_like_sha(gitref) {
format!("{gitref}^{{commit}}")
} else {
gitref.to_string()
}
}
fn looks_like_abbreviated_sha(s: &str) -> bool {
(7..40).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
}
pub fn main_checkout_equivalent(path: &Path) -> Option<PathBuf> {
static CACHE: LazyLock<Mutex<HashMap<PathBuf, Option<PathBuf>>>> =
LazyLock::new(Default::default);
for wt_root in path.ancestors() {
let dotgit = wt_root.join(".git");
if dotgit.is_dir() {
return None;
}
if dotgit.is_file() {
let main_root = CACHE
.lock()
.unwrap()
.entry(wt_root.to_path_buf())
.or_insert_with(|| registered_main_checkout_root(&dotgit))
.clone();
if let Some(main_root) = main_root {
let equiv = main_root.join(path.strip_prefix(wt_root).ok()?);
if equiv.canonicalize().is_ok_and(|real| real != equiv) {
return None;
}
return (equiv != path).then_some(equiv);
}
}
}
None
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Checkout {
pub repository: Option<PathBuf>,
pub worktree: Option<PathBuf>,
}
pub fn checkout_of(path: &Path) -> Checkout {
for dir in path.ancestors() {
let dotgit = dir.join(".git");
if dotgit.is_dir() {
return Checkout {
repository: Some(dir.to_path_buf()),
worktree: None,
};
}
if !dotgit.is_file() {
continue;
}
if worktree_gitdir(&dotgit).is_some() {
return match main_checkout_root(&dotgit) {
Some(repository) => Checkout {
repository: Some(repository),
worktree: Some(dir.to_path_buf()),
},
None => Checkout {
repository: Some(dir.to_path_buf()),
worktree: None,
},
};
}
if !is_submodule_gitdir(&dotgit) {
return Checkout {
repository: Some(dir.to_path_buf()),
worktree: None,
};
}
}
Checkout::default()
}
pub fn in_linked_worktree(path: &Path) -> bool {
for wt_root in path.ancestors() {
let dotgit = wt_root.join(".git");
if dotgit.is_dir() {
return false;
}
if dotgit.is_file() {
if worktree_gitdir(&dotgit).is_some() {
return true;
}
if !is_submodule_gitdir(&dotgit) {
return false;
}
}
}
false
}
fn worktree_gitdir(dotgit_file: &Path) -> Option<PathBuf> {
let gitdir = read_gitdir(dotgit_file)?;
if gitdir.parent()?.file_name() != Some(OsStr::new("worktrees")) {
return None;
}
worktree_common_dir(&gitdir).is_some().then_some(gitdir)
}
fn worktree_common_dir(gitdir: &Path) -> Option<PathBuf> {
let common = PathBuf::from(read_pointer_file(&gitdir.join("commondir"))?.trim());
let common = if common.is_relative() {
gitdir.join(common)
} else {
common
};
let common = common.canonicalize().ok()?;
if common != gitdir.parent()?.parent()?.canonicalize().ok()? {
return None;
}
common.join("HEAD").is_file().then_some(common)
}
fn is_submodule_gitdir(dotgit_file: &Path) -> bool {
let Some(gitdir) = read_gitdir(dotgit_file) else {
return false;
};
if !gitdir.is_dir() {
return false;
}
let mut dir = gitdir.as_path();
while let Some(parent) = dir.parent() {
if dir.file_name() == Some(OsStr::new("modules")) && parent.join("HEAD").is_file() {
return true;
}
dir = parent;
}
false
}
const POINTER_FILE_LIMIT: u64 = 16 * 1024;
fn read_pointer_file(path: &Path) -> Option<String> {
use std::io::Read;
let mut contents = String::new();
crate::file::open_regular_file(path)
.ok()?
.take(POINTER_FILE_LIMIT + 1)
.read_to_string(&mut contents)
.ok()?;
(contents.len() as u64 <= POINTER_FILE_LIMIT).then_some(contents)
}
fn read_gitdir(dotgit_file: &Path) -> Option<PathBuf> {
let contents = read_pointer_file(dotgit_file)?;
let gitdir = PathBuf::from(contents.strip_prefix("gitdir:")?.trim());
Some(if gitdir.is_relative() {
dotgit_file.parent()?.join(gitdir)
} else {
gitdir
})
}
pub fn has_sibling_worktrees(worktree_root: &Path) -> bool {
let Some(gitdir) = worktree_gitdir(&worktree_root.join(".git")) else {
return false;
};
let Some(registry) = gitdir.parent() else {
return false;
};
std::fs::read_dir(registry)
.into_iter()
.flatten()
.flatten()
.filter(|entry| {
let Some(pointer) = read_pointer_file(&entry.path().join("gitdir")) else {
return false;
};
let pointer = Path::new(pointer.trim());
match pointer.is_relative() {
true => entry.path().join(pointer).exists(),
false => pointer.exists(),
}
})
.nth(1)
.is_some()
}
fn main_checkout_root(dotgit_file: &Path) -> Option<PathBuf> {
let common = worktree_common_dir(&worktree_gitdir(dotgit_file)?)?;
if common.file_name() == Some(OsStr::new(".git")) {
common.parent().map(|p| p.to_path_buf())
} else {
None }
}
fn registered_main_checkout_root(dotgit_file: &Path) -> Option<PathBuf> {
let gitdir = worktree_gitdir(dotgit_file)?;
let pointer = PathBuf::from(read_pointer_file(&gitdir.join("gitdir"))?.trim());
let pointer = if pointer.is_relative() {
gitdir.join(pointer)
} else {
pointer
};
if pointer.file_name() != Some(OsStr::new(".git"))
|| pointer.parent()?.canonicalize().ok()? != dotgit_file.parent()?.canonicalize().ok()?
{
return None;
}
main_checkout_root(dotgit_file)
}
pub fn plumbing_binary() -> Option<&'static Path> {
static BIN: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
let git = crate::file::which_spawnable("git")?;
if cfg!(target_os = "macos") && git == Path::new("/usr/bin/git") {
let installed = std::process::Command::new("xcode-select")
.arg("-p")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|status| status.success());
if !installed {
return None;
}
}
Some(git)
});
BIN.as_deref()
}
#[derive(Debug, Default)]
pub struct PlumbingCall<'a> {
pub args: Vec<OsString>,
pub work_tree: Option<&'a Path>,
pub index_file: Option<&'a Path>,
pub cwd: Option<&'a Path>,
pub stdin: Option<&'a [u8]>,
pub env: Vec<(OsString, OsString)>,
}
impl<'a> PlumbingCall<'a> {
pub fn new<I, S>(args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
Self {
args: args.into_iter().map(Into::into).collect(),
..Default::default()
}
}
pub fn work_tree(mut self, path: &'a Path) -> Self {
self.work_tree = Some(path);
self
}
pub fn index_file(mut self, path: &'a Path) -> Self {
self.index_file = Some(path);
self
}
pub fn stdin(mut self, bytes: &'a [u8]) -> Self {
self.stdin = Some(bytes);
self
}
pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
self.env.push((key.into(), value.into()));
self
}
}
#[derive(Debug)]
pub struct GitPlumbing {
git_dir: PathBuf,
disabled_hooks: std::sync::Mutex<Option<tempfile::TempDir>>,
}
impl GitPlumbing {
pub fn new(git_dir: impl Into<PathBuf>) -> Self {
Self {
git_dir: git_dir.into(),
disabled_hooks: std::sync::Mutex::new(None),
}
}
pub fn git_dir(&self) -> &Path {
&self.git_dir
}
pub fn exists(&self) -> bool {
self.git_dir.join("HEAD").is_file()
}
pub fn init_bare(&self) -> Result<()> {
if self.exists() {
return Ok(());
}
if let Some(parent) = self.git_dir.parent() {
crate::file::create_dir_all(parent)?;
}
let mut cmd = self.base_command()?;
cmd.args(["init", "--bare", "--quiet"]).arg(&self.git_dir);
run_plumbing(cmd, None)?;
for (key, value) in [
("core.autocrlf", "false"),
("core.logAllRefUpdates", "false"),
("gc.auto", "0"),
#[cfg(unix)]
("core.symlinks", "true"),
] {
self.run(PlumbingCall::new(["config", key, value]))?;
}
Ok(())
}
pub fn run(&self, call: PlumbingCall<'_>) -> Result<()> {
self.output(call).map(|_| ())
}
pub fn output(&self, call: PlumbingCall<'_>) -> Result<Vec<u8>> {
let cmd = self.command(&call)?;
run_plumbing(cmd, call.stdin)
}
pub fn blob_starts_with(&self, oid: &str, prefix: &[u8]) -> Result<bool> {
use std::io::Read;
use std::process::Stdio;
let mut child = self
.command(&PlumbingCall::new(["cat-file", "blob", oid]))?
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()?;
let mut bytes = Vec::new();
let mut output = child
.stdout
.take()
.expect("stdout was piped")
.take(prefix.len() as u64);
let read = output.read_to_end(&mut bytes);
let complete = bytes.len() == prefix.len();
if complete || read.is_err() {
let _ = child.kill();
}
let status = child.wait()?;
read?;
if !complete && !status.success() {
eyre::bail!("failed to inspect Git blob {oid}");
}
Ok(bytes == prefix)
}
pub fn output_unchecked(&self, call: PlumbingCall<'_>) -> Result<std::process::Output> {
let cmd = self.command(&call)?;
spawn_plumbing(cmd, call.stdin)
}
pub fn status_inherited(&self, call: PlumbingCall<'_>) -> Result<std::process::ExitStatus> {
let mut cmd = self.command(&call)?;
cmd.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
.stdin(std::process::Stdio::null());
cmd.status()
.wrap_err_with(|| format!("failed to run {}", describe_plumbing(&cmd)))
}
pub fn output_str(&self, call: PlumbingCall<'_>) -> Result<String> {
let out = self.output(call)?;
Ok(String::from_utf8_lossy(&out).trim().to_string())
}
pub fn network_output(&self, call: PlumbingCall<'_>) -> Result<std::process::Output> {
eyre::ensure!(
call.work_tree.is_none()
&& call.index_file.is_none()
&& call.stdin.is_none()
&& call.env.is_empty(),
"network Git calls do not accept a work tree, alternate index, stdin, or environment overrides"
);
let git =
plumbing_binary().ok_or_else(|| eyre!("no unattended git executable is available"))?;
let mut cmd = std::process::Command::new(git);
sanitize_git_command(&mut cmd);
if !console::user_attended_stderr() {
cmd.env("GIT_TERMINAL_PROMPT", "0");
}
cmd.args([
"-c",
&github_credential_config("github.com"),
"-c",
&github_credential_config("github.com:443"),
]);
cmd.env("GIT_OPTIONAL_LOCKS", "0")
.env("LC_ALL", "C")
.stdin(std::process::Stdio::null());
let mut git_dir = OsString::from("--git-dir=");
git_dir.push(&self.git_dir);
cmd.arg(git_dir);
let hooks = tempfile::tempdir()?;
let mut hooks_config = OsString::from("core.hooksPath=");
hooks_config.push(hooks.path());
cmd.arg("-c")
.arg(hooks_config)
.args(["-c", "advice.fetchShowForcedUpdates=false"]);
cmd.args(&call.args);
if let Some(cwd) = call.cwd {
cmd.current_dir(cwd);
}
spawn_plumbing(cmd, None)
}
fn base_command(&self) -> Result<std::process::Command> {
let git =
plumbing_binary().ok_or_else(|| eyre!("no unattended git executable is available"))?;
let mut cmd = std::process::Command::new(git);
sanitize_git_command(&mut cmd);
cmd.env_remove("GIT_CONFIG_COUNT")
.env_remove("GIT_CONFIG_PARAMETERS");
let mut hooks = self
.disabled_hooks
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if hooks.is_none() {
*hooks = Some(tempfile::tempdir()?);
}
let mut hooks_config = OsString::from("core.hooksPath=");
hooks_config.push(hooks.as_ref().expect("hooks directory initialized").path());
cmd.arg("-c").arg(hooks_config);
cmd.env("GIT_CONFIG_NOSYSTEM", "1")
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_TERMINAL_PROMPT", "0")
.env("GIT_OPTIONAL_LOCKS", "0")
.env("GIT_AUTHOR_NAME", "mise")
.env("GIT_AUTHOR_EMAIL", "mise@localhost")
.env("GIT_COMMITTER_NAME", "mise")
.env("GIT_COMMITTER_EMAIL", "mise@localhost")
.env("LC_ALL", "C")
.stdin(std::process::Stdio::null());
Ok(cmd)
}
fn command(&self, call: &PlumbingCall<'_>) -> Result<std::process::Command> {
let mut cmd = self.base_command()?;
let mut git_dir = OsString::from("--git-dir=");
git_dir.push(&self.git_dir);
cmd.arg(git_dir);
if let Some(work_tree) = call.work_tree {
let mut arg = OsString::from("--work-tree=");
arg.push(work_tree);
cmd.arg(arg);
}
cmd.args([
"-c",
"core.autocrlf=false",
"-c",
"core.quotePath=false",
"-c",
"advice.addEmbeddedRepo=false",
]);
cmd.args(&call.args);
if let Some(index) = call.index_file {
cmd.env("GIT_INDEX_FILE", index);
}
if let Some(cwd) = call.cwd {
cmd.current_dir(cwd);
}
for (key, value) in &call.env {
cmd.env(key, value);
}
if call.stdin.is_some() {
cmd.stdin(std::process::Stdio::piped());
}
Ok(cmd)
}
}
fn describe_plumbing(cmd: &std::process::Command) -> String {
let args = cmd
.get_args()
.map(|arg| arg.to_string_lossy().into_owned())
.collect::<Vec<_>>();
format!("git {}", args.join(" "))
}
fn spawn_plumbing(
mut cmd: std::process::Command,
stdin: Option<&[u8]>,
) -> Result<std::process::Output> {
use std::io::Write;
cmd.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
let mut child = cmd
.spawn()
.wrap_err_with(|| format!("failed to spawn {}", describe_plumbing(&cmd)))?;
if let Some(bytes) = stdin {
let mut pipe = child.stdin.take().expect("stdin was piped");
let _ = pipe.write_all(bytes);
drop(pipe);
}
child
.wait_with_output()
.wrap_err_with(|| format!("failed to run {}", describe_plumbing(&cmd)))
}
fn run_plumbing(cmd: std::process::Command, stdin: Option<&[u8]>) -> Result<Vec<u8>> {
let describe = describe_plumbing(&cmd);
let output = spawn_plumbing(cmd, stdin)?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(eyre!(
"{describe} failed ({}): {}",
output.status,
stderr.trim()
));
}
Ok(output.stdout)
}
impl Debug for Git {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Git").field("dir", &self.dir).finish()
}
}
#[derive(Default)]
pub struct CloneOptions<'a> {
pr: Option<&'a dyn SingleReport>,
branch: Option<String>,
revision: Option<String>,
}
impl<'a> CloneOptions<'a> {
pub fn pr(mut self, pr: &'a dyn SingleReport) -> Self {
self.pr = Some(pr);
self
}
pub fn branch(mut self, branch: &str) -> Self {
self.branch = Some(branch.to_string());
self.revision = None;
self
}
pub fn revision(mut self, revision: &str) -> Self {
self.branch = None;
self.revision = Some(revision.to_string());
self
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod plumbing_tests;