index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff

Diffstat (limited to 'src/git/repository.rs')

-rw-r--r-- src/git/repository.rs 125
 1 file changed, 82 insertions(+), 43 deletions(-)

diff --git a/src/git/repository.rs b/src/git/repository.rs
index 529a326..914a60e 100644
--- a/src/git/repository.rs
+++ b/src/git/repository.rs
@@ -23,32 +23,28 @@
    pub description: String,
    pub owner: Option<String>,

    // So clients dont see the path
    // Path on disk (not exposed to clients)
    pub path: PathBuf,
    // ThreadSafeRepository holds shared repo state so it can live across web worker threads.
    // Call `self.gix()` on a worker thread to get a thread-local `gix::Repository` with object caches.
    pub gix: gix::ThreadSafeRepository,
}

impl Repository {
    pub fn open(path: &Path) -> Result<Self, Error> {
        let Some(name) = path.file_name().and_then(OsStr::to_str) else {
            return Err(Error::Failed);
        };
        let description = std::fs::read(path.join("description")).unwrap_or_default();
        let description = match String::from_utf8(description) {
            Ok(v) => {
                if !v.is_empty() {
                    v
                } else {
                    "There is no description!".to_string()
                }
            }
        let name = path
            .file_name()
            .and_then(OsStr::to_str)
            .ok_or(Error::Failed)?;

        let raw_desc = std::fs::read(path.join("description")).unwrap_or_default();
        let description = match String::from_utf8(raw_desc) {
            Ok(s) if !s.is_empty() => s,
            Ok(_) => "There is no description!".to_string(),
            Err(_) => "Failed to get the description!".to_string(),
        };

        let gix = match gix::ThreadSafeRepository::open(path) {
            Ok(repo) => repo,
            Err(_) => return Err(Error::Failed),
        };
        let gix = gix::ThreadSafeRepository::open(path).map_err(|_| Error::Failed)?;

        let owner = gix
            .to_thread_local()
@@ -65,39 +61,48 @@
        })
    }

    /// Converts the shared `ThreadSafeRepository` handle into a thread-local `gix::Repository`
    /// that caches decoded Git objects in memory for the current request.
    pub fn gix(&self) -> gix::Repository {
        self.gix.to_thread_local()
    }

    /// Looks for a `README*` file in the root folder (`Tree`) of the `HEAD` commit.
    pub fn readme(&self) -> Option<String> {
        let gix_repo = self.gix();
        // 1. Follow HEAD -> branch -> latest Commit object
        let commit = gix_repo.head().ok()?.peel_to_commit().ok()?;
        // 2. Get the root directory snapshot (Tree) of that Commit
        let tree = commit.tree().ok()?;

        let entry = tree.iter().find(|entry| {
            entry
                .as_ref()
                .unwrap()
        // 3. Find the first entry whose filename starts with "readme" (case-insensitive)
        for entry in tree.iter().flatten() {
            if entry
                .filename()
                .to_string()
                .to_lowercase()
                .starts_with("readme")
        })?;

        let blob = entry.unwrap().object().unwrap().into_blob();
        Some(String::from_utf8_lossy(&blob.data).into_owned())
            {
                // Load the file contents (Blob) from Git's object database
                let blob = entry.object().ok()?.into_blob();
                return Some(String::from_utf8_lossy(&blob.data).into_owned());
            }
        }
        None
    }

    /// Streams a commit or branch's directory tree into an in-memory `.tar.gz` archive.
    pub fn archive(
        &self,
        current_ref: &Ref,
        commit: &Option<String>,
    ) -> Result<(Vec<u8>, String), anyhow::Error> {
        let gix_repo = self.gix();
        // Resolve the root directory Tree either from a specific commit hash or from a branch/tag ref
        let (tree, filename) = if let Some(commit) = commit {
            (
                self.find_commit(&gix_repo, commit)?.gix.tree()?,
                format!("{}.tar.gz", commit),
                format!("{commit}.tar.gz"),
            )
        } else {
            (
@@ -111,8 +116,7 @@

        Self::add_tree_to_archive(&tree, "", &mut builder)?;

        // finish() flushes the tar footer, then finish() on the gz encoder
        // flushes the gzip footer and gives you the final Vec<u8>.
        // Flush the tar footer, then finish the gzip stream to get the final compressed bytes.
        let encoder = builder.into_inner()?;
        let bytes = encoder.finish()?;
        Ok((bytes, filename))
@@ -154,49 +158,47 @@
        Ok(())
    }

    /// Resolves a relative repository path on `current_ref` to either a folder listing (`PathView::Tree`)
    /// or a file view (`PathView::Blob`).
    pub fn resolve_path(&self, current_ref: &Ref, path: &str) -> anyhow::Result<PathView> {
        let gix_repo = self.gix();
        let commit = Commit::from_gix(
            gix_repo
                .find_reference(&current_ref.name.to_string())?
                .find_reference(&current_ref.name)?
                .peel_to_commit()?,
        )?; // however you currently get a Commit from a Ref
        )?;
        let path = path.trim_matches('/');

        if path.is_empty() {
            // root of the tree
            let entries = commit.tree("")?;
            return Ok(PathView::Tree(entries));
            return Ok(PathView::Tree(commit.tree("")?));
        }

        let tree = commit.gix.tree().context("failed to get root tree")?;

        let entry = tree
        let root_tree = commit.gix.tree().context("failed to get root tree")?;
        let entry = root_tree
            .lookup_entry_by_path(path)
            .with_context(|| format!("failed lookup for path: {path}"))?
            .with_context(|| format!("path not found: {path}"))?;

        let mode = entry.mode();
        let kind = mode.kind();

        match kind {
        match mode.kind() {
            EntryKind::Tree => {
                let entries = commit.tree(path)?;
                Ok(PathView::Tree(entries))
            }
            EntryKind::Blob | EntryKind::BlobExecutable => {
                let object = entry.object().context("failed to load blob object")?;
                let blob = object
                let blob = entry
                    .object()
                    .context("failed to load blob object")?
                    .try_into_blob()
                    .map_err(|_| anyhow::anyhow!("entry is not a blob"))?;

                let id = entry.oid().to_string();
                let size = blob.data.len() as u64;

                // try to decode as UTF-8 text; if it fails, treat as binary
                // Try decoding as UTF-8 text; if it contains non-UTF-8 bytes, treat it as binary (None).
                let lines = std::str::from_utf8(&blob.data)
                    .ok()
                    .map(|s| s.lines().map(|l| l.to_string()).collect());
                    .map(|s| s.lines().map(str::to_string).collect());

                Ok(PathView::Blob(Blob {
                    id,
@@ -207,7 +209,44 @@
            }
            EntryKind::Link => {
                anyhow::bail!("symlinks are not yet supported for direct viewing")
            }
            EntryKind::Commit => {
                anyhow::bail!("path resolves to a submodule, not a viewable file/dir")
            }
        }
    }

    /// Reads the raw bytes of a file (`Blob`) at `path` without splitting lines or cloning buffers.
    /// Returns `Ok(None)` if `path` points to a directory (`Tree`).
    pub fn read_raw_blob(&self, current_ref: &Ref, path: &str) -> anyhow::Result<Option<Vec<u8>>> {
        let path = path.trim_matches('/');
        if path.is_empty() {
            return Ok(None);
        }

        let gix_repo = self.gix();
        let root_tree = gix_repo
            .find_reference(&current_ref.name)?
            .peel_to_tree()
            .context("failed to get root tree")?;

        let entry = root_tree
            .lookup_entry_by_path(path)
            .with_context(|| format!("failed lookup for path: {path}"))?
            .with_context(|| format!("path not found: {path}"))?;

        match entry.mode().kind() {
            EntryKind::Tree => Ok(None),
            EntryKind::Blob | EntryKind::BlobExecutable => {
                let blob = entry
                    .object()
                    .context("failed to load blob object")?
                    .try_into_blob()
                    .map_err(|_| anyhow::anyhow!("entry is not a blob"))?;
                // `.detach().data` moves the underlying Vec<u8> out of the gix Blob without cloning.
                Ok(Some(blob.detach().data))
            }
            EntryKind::Link => anyhow::bail!("symlinks are not yet supported for direct viewing"),
            EntryKind::Commit => {
                anyhow::bail!("path resolves to a submodule, not a viewable file/dir")
            }