remove unused reader functions

This commit is contained in:
Kiril Videlov 2024-05-29 14:04:51 +02:00
parent d97bba0001
commit 9e4bbdedec
3 changed files with 2 additions and 396 deletions

View File

@ -5,10 +5,10 @@ use std::{
sync::Arc,
};
use anyhow::{Context, Result};
use anyhow::Result;
use serde::{ser::SerializeStruct, Serialize};
use crate::{git, lock, path::Normalize};
use crate::git::{self};
#[derive(Debug, Clone, thiserror::Error)]
pub enum Error {
@ -37,216 +37,6 @@ impl From<FromError> for Error {
}
}
pub enum Reader<'reader> {
Filesystem(FilesystemReader),
Commit(CommitReader<'reader>),
Prefixed(PrefixedReader<'reader>),
}
impl<'reader> Reader<'reader> {
pub fn open<P: AsRef<Path>>(root: P) -> Result<Self, io::Error> {
FilesystemReader::open(root).map(Reader::Filesystem)
}
pub fn sub<P: AsRef<Path>>(&'reader self, prefix: P) -> Self {
Reader::Prefixed(PrefixedReader::new(self, prefix))
}
pub fn commit_id(&self) -> Option<git::Oid> {
match self {
Reader::Filesystem(_) => None,
Reader::Commit(reader) => Some(reader.get_commit_oid()),
Reader::Prefixed(reader) => reader.reader.commit_id(),
}
}
pub fn from_commit(
repository: &'reader git::Repository,
commit: &git::Commit<'reader>,
) -> Result<Self> {
Ok(Reader::Commit(CommitReader::new(repository, commit)?))
}
pub fn exists<P: AsRef<Path>>(&self, file_path: P) -> Result<bool, io::Error> {
match self {
Reader::Filesystem(reader) => reader.exists(file_path),
Reader::Commit(reader) => Ok(reader.exists(file_path)),
Reader::Prefixed(reader) => reader.exists(file_path),
}
}
pub fn read<P: AsRef<Path>>(&self, path: P) -> Result<Content, Error> {
let mut contents = self.batch(&[path])?;
contents
.pop()
.expect("batch should return at least one result")
}
pub fn batch<P: AsRef<Path>>(
&self,
paths: &[P],
) -> Result<Vec<Result<Content, Error>>, io::Error> {
match self {
Reader::Filesystem(reader) => reader.batch(|root| {
paths
.iter()
.map(|path| {
let path = root.join(path);
if !path.exists() {
return Err(Error::NotFound);
}
let content = Content::read_from_file(&path)?;
Ok(content)
})
.collect()
}),
Reader::Commit(reader) => Ok(paths
.iter()
.map(|path| reader.read(path.normalize()))
.collect()),
Reader::Prefixed(reader) => reader.batch(paths),
}
}
pub fn list_files<P: AsRef<Path>>(&self, dir_path: P) -> Result<Vec<PathBuf>> {
match self {
Reader::Filesystem(reader) => reader.list_files(dir_path.as_ref()),
Reader::Commit(reader) => reader.list_files(dir_path.as_ref()),
Reader::Prefixed(reader) => reader.list_files(dir_path.as_ref()),
}
}
}
pub struct FilesystemReader(lock::Dir);
impl FilesystemReader {
fn open<P: AsRef<Path>>(root: P) -> Result<Self, io::Error> {
lock::Dir::new(root).map(Self)
}
fn exists<P: AsRef<Path>>(&self, path: P) -> Result<bool, io::Error> {
let exists = self.0.batch(|root| root.join(path.as_ref()).exists())?;
Ok(exists)
}
fn batch<R>(&self, action: impl FnOnce(&Path) -> R) -> Result<R, io::Error> {
self.0.batch(action)
}
fn list_files<P: AsRef<Path>>(&self, path: P) -> Result<Vec<PathBuf>> {
let path = path.as_ref();
self.0
.batch(|root| crate::fs::list_files(root.join(path).as_path(), &[Path::new(".git")]))?
}
}
pub struct CommitReader<'reader> {
repository: &'reader git::Repository,
commit_oid: git::Oid,
tree: git::Tree<'reader>,
}
impl<'reader> CommitReader<'reader> {
pub fn new(
repository: &'reader git::Repository,
commit: &git::Commit<'reader>,
) -> Result<CommitReader<'reader>> {
let tree = commit
.tree()
.with_context(|| format!("{}: tree not found", commit.id()))?;
Ok(CommitReader {
repository,
tree,
commit_oid: commit.id(),
})
}
pub fn get_commit_oid(&self) -> git::Oid {
self.commit_oid
}
fn read<P: AsRef<Path>>(&self, path: P) -> Result<Content, Error> {
let path = path.as_ref();
let entry = match self
.tree
.get_path(Path::new(path))
.context(format!("{}: tree entry not found", path.display()))
{
Ok(entry) => entry,
Err(_) => return Err(Error::NotFound),
};
let blob = match self.repository.find_blob(entry.id()) {
Ok(blob) => blob,
Err(_) => return Err(Error::NotFound),
};
Ok(Content::from(&blob))
}
pub fn list_files<P: AsRef<Path>>(&self, dir_path: P) -> Result<Vec<PathBuf>> {
let dir_path = dir_path.as_ref();
let mut files = vec![];
self.tree
.walk(|root, entry| {
if entry.kind() == Some(git2::ObjectType::Tree) {
return git::TreeWalkResult::Continue;
}
if entry.name().is_none() {
return git::TreeWalkResult::Continue;
}
let entry_path = Path::new(root).join(entry.name().unwrap());
if !entry_path.starts_with(dir_path) {
return git::TreeWalkResult::Continue;
}
files.push(entry_path.strip_prefix(dir_path).unwrap().to_path_buf());
git::TreeWalkResult::Continue
})
.with_context(|| format!("{}: tree walk failed", dir_path.display()))?;
Ok(files)
}
pub fn exists<P: AsRef<Path>>(&self, file_path: P) -> bool {
self.tree.get_path(file_path.normalize()).is_ok()
}
}
pub struct PrefixedReader<'r> {
reader: &'r Reader<'r>,
prefix: PathBuf,
}
impl<'r> PrefixedReader<'r> {
fn new<P: AsRef<Path>>(reader: &'r Reader, prefix: P) -> Self {
PrefixedReader {
reader,
prefix: prefix.as_ref().to_path_buf(),
}
}
pub fn batch<P: AsRef<Path>>(
&self,
paths: &[P],
) -> Result<Vec<Result<Content, Error>>, io::Error> {
let paths = paths
.iter()
.map(|path| self.prefix.join(path))
.collect::<Vec<_>>();
self.reader.batch(paths.as_slice())
}
fn list_files<P: AsRef<Path>>(&self, dir_path: P) -> Result<Vec<PathBuf>> {
self.reader.list_files(self.prefix.join(dir_path.as_ref()))
}
fn exists<P: AsRef<Path>>(&self, file_path: P) -> Result<bool, io::Error> {
self.reader.exists(self.prefix.join(file_path.as_ref()))
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum FromError {
#[error(transparent)]

View File

@ -8,7 +8,6 @@ mod git;
mod keys;
mod lock;
mod ops;
mod reader;
mod types;
pub mod virtual_branches;
mod zip;

View File

@ -1,183 +0,0 @@
use std::{fs, path::Path};
use anyhow::Result;
use gitbutler_core::reader::{CommitReader, Content, Reader};
use gitbutler_testsupport::{commit_all, temp_dir, test_repository};
#[test]
fn directory_reader_read_file() -> Result<()> {
let dir = temp_dir();
let file_path = Path::new("test.txt");
fs::write(dir.path().join(file_path), "test")?;
let reader = Reader::open(dir.path())?;
assert_eq!(reader.read(file_path)?, Content::UTF8("test".to_string()));
Ok(())
}
#[test]
fn commit_reader_read_file() -> Result<()> {
let (repository, _tmp) = test_repository();
let file_path = Path::new("test.txt");
fs::write(repository.path().parent().unwrap().join(file_path), "test")?;
let oid = commit_all(&repository);
fs::write(repository.path().parent().unwrap().join(file_path), "test2")?;
let reader = Reader::from_commit(&repository, &repository.find_commit(oid)?)?;
assert_eq!(reader.read(file_path)?, Content::UTF8("test".to_string()));
Ok(())
}
#[test]
fn reader_list_files_should_return_relative() -> Result<()> {
let dir = temp_dir();
fs::write(dir.path().join("test1.txt"), "test")?;
fs::create_dir_all(dir.path().join("dir"))?;
fs::write(dir.path().join("dir").join("test.txt"), "test")?;
let reader = Reader::open(dir.path())?;
let files = reader.list_files(Path::new("dir"))?;
assert_eq!(files.len(), 1);
assert!(files.contains(&Path::new("test.txt").to_path_buf()));
Ok(())
}
#[test]
fn reader_list_files() -> Result<()> {
let dir = temp_dir();
fs::write(dir.path().join("test.txt"), "test")?;
fs::create_dir_all(dir.path().join("dir"))?;
fs::write(dir.path().join("dir").join("test.txt"), "test")?;
let reader = Reader::open(dir.path())?;
let files = reader.list_files(Path::new(""))?;
assert_eq!(files.len(), 2);
assert!(files.contains(&Path::new("test.txt").to_path_buf()));
assert!(files.contains(&Path::new("dir/test.txt").to_path_buf()));
Ok(())
}
#[test]
fn commit_reader_list_files_should_return_relative() -> Result<()> {
let (repository, _tmp) = test_repository();
fs::write(
repository.path().parent().unwrap().join("test1.txt"),
"test",
)?;
fs::create_dir_all(repository.path().parent().unwrap().join("dir"))?;
fs::write(
repository
.path()
.parent()
.unwrap()
.join("dir")
.join("test.txt"),
"test",
)?;
let oid = commit_all(&repository);
fs::remove_dir_all(repository.path().parent().unwrap().join("dir"))?;
let reader = CommitReader::new(&repository, &repository.find_commit(oid)?)?;
let files = reader.list_files(Path::new("dir"))?;
assert_eq!(files.len(), 1);
assert!(files.contains(&Path::new("test.txt").to_path_buf()));
Ok(())
}
#[test]
fn commit_reader_list_files() -> Result<()> {
let (repository, _tmp) = test_repository();
fs::write(repository.path().parent().unwrap().join("test.txt"), "test")?;
fs::create_dir_all(repository.path().parent().unwrap().join("dir"))?;
fs::write(
repository
.path()
.parent()
.unwrap()
.join("dir")
.join("test.txt"),
"test",
)?;
let oid = commit_all(&repository);
fs::remove_dir_all(repository.path().parent().unwrap().join("dir"))?;
let reader = CommitReader::new(&repository, &repository.find_commit(oid)?)?;
let files = reader.list_files(Path::new(""))?;
assert_eq!(files.len(), 2);
assert!(files.contains(&Path::new("test.txt").to_path_buf()));
assert!(files.contains(&Path::new("dir/test.txt").to_path_buf()));
Ok(())
}
#[test]
fn directory_reader_exists() -> Result<()> {
let dir = temp_dir();
fs::write(dir.path().join("test.txt"), "test")?;
let reader = Reader::open(dir.path())?;
assert!(reader.exists(Path::new("test.txt"))?);
assert!(!reader.exists(Path::new("test2.txt"))?);
Ok(())
}
#[test]
fn commit_reader_exists() -> Result<()> {
let (repository, _tmp) = test_repository();
fs::write(repository.path().parent().unwrap().join("test.txt"), "test")?;
let oid = commit_all(&repository);
fs::remove_file(repository.path().parent().unwrap().join("test.txt"))?;
let reader = CommitReader::new(&repository, &repository.find_commit(oid)?)?;
assert!(reader.exists(Path::new("test.txt")));
assert!(!reader.exists(Path::new("test2.txt")));
Ok(())
}
#[test]
fn from_bytes() {
for (bytes, expected) in [
("test".as_bytes(), Content::UTF8("test".to_string())),
(&[0, 159, 146, 150, 159, 146, 150], Content::Binary),
] {
assert_eq!(Content::from(bytes), expected);
}
}
#[test]
fn serialize_content() {
for (content, expected) in [
(
Content::UTF8("test".to_string()),
r#"{"type":"utf8","value":"test"}"#,
),
(Content::Binary, r#"{"type":"binary"}"#),
(Content::Large, r#"{"type":"large"}"#),
] {
assert_eq!(serde_json::to_string(&content).unwrap(), expected);
}
}