use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use crate::error::{Error, Result};
use crate::objects::ObjectId;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ref {
Direct(ObjectId),
Symbolic(String),
}
pub fn read_ref_file(path: &Path) -> Result<Ref> {
let content = fs::read_to_string(path).map_err(Error::Io)?;
let content = content.trim_end_matches('\n');
parse_ref_content(content)
}
pub(crate) fn parse_ref_content(content: &str) -> Result<Ref> {
if let Some(target) = content.strip_prefix("ref: ") {
Ok(Ref::Symbolic(target.trim().to_owned()))
} else if content.len() == 40 && content.chars().all(|c| c.is_ascii_hexdigit()) {
let oid: ObjectId = content.parse()?;
Ok(Ref::Direct(oid))
} else {
Err(Error::InvalidRef(content.to_owned()))
}
}
pub fn resolve_ref(git_dir: &Path, refname: &str) -> Result<ObjectId> {
if crate::reftable::is_reftable_repo(git_dir) {
return crate::reftable::reftable_resolve_ref(git_dir, refname);
}
let common = common_dir(git_dir);
resolve_ref_depth(git_dir, common.as_deref(), refname, 0)
}
pub fn common_dir(git_dir: &Path) -> Option<PathBuf> {
let commondir_file = git_dir.join("commondir");
let raw = fs::read_to_string(commondir_file).ok()?;
let rel = raw.trim();
let path = if Path::new(rel).is_absolute() {
PathBuf::from(rel)
} else {
git_dir.join(rel)
};
path.canonicalize().ok()
}
fn notes_merge_state_ref(refname: &str) -> bool {
matches!(refname, "NOTES_MERGE_REF" | "NOTES_MERGE_PARTIAL")
}
fn resolve_ref_depth(
git_dir: &Path,
common: Option<&Path>,
refname: &str,
depth: usize,
) -> Result<ObjectId> {
if depth > 10 {
return Err(Error::InvalidRef(format!(
"ref symlink too deep: {refname}"
)));
}
let path = git_dir.join(refname);
match read_ref_file(&path) {
Ok(Ref::Direct(oid)) => return Ok(oid),
Ok(Ref::Symbolic(target)) => {
return resolve_ref_depth(git_dir, common, &target, depth + 1);
}
Err(Error::Io(ref e)) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
if let Some(cdir) = common {
if notes_merge_state_ref(refname) {
} else if cdir != git_dir {
let cpath = cdir.join(refname);
match read_ref_file(&cpath) {
Ok(Ref::Direct(oid)) => return Ok(oid),
Ok(Ref::Symbolic(target)) => {
return resolve_ref_depth(git_dir, common, &target, depth + 1);
}
Err(Error::Io(ref e)) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
}
}
let packed_dir = common.unwrap_or(git_dir);
if let Some(oid) = lookup_packed_ref(packed_dir, refname)? {
return Ok(oid);
}
if common.is_some() && common != Some(git_dir) {
if let Some(oid) = lookup_packed_ref(git_dir, refname)? {
return Ok(oid);
}
}
Err(Error::InvalidRef(format!("ref not found: {refname}")))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RawRefLookup {
Exists,
NotFound,
IsDirectory,
}
pub fn read_raw_ref(git_dir: &Path, refname: &str) -> Result<RawRefLookup> {
if crate::reftable::is_reftable_repo(git_dir) {
read_raw_ref_reftable(git_dir, refname)
} else {
read_raw_ref_files(git_dir, refname)
}
}
fn read_raw_ref_files(git_dir: &Path, refname: &str) -> Result<RawRefLookup> {
let common = common_dir(git_dir);
if let Some(lookup) = read_raw_ref_at(git_dir.join(refname))? {
return Ok(lookup);
}
if let Some(cdir) = common.as_ref() {
if *cdir != git_dir && !notes_merge_state_ref(refname) {
if let Some(lookup) = read_raw_ref_at(cdir.join(refname))? {
return Ok(lookup);
}
}
}
let packed_dir = common.as_deref().unwrap_or(git_dir);
if packed_ref_name_exists(packed_dir, refname)? {
return Ok(RawRefLookup::Exists);
}
if common.is_some()
&& common.as_deref() != Some(git_dir)
&& packed_ref_name_exists(git_dir, refname)?
{
return Ok(RawRefLookup::Exists);
}
Ok(RawRefLookup::NotFound)
}
fn read_raw_ref_at(path: PathBuf) -> Result<Option<RawRefLookup>> {
match fs::symlink_metadata(&path) {
Ok(meta) => {
if meta.is_dir() {
return Ok(Some(RawRefLookup::IsDirectory));
}
Ok(Some(RawRefLookup::Exists))
}
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(Error::Io(e)),
}
}
fn packed_ref_name_exists(git_dir: &Path, refname: &str) -> Result<bool> {
let packed = git_dir.join("packed-refs");
let content = match fs::read_to_string(&packed) {
Ok(c) => c,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
Err(e) => return Err(Error::Io(e)),
};
for line in content.lines() {
if line.is_empty() || line.starts_with('#') || line.starts_with('^') {
continue;
}
let mut parts = line.split_whitespace();
let _oid = parts.next();
if let Some(name) = parts.next() {
if name == refname {
return Ok(true);
}
}
}
Ok(false)
}
fn read_raw_ref_reftable(git_dir: &Path, refname: &str) -> Result<RawRefLookup> {
if refname == "HEAD" {
let head_path = git_dir.join("HEAD");
match fs::symlink_metadata(&head_path) {
Ok(meta) => {
if meta.is_dir() {
return Ok(RawRefLookup::IsDirectory);
}
return Ok(RawRefLookup::Exists);
}
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(RawRefLookup::NotFound),
Err(e) => return Err(Error::Io(e)),
}
}
if let Some(lookup) = read_raw_ref_at(git_dir.join(refname))? {
return Ok(lookup);
}
let stack = crate::reftable::ReftableStack::open(git_dir)?;
match stack.lookup_ref(refname)? {
Some(rec) => match rec.value {
crate::reftable::RefValue::Deletion => Ok(RawRefLookup::NotFound),
_ => Ok(RawRefLookup::Exists),
},
None => Ok(RawRefLookup::NotFound),
}
}
fn lookup_packed_ref(git_dir: &Path, refname: &str) -> Result<Option<ObjectId>> {
let packed = git_dir.join("packed-refs");
let content = match fs::read_to_string(&packed) {
Ok(c) => c,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(Error::Io(e)),
};
for line in content.lines() {
if line.starts_with('#') || line.starts_with('^') {
continue;
}
let mut parts = line.splitn(2, ' ');
let hash = parts.next().unwrap_or("");
let name = parts.next().unwrap_or("").trim();
if name == refname && hash.len() == 40 {
let oid: ObjectId = hash.parse()?;
return Ok(Some(oid));
}
}
Ok(None)
}
pub fn write_symbolic_ref(git_dir: &Path, refname: &str, target: &str) -> Result<()> {
if crate::reftable::is_reftable_repo(git_dir) {
return crate::reftable::reftable_write_symref(git_dir, refname, target, None, None);
}
let storage_dir = ref_storage_dir(git_dir, refname);
let path = storage_dir.join(refname);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let content = format!("ref: {target}\n");
let lock = path.with_extension("lock");
fs::write(&lock, &content)?;
fs::rename(&lock, &path)?;
Ok(())
}
pub fn write_ref(git_dir: &Path, refname: &str, oid: &ObjectId) -> Result<()> {
if crate::reftable::is_reftable_repo(git_dir) {
return crate::reftable::reftable_write_ref(git_dir, refname, oid, None, None);
}
let storage_dir = ref_storage_dir(git_dir, refname);
let path = storage_dir.join(refname);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let content = format!("{oid}\n");
let lock = path.with_extension("lock");
fs::write(&lock, &content)?;
fs::rename(&lock, &path)?;
Ok(())
}
pub fn delete_ref(git_dir: &Path, refname: &str) -> Result<()> {
if crate::reftable::is_reftable_repo(git_dir) {
return crate::reftable::reftable_delete_ref(git_dir, refname);
}
let storage_dir = ref_storage_dir(git_dir, refname);
let path = storage_dir.join(refname);
match fs::remove_file(&path) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(Error::Io(e)),
}
remove_packed_ref(&storage_dir, refname)?;
let log_path = storage_dir.join("logs").join(refname);
if !refname.starts_with("refs/heads/") {
let _ = fs::remove_file(&log_path);
let logs_heads = storage_dir.join("logs/refs/heads");
let mut parent = log_path.parent();
while let Some(p) = parent {
if p == logs_heads.as_path() || !p.starts_with(&logs_heads) {
break;
}
if fs::remove_dir(p).is_err() {
break;
}
parent = p.parent();
}
}
Ok(())
}
fn remove_packed_ref(git_dir: &Path, refname: &str) -> Result<()> {
let packed_path = git_dir.join("packed-refs");
let content = match fs::read_to_string(&packed_path) {
Ok(c) => c,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(Error::Io(e)),
};
let mut out = String::new();
let mut skip_peeled = false;
let mut changed = false;
let mut header_written = false;
for line in content.lines() {
if skip_peeled {
if line.starts_with('^') {
changed = true;
continue;
}
skip_peeled = false;
}
if line.starts_with('#') {
continue;
}
if line.starts_with('^') {
out.push_str(line);
out.push('\n');
continue;
}
if !header_written {
out.insert_str(0, "# pack-refs with: peeled fully-peeled sorted\n");
header_written = true;
}
let mut parts = line.splitn(2, ' ');
let _hash = parts.next().unwrap_or("");
let name = parts.next().unwrap_or("").trim();
if name == refname {
changed = true;
skip_peeled = true;
continue;
}
out.push_str(line);
out.push('\n');
}
if changed {
let lock = packed_path.with_extension("lock");
fs::write(&lock, &out).map_err(Error::Io)?;
fs::rename(&lock, &packed_path).map_err(Error::Io)?;
}
Ok(())
}
pub fn read_head(git_dir: &Path) -> Result<Option<String>> {
match read_ref_file(&git_dir.join("HEAD"))? {
Ref::Symbolic(target) => Ok(Some(target)),
Ref::Direct(_) => Ok(None),
}
}
pub fn read_symbolic_ref(git_dir: &Path, refname: &str) -> Result<Option<String>> {
if crate::reftable::is_reftable_repo(git_dir) {
return crate::reftable::reftable_read_symbolic_ref(git_dir, refname);
}
let path = git_dir.join(refname);
match read_ref_file(&path) {
Ok(Ref::Symbolic(target)) => Ok(Some(target)),
Ok(Ref::Direct(_)) => Ok(None),
Err(Error::Io(ref e)) if e.kind() == io::ErrorKind::NotFound => {
if !notes_merge_state_ref(refname) {
if let Some(common) = common_dir(git_dir) {
if common != git_dir {
let cpath = common.join(refname);
match read_ref_file(&cpath) {
Ok(Ref::Symbolic(target)) => return Ok(Some(target)),
Ok(Ref::Direct(_)) => return Ok(None),
Err(Error::Io(ref e)) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
}
}
}
Ok(None)
}
Err(e) => Err(e),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LogRefsConfig {
Unset,
None,
Normal,
Always,
}
pub fn read_log_refs_config(git_dir: &Path) -> LogRefsConfig {
let config_dir = common_dir(git_dir).unwrap_or_else(|| git_dir.to_path_buf());
let config_path = config_dir.join("config");
let content = match fs::read_to_string(config_path) {
Ok(c) => c,
Err(_) => return LogRefsConfig::Unset,
};
let mut in_core = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') {
in_core = trimmed.to_ascii_lowercase().starts_with("[core]");
continue;
}
if !in_core {
continue;
}
let Some((key, value)) = trimmed.split_once('=') else {
continue;
};
if !key.trim().eq_ignore_ascii_case("logallrefupdates") {
continue;
}
let v = value.trim();
let lower = v.to_ascii_lowercase();
return match lower.as_str() {
"always" => LogRefsConfig::Always,
"1" | "true" | "yes" | "on" => LogRefsConfig::Normal,
"0" | "false" | "no" | "off" | "never" => LogRefsConfig::None,
_ => LogRefsConfig::Unset,
};
}
LogRefsConfig::Unset
}
fn read_core_bare(git_dir: &Path) -> bool {
let config_dir = common_dir(git_dir).unwrap_or_else(|| git_dir.to_path_buf());
let config_path = config_dir.join("config");
let Ok(content) = fs::read_to_string(config_path) else {
return false;
};
let mut in_core = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') {
in_core = trimmed.to_ascii_lowercase().starts_with("[core]");
continue;
}
if !in_core {
continue;
}
let Some((key, value)) = trimmed.split_once('=') else {
continue;
};
if key.trim().eq_ignore_ascii_case("bare") {
let v = value.trim().to_ascii_lowercase();
return matches!(v.as_str(), "1" | "true" | "yes" | "on");
}
}
false
}
pub fn effective_log_refs_config(git_dir: &Path) -> LogRefsConfig {
match read_log_refs_config(git_dir) {
LogRefsConfig::Unset => {
if read_core_bare(git_dir) {
LogRefsConfig::None
} else {
LogRefsConfig::Normal
}
}
other => other,
}
}
#[must_use]
pub fn should_autocreate_reflog_for_mode(refname: &str, mode: LogRefsConfig) -> bool {
match mode {
LogRefsConfig::Always => true,
LogRefsConfig::Normal => {
refname == "HEAD"
|| refname.starts_with("refs/heads/")
|| refname.starts_with("refs/remotes/")
|| refname.starts_with("refs/notes/")
}
LogRefsConfig::None | LogRefsConfig::Unset => false,
}
}
#[must_use]
pub fn should_autocreate_reflog(git_dir: &Path, refname: &str) -> bool {
should_autocreate_reflog_for_mode(refname, effective_log_refs_config(git_dir))
}
pub fn append_reflog(
git_dir: &Path,
refname: &str,
old_oid: &ObjectId,
new_oid: &ObjectId,
identity: &str,
message: &str,
force_create: bool,
) -> Result<()> {
if crate::reftable::is_reftable_repo(git_dir) {
return crate::reftable::reftable_append_reflog(
git_dir,
refname,
old_oid,
new_oid,
identity,
message,
force_create,
);
}
let storage_dir = ref_storage_dir(git_dir, refname);
let log_path = storage_dir.join("logs").join(refname);
let may_write =
force_create || should_autocreate_reflog(git_dir, refname) || !message.is_empty();
if !may_write && !log_path.exists() {
return Ok(());
}
if let Some(parent) = log_path.parent() {
fs::create_dir_all(parent)?;
}
let line = if message.is_empty() {
format!("{old_oid} {new_oid} {identity}\n")
} else {
format!("{old_oid} {new_oid} {identity}\t{message}\n")
};
let mut file = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&log_path)?;
use io::Write;
file.write_all(line.as_bytes())?;
Ok(())
}
fn ref_storage_dir(git_dir: &Path, refname: &str) -> PathBuf {
if refname == "HEAD" || refname == "NOTES_MERGE_PARTIAL" || refname == "NOTES_MERGE_REF" {
return git_dir.to_path_buf();
}
common_dir(git_dir).unwrap_or_else(|| git_dir.to_path_buf())
}
pub fn list_refs(git_dir: &Path, prefix: &str) -> Result<Vec<(String, ObjectId)>> {
if crate::reftable::is_reftable_repo(git_dir) {
return crate::reftable::reftable_list_refs(git_dir, prefix);
}
let mut results = Vec::new();
let base = git_dir.join(prefix);
collect_refs(&base, prefix, git_dir, &mut results)?;
collect_packed_refs(git_dir, prefix, &mut results)?;
if let Some(cdir) = common_dir(git_dir) {
if cdir != git_dir {
let cbase = cdir.join(prefix);
collect_refs(&cbase, prefix, &cdir, &mut results)?;
collect_packed_refs(&cdir, prefix, &mut results)?;
results.sort_by(|a, b| a.0.cmp(&b.0));
results.dedup_by(|b, a| a.0 == b.0);
}
}
results.sort_by(|a, b| a.0.cmp(&b.0));
Ok(results)
}
pub fn list_refs_glob(git_dir: &Path, pattern: &str) -> Result<Vec<(String, ObjectId)>> {
let glob_pos = pattern.find(['*', '?', '[']);
let prefix = match glob_pos {
Some(pos) => match pattern[..pos].rfind('/') {
Some(slash) => &pattern[..=slash],
None => "",
},
None => pattern,
};
let all = list_refs(git_dir, prefix)?;
let mut results = Vec::new();
for (refname, oid) in all {
if glob_match(pattern, &refname) {
results.push((refname, oid));
}
}
Ok(results)
}
pub fn ref_matches_glob(refname: &str, pattern: &str) -> bool {
if !pattern.contains('*') && !pattern.contains('?') && !pattern.contains('[') {
return refname == pattern
|| refname.ends_with(&format!("/{pattern}"))
|| refname.starts_with(&format!("{pattern}/"));
}
glob_match(pattern, refname)
}
fn glob_match(pattern: &str, text: &str) -> bool {
let pat = pattern.as_bytes();
let txt = text.as_bytes();
let (mut pi, mut ti) = (0, 0);
let (mut star_pi, mut star_ti) = (usize::MAX, 0);
while ti < txt.len() {
if pi < pat.len() && (pat[pi] == b'?' || pat[pi] == txt[ti]) {
pi += 1;
ti += 1;
} else if pi < pat.len() && pat[pi] == b'*' {
star_pi = pi;
star_ti = ti;
pi += 1;
} else if star_pi != usize::MAX {
pi = star_pi + 1;
star_ti += 1;
ti = star_ti;
} else {
return false;
}
}
while pi < pat.len() && pat[pi] == b'*' {
pi += 1;
}
pi == pat.len()
}
fn collect_refs(
dir: &Path,
prefix: &str,
git_dir: &Path,
out: &mut Vec<(String, ObjectId)>,
) -> Result<()> {
let read = match fs::read_dir(dir) {
Ok(r) => r,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(Error::Io(e)),
};
for entry in read {
let entry = entry?;
let name = entry.file_name();
let name_str = name.to_string_lossy();
let refname = format!("{prefix}{name_str}");
let path = entry.path();
let meta = match fs::metadata(&path) {
Ok(m) => m,
Err(_) => continue,
};
if meta.is_dir() {
collect_refs(&path, &format!("{refname}/"), git_dir, out)?;
} else if meta.is_file() {
if let Ok(oid) = resolve_ref(git_dir, &refname) {
out.push((refname, oid))
}
}
}
Ok(())
}
pub fn resolve_at_n_branch(git_dir: &Path, spec: &str) -> Result<String> {
let inner = spec
.strip_prefix("@{-")
.and_then(|s| s.strip_suffix('}'))
.ok_or_else(|| Error::InvalidRef(format!("not an @{{-N}} ref: {spec}")))?;
let n: usize = inner
.parse()
.map_err(|_| Error::InvalidRef(format!("invalid N in {spec}")))?;
if n == 0 {
return Err(Error::InvalidRef("@{-0} is not valid".to_string()));
}
let entries = crate::reflog::read_reflog(git_dir, "HEAD")?;
let mut count = 0usize;
for entry in entries.iter().rev() {
let msg = &entry.message;
if let Some(rest) = msg.strip_prefix("checkout: moving from ") {
count += 1;
if count == n {
if let Some(to_pos) = rest.find(" to ") {
return Ok(rest[..to_pos].to_string());
}
}
}
}
Err(Error::InvalidRef(format!(
"{spec}: only {count} checkout(s) in reflog"
)))
}
fn collect_packed_refs(
git_dir: &Path,
prefix: &str,
out: &mut Vec<(String, ObjectId)>,
) -> Result<()> {
let packed_path = git_dir.join("packed-refs");
let content = match fs::read_to_string(&packed_path) {
Ok(c) => c,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(Error::Io(e)),
};
for line in content.lines() {
if line.starts_with('#') || line.starts_with('^') || line.is_empty() {
continue;
}
let mut parts = line.splitn(2, ' ');
let hash = parts.next().unwrap_or("");
let refname = parts.next().unwrap_or("").trim();
if !refname.starts_with(prefix) || hash.len() != 40 {
continue;
}
let oid: ObjectId = hash.parse()?;
out.push((refname.to_string(), oid));
}
Ok(())
}
#[cfg(test)]
mod read_raw_ref_tests {
use super::*;
use tempfile::tempdir;
#[test]
fn loose_ref_file_is_exists() {
let dir = tempdir().unwrap();
let git_dir = dir.path();
fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
fs::write(
git_dir.join("refs/heads/side"),
"0000000000000000000000000000000000000000\n",
)
.unwrap();
assert_eq!(
read_raw_ref(git_dir, "refs/heads/side").unwrap(),
RawRefLookup::Exists
);
}
#[test]
fn missing_ref_is_not_found() {
let dir = tempdir().unwrap();
let git_dir = dir.path();
fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
assert_eq!(
read_raw_ref(git_dir, "refs/heads/nope").unwrap(),
RawRefLookup::NotFound
);
}
#[test]
fn directory_where_ref_expected_is_is_directory() {
let dir = tempdir().unwrap();
let git_dir = dir.path();
fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
assert_eq!(
read_raw_ref(git_dir, "refs/heads").unwrap(),
RawRefLookup::IsDirectory
);
}
#[test]
fn packed_ref_name_is_exists() {
let dir = tempdir().unwrap();
let git_dir = dir.path();
fs::write(
git_dir.join("packed-refs"),
"# pack-refs with: peeled fully-peeled \n\
0000000000000000000000000000000000000000 refs/heads/packed\n",
)
.unwrap();
assert_eq!(
read_raw_ref(git_dir, "refs/heads/packed").unwrap(),
RawRefLookup::Exists
);
}
}