feat: browse the files of a commit
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s

This commit is contained in:
2026-11-26 08:37:43 +07:00
parent d421a10a3e
commit f57427d30d
9 changed files with 469 additions and 95 deletions
+69 -13
View File
@@ -1084,15 +1084,48 @@ impl Repo {
/// Lists every worktree path relative to the root, directories first.
pub fn entries(&self) -> Result<Vec<PathBuf>> {
let workdir = self.inner.workdir().context("repository has no worktree")?;
let mut entries: Vec<(PathBuf, bool)> = Vec::new();
Self::collect_entries(workdir, workdir, &mut entries)?;
Self::collect_entries(workdir, workdir, &mut entries)?;
Self::sort_entries(&mut entries);
Ok(entries.into_iter().map(|(path, _)| path).collect())
}
/// Sorts directories before files, each alphabetically.
fn sort_entries(entries: &mut [(PathBuf, bool)]) {
entries.sort_by(|(a, a_is_dir), (b, b_is_dir)| {
b_is_dir
.cmp(a_is_dir)
.then_with(|| a.as_os_str().cmp(b.as_os_str()))
});
}
/// Lists every path in the tree of commit `id`, directories first like `entries`.
pub fn entries_at(&self, id: &str) -> Result<Vec<PathBuf>> {
let commit_id = self.inner.rev_parse_single(id.as_bytes())?;
let tree = commit_id.object()?.into_commit().tree()?;
let mut entries: Vec<(PathBuf, bool)> = Vec::new();
for entry in tree.traverse().breadthfirst.files()? {
if !entry.mode.is_blob() {
continue;
}
let path = gix::path::from_bstring(entry.filepath);
for dir in path
.ancestors()
.skip(1)
.filter(|dir| !dir.as_os_str().is_empty())
{
entries.push((dir.to_path_buf(), true));
}
entries.push((path, false));
}
Self::sort_entries(&mut entries);
entries.dedup_by(|a, b| a.0 == b.0);
Ok(entries.into_iter().map(|(path, _)| path).collect())
}
@@ -1109,22 +1142,48 @@ impl Repo {
}
}
/// Reads a file from the tree of commit `id`, or `None` when it has no file at `rel`.
pub fn read_at(&self, id: &str, rel: &Path) -> Result<Option<Vec<u8>>> {
let commit_id = self.inner.rev_parse_single(id.as_bytes())?;
let tree = commit_id.object()?.into_commit().tree()?;
match tree.lookup_entry_by_path(rel)? {
Some(entry) if entry.mode().is_blob() => {
let mut blob = entry.object()?;
Ok(Some(std::mem::take(&mut blob.data)))
}
_ => Ok(None),
}
}
/// Finds the top-level README, preferring markdown extensions.
pub fn find_readme(&self) -> Result<Option<PathBuf>> {
let Some(workdir) = self.inner.workdir() else {
return Ok(None);
};
let mut candidates: Vec<PathBuf> = Vec::new();
let mut names = Vec::new();
for entry in std::fs::read_dir(workdir)? {
let entry = entry?;
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
if name.to_ascii_lowercase().starts_with("readme") {
candidates.push(entry.path());
}
names.push(PathBuf::from(entry?.file_name()));
}
Ok(Self::pick_readme(&names))
}
/// The top-level README among `entries`, preferring markdown extensions.
pub fn pick_readme(entries: &[PathBuf]) -> Option<PathBuf> {
let mut candidates: Vec<PathBuf> = entries
.iter()
.filter(|path| {
path.components().count() == 1
&& path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.to_ascii_lowercase().starts_with("readme"))
})
.cloned()
.collect();
candidates.sort_by_key(|path| {
let ext = path
.extension()
@@ -1139,10 +1198,7 @@ impl Repo {
}
});
Ok(candidates
.into_iter()
.next()
.and_then(|path| path.strip_prefix(workdir).ok().map(Path::to_path_buf)))
candidates.into_iter().next()
}
/// Captures worktree entries, README, and ref state in one pass.
+69
View File
@@ -992,3 +992,72 @@ fn parses_real_format_patch_output() {
assert_eq!(file.insertions, 0);
assert_eq!(file.deletions, 0);
}
#[test]
fn entries_at_lists_a_commits_files_directories_first() {
let (_dir, repo) = fixture(&[
("README", b"plain"),
("docs/README.md", b"# Docs"),
("notes.txt", b"one"),
("readme.md", b"# Title"),
("src/lib.rs", b"fn old() {}"),
]);
commit_all(&repo, "initial");
let first = repo.head_commit().expect("head").expect("commit").id;
let expected = vec![
PathBuf::from("docs"),
PathBuf::from("src"),
PathBuf::from("README"),
PathBuf::from("docs/README.md"),
PathBuf::from("notes.txt"),
PathBuf::from("readme.md"),
PathBuf::from("src/lib.rs"),
];
let entries = repo.entries_at(&first).expect("entries");
assert_eq!(entries, expected);
assert_eq!(repo.entries().expect("entries"), expected);
assert_eq!(
Repo::pick_readme(&entries).as_deref(),
Some(Path::new("readme.md"))
);
assert_eq!(
repo.find_readme().expect("readme").as_deref(),
Some(Path::new("readme.md"))
);
}
#[test]
fn read_at_reads_the_files_of_that_commit() {
let (dir, repo) = fixture(&[("notes.txt", b"one"), ("src/lib.rs", b"fn old() {}")]);
commit_all(&repo, "initial");
let first = repo.head_commit().expect("head").expect("commit").id;
std::fs::write(dir.path().join("src/lib.rs"), b"fn new() {}").expect("write");
std::fs::remove_file(dir.path().join("notes.txt")).expect("remove");
commit_all(&repo, "second");
let second = repo.head_commit().expect("head").expect("commit").id;
assert_eq!(
repo.read_at(&first, Path::new("src/lib.rs"))
.expect("read")
.as_deref(),
Some(b"fn old() {}".as_slice())
);
assert_eq!(
repo.read_at(&second, Path::new("src/lib.rs"))
.expect("read")
.as_deref(),
Some(b"fn new() {}".as_slice())
);
assert_eq!(
repo.read_at(&second, Path::new("notes.txt")).expect("read"),
None
);
assert_eq!(repo.read_at(&second, Path::new("src")).expect("read"), None);
assert!(
repo.read_at("0000000000000000000000000000000000000000", Path::new("src"))
.is_err()
);
}