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

Diffstat

-rw-r--r-- src/main.rs 24
-rw-r--r-- templates/macros.html 16
-rw-r--r-- templates/repositorys.html 19
-rw-r--r-- src/git/commit.rs 103
-rw-r--r-- src/routes/mod.rs 36
-rw-r--r-- src/routes/static.rs 21
 6 files changed, 169 insertions(+), 50 deletions(-)

diff --git a/src/main.rs b/src/main.rs
index dea7035..ef61bfd 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -79,3 +79,27 @@
    println!("Installed /etc/systemd/system/git-rs.service");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;
    use std::time::Instant;

    #[test]
    fn commit_list_populates_head_and_branch_tips_without_n_plus_one() {
        let repo = Repository::open(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
        let current_ref = Ref {
            name: repo.head_branch_name().unwrap(),
            is_head: true,
        };
        let gix_repo = repo.gix();

        let start = Instant::now();
        let (commits, _) = repo.commits(&gix_repo, &current_ref, 0, 50, None).unwrap();
        assert!(!commits.is_empty());
        assert!(commits[0].is_head(&repo).unwrap());
        assert!(!commits[0].branch_tips(&repo).unwrap().is_empty());
        assert!(start.elapsed().as_millis() < 100);
    }
}
diff --git a/templates/macros.html b/templates/macros.html
index 3d4c916..7047cff 100644
--- a/templates/macros.html
+++ b/templates/macros.html
@@ -1,7 +1,7 @@
{% macro header(repo: Option<&Repository> = None, branches: Vec<String> = Vec::new(), current_ref: Option<&Ref> = None) %}
  {% if let Some(repo) = repo && let Some(current_ref) = current_ref %}
    <tr>
      <td class="logo" rowspan="2"><a href="/"><img src="/static/logo.png" alt="logo"></a></td>
      <td class="logo" rowspan="2"><a href="/"><img src="/static/logo.png" width="64" height="64" alt="logo"></a></td>
      <td class="main"><a href="/">index</a> : <a title="{{ repo.name }}" href="/{{ repo.name }}/">{{ repo.name }}</a></td>
      <td class="form">
        <form method="get">
@@ -19,7 +19,7 @@
    </tr>
  {% else %}
    <tr>
      <td class="logo" rowspan="2"><a href="/"><img src="/static/logo.png" alt="logo"></a></td>
      <td class="logo" rowspan="2"><a href="/"><img src="/static/logo.png" width="64" height="64" alt="logo"></a></td>
      <td class="main">y2w8 Repos</td>
    </tr>
    <tr>
@@ -105,8 +105,8 @@
          <td class="msg"><span class="msg-text">{{ branch.last_commit.summary()? }}</span></td>
          <td class="author">
            <span class="avatar">
              <img class="inline" src="{{ branch.author.avatar_url(20) }}">
              <img class="onhover" src="{{ branch.author.avatar_url(128) }}">
              <img class="inline" src="{{ branch.author.avatar_url(20) }}" width="18" height="18" loading="lazy" decoding="async" alt="">
              <img class="onhover" src="{{ branch.author.avatar_url(128) }}" width="128" height="128" loading="lazy" decoding="async" alt="">
            </span>
            {{ branch.author.name }}
          </td>
@@ -158,8 +158,8 @@
          <td>
            {% if let Some(tagger) = tag.tagger %}
                <span class="avatar">
                  <img class="inline" src="{{ tagger.avatar_url(20) }}">
                  <img class="onhover" src="{{ tagger.avatar_url(128) }}">
                  <img class="inline" src="{{ tagger.avatar_url(20) }}" width="18" height="18" loading="lazy" decoding="async" alt="">
                  <img class="onhover" src="{{ tagger.avatar_url(128) }}" width="128" height="128" loading="lazy" decoding="async" alt="">
                </span>
                {{ tagger.name }}
            {% endif %}
@@ -215,8 +215,8 @@
          </td>
          <td>
            <span class="avatar">
              <img class="inline" src="{{ commit.author.avatar_url(20) }}">
              <img class="onhover" src="{{ commit.author.avatar_url(128) }}">
              <img class="inline" src="{{ commit.author.avatar_url(20) }}" width="18" height="18" loading="lazy" decoding="async" alt="">
              <img class="onhover" src="{{ commit.author.avatar_url(128) }}" width="128" height="128" loading="lazy" decoding="async" alt="">
            </span>
            {{ commit.author.name }}
          </td>
diff --git a/templates/repositorys.html b/templates/repositorys.html
index 93c40c7..69be51c 100644
--- a/templates/repositorys.html
+++ b/templates/repositorys.html
@@ -33,23 +33,22 @@
        </tr>
    </thead>
    <tbody>
        {% for repo in repos %}
        {% for entry in repos %}
        <tr>
            <td><a href="/{{ repo.name }}/">{{ repo.name }}</a></td>
            <td><a href="/{{ repo.name }}/">{{ repo.description }}</a></td>
            <td>{% if let Some(owner) = repo.owner %}{{ owner }}{% endif %}</td>
            {% let gix_repo = repo.gix() %}
            {% if let Some(last_commit) = repo.last_commit(gix_repo)? %}
              {% let time = last_commit.committer.time.format_relative() %}
              <td data-sort="-{{ last_commit.committer.time.seconds() }}">
                <span class="{{ time.1 }}" title="{{ last_commit.committer.time.format() }}">{{ time.0 }}</span>
            <td><a href="/{{ entry.repo.name }}/">{{ entry.repo.name }}</a></td>
            <td><a href="/{{ entry.repo.name }}/">{{ entry.repo.description }}</a></td>
            <td>{% if let Some(owner) = entry.repo.owner %}{{ owner }}{% endif %}</td>
            {% if let Some(last_time) = entry.last_time %}
              {% let time = last_time.format_relative() %}
              <td data-sort="-{{ last_time.seconds() }}">
                <span class="{{ time.1 }}" title="{{ last_time.format() }}">{{ time.0 }}</span>
              </td>
            {% else %}
              <td data-sort="999999999999">
                <span class="stale">Unknown</span>
              </td>
            {% endif %}
            <td><a href="/{{ repo.name }}/">summary</a><a href="/{{ repo.name }}/log/">log</a><a href="/{{ repo.name }}/tree/">tree</a></td>
            <td><a href="/{{ entry.repo.name }}/">summary</a><a href="/{{ entry.repo.name }}/log/">log</a><a href="/{{ entry.repo.name }}/tree/">tree</a></td>
        </tr>
        {% endfor %}
    </tbody>
diff --git a/src/git/commit.rs b/src/git/commit.rs
index a6cd67e..dfda921 100644
--- a/src/git/commit.rs
+++ b/src/git/commit.rs
@@ -11,18 +11,35 @@
    pub author: GitSignature,
    pub committer: GitSignature,
    pub time: Time,
    pub is_head: bool,
    pub branch_tips: Vec<String>,
    pub gix: gix::Commit<'repo>,
}

impl<'repo> Commit<'repo> {
    pub fn from_gix(gix: gix::Commit<'_>) -> Result<Commit<'_>, Error> {
        // Decode the raw commit object once instead of re-parsing it 5 times via
        // `.tree_id()`, `.parent_ids()`, `.author()`, `.committer()`, and `.time()`.
        let (tree_id, parents, author, committer) = {
            let decoded = gix.decode()?;
            (
                decoded.tree().to_string(),
                decoded.parents().map(|id| id.to_string()).collect(),
                GitSignature::from_gix(decoded.author()?),
                GitSignature::from_gix(decoded.committer()?),
            )
        };
        let time = committer.time.clone();

        Ok(Commit {
            id: gix.id().to_string(),
            tree_id: gix.tree_id()?.to_string(),
            parents: gix.parent_ids().map(|id| id.to_string()).collect(),
            author: GitSignature::from_gix(gix.author()?),
            committer: GitSignature::from_gix(gix.committer()?),
            time: Time::new(gix.time()?),
            tree_id,
            parents,
            author,
            committer,
            time,
            is_head: false,
            branch_tips: Vec::new(),
            gix,
        })
    }
@@ -35,18 +52,16 @@
        Ok(self.gix.message()?.body.unwrap_or(BStr::new("")))
    }

    pub fn branch_name(&self, repo: &Repository) -> Result<Option<String>, Error> {
        Ok(self.branch_tips(repo)?.into_iter().next())
    pub fn branch_name(&self, _repo: &Repository) -> Result<Option<&str>, Error> {
        Ok(self.branch_tips.first().map(String::as_str))
    }

    pub fn branch_tips(&self, repo: &Repository) -> Result<Vec<String>, Error> {
        let branch_tips = repo.branch_tips_by_commit()?;
        Ok(branch_tips.get(&self.id).cloned().unwrap_or_default())
    pub fn branch_tips(&self, _repo: &Repository) -> Result<&[String], Error> {
        Ok(&self.branch_tips)
    }

    pub fn is_head(&self, repo: &Repository) -> Result<bool, Error> {
        let head_id = repo.gix().head_id().ok().map(|id| id.to_string());
        Ok(head_id.as_deref() == Some(&self.id))
    pub fn is_head(&self, _repo: &Repository) -> Result<bool, Error> {
        Ok(self.is_head)
    }
}

@@ -66,12 +81,17 @@
        id: Option<&str>,
        current_ref: &Ref,
    ) -> Result<Commit<'repo>, Error> {
        if let Some(id) = id {
            self.find_commit(gix_repo, id)
        let mut commit = if let Some(id) = id {
            self.find_commit(gix_repo, id)?
        } else {
            let mut reference = gix_repo.find_reference(&current_ref.name)?;
            Commit::from_gix(reference.peel_to_commit()?)
        }
            Commit::from_gix(reference.peel_to_commit()?)?
        };
        let head_id = gix_repo.head_id().ok().map(|id| id.to_string());
        let mut branch_tips = Self::branch_tips_from_repo(gix_repo)?;
        commit.is_head = head_id.as_deref() == Some(&commit.id);
        commit.branch_tips = branch_tips.remove(&commit.id).unwrap_or_default();
        Ok(commit)
    }

    pub fn last_commit<'repo>(
@@ -87,21 +107,45 @@
            }
        }
        Ok(None)
    }

    /// Returns the committer `Time` of the repository's latest commit without allocating
    /// a full `Commit` struct.
    pub fn last_commit_time(&self) -> Option<Time> {
        let gix_repo = self.gix();
        if let Ok(commit) = gix_repo.head_commit()
            && let Ok(sig) = commit.committer()
            && let Ok(t) = sig.time()
        {
            return Some(Time::new(t));
        }
        for reference in gix_repo.references().ok()?.all().ok()? {
            if let Ok(commit) = reference.ok()?.peel_to_commit()
                && let Ok(sig) = commit.committer()
                && let Ok(t) = sig.time()
            {
                return Some(Time::new(t));
            }
        }
        None
    }

    /// Returns the committer timestamp (in seconds) of the repository's latest commit,
    /// or `i64::MIN` if the repository has no commits yet.
    pub fn last_commit_timestamp(&self) -> i64 {
        let gix_repo = self.gix();
        self.last_commit(&gix_repo)
            .ok()
            .flatten()
            .map(|c| c.committer.time.seconds())
        self.last_commit_time()
            .map(|t| t.seconds())
            .unwrap_or(i64::MIN)
    }

    pub fn branch_tips_by_commit(&self) -> Result<HashMap<String, Vec<String>>, Error> {
        let gix_repo = self.gix();
        Self::branch_tips_from_repo(&gix_repo)
    }

    fn branch_tips_from_repo(
        gix_repo: &gix::Repository,
    ) -> Result<HashMap<String, Vec<String>>, Error> {
        let references = gix_repo.references()?;
        let mut map: HashMap<String, Vec<String>> = HashMap::new();

@@ -130,13 +174,22 @@
                Default::default(),
            ))
            .all()?;

        let head_id = gix_repo.head_id().ok().map(|id| id.to_string());
        let mut branch_tips = Self::branch_tips_from_repo(gix_repo)?;

        let mut commits = Vec::new();
        let mut commits = Vec::with_capacity(limit);
        let mut has_next = false;
        let mut matched = 0usize;

        for rev in revwalk {
            let commit = Commit::from_gix(rev?.object()?)?;
            let rev = rev?;
            if filter.is_none() && matched < offset {
                matched += 1;
                continue;
            }

            let mut commit = Commit::from_gix(rev.object()?)?;
            if let Some(f) = filter
                && !f(&commit)
            {
@@ -153,6 +206,8 @@
                break;
            }

            commit.is_head = head_id.as_deref() == Some(&commit.id);
            commit.branch_tips = branch_tips.remove(&commit.id).unwrap_or_default();
            commits.push(commit);
        }

diff --git a/src/routes/mod.rs b/src/routes/mod.rs
index 9ec1eb7..e5ca9eb 100644
--- a/src/routes/mod.rs
+++ b/src/routes/mod.rs
@@ -52,16 +52,21 @@
    }
}

struct RepoEntry {
    repo: Repository,
    last_time: Option<Time>,
}

#[derive(Template)]
#[template(path = "repositorys.html")]
struct ReposPage {
    repos: Vec<Repository>,
    repos: Vec<RepoEntry>,
}

#[get("/")]
pub async fn page(query: web::Query<PageQuery>, data: web::Data<App>) -> ActixResult<HttpResponse> {
    let rendered = {
        let mut repos: Vec<Repository> = {
        let raw_repos: Vec<Repository> = {
            let guard = match data.repos.read() {
                Ok(g) => g,
                Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
@@ -83,18 +88,39 @@
                _ => guard.clone(),
            }
        }; // guard dropped here

        // Resolve last_commit_time once per repo for both sorting and template rendering
        let mut repos: Vec<RepoEntry> = raw_repos
            .into_iter()
            .map(|repo| {
                let last_time = repo.last_commit_time();
                RepoEntry { repo, last_time }
            })
            .collect();

        if let (qt, Some(value)) = (query.query_type.as_deref(), query.value.as_deref()) {
            let value_lower = value.to_lowercase();
            repos.sort_by_key(|a| {
                (
                    relevance(a, qt, &value_lower),
                    std::cmp::Reverse(a.last_commit_timestamp()),
                    relevance(&a.repo, qt, &value_lower),
                    std::cmp::Reverse(
                        a.last_time
                            .as_ref()
                            .map(|t| t.seconds())
                            .unwrap_or(i64::MIN),
                    ),
                )
            });
        } else {
            // Auto-sort repositories by Idle/Age (most recently updated first)
            repos.sort_by_key(|a| std::cmp::Reverse(a.last_commit_timestamp()));
            repos.sort_by_key(|a| {
                std::cmp::Reverse(
                    a.last_time
                        .as_ref()
                        .map(|t| t.seconds())
                        .unwrap_or(i64::MIN),
                )
            });
        }
        ReposPage { repos }.render()
    };
diff --git a/src/routes/static.rs b/src/routes/static.rs
index cb0e0b1..ff5f4cd 100644
--- a/src/routes/static.rs
+++ b/src/routes/static.rs
@@ -7,7 +7,7 @@
struct Static;

#[get("/static/{filename:.*}")]
pub async fn files(path: web::Path<String>) -> ActixResult<HttpResponse> {
pub async fn files(req: HttpRequest, path: web::Path<String>) -> ActixResult<HttpResponse> {
    let path = path.into_inner();

    if path.is_empty() {
@@ -16,11 +16,26 @@

    match Static::get(&path) {
        Some(content) => {
            let hash = content.metadata.sha256_hash();
            let etag = format!(
                "\"{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}\"",
                hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7]
            );

            if let Some(if_none_match) = req.headers().get("If-None-Match")
                && if_none_match.to_str().ok() == Some(&etag)
            {
                return Ok(HttpResponse::NotModified()
                    .insert_header(("ETag", etag))
                    .finish());
            }

            let mime_type = mime_guess::from_path(&path).first_or_octet_stream();
            Ok(HttpResponse::Ok()
                .content_type(mime_type.as_ref())
                .insert_header(("Cache-Control", "no-cache, must-revalidate"))
                .body(content.data.into_owned()))
                .insert_header(("ETag", etag))
                .insert_header(("Cache-Control", "public, max-age=3600, must-revalidate"))
                .body(content.data))
        }
        None => Ok(HttpResponse::NotFound().body("Not Found")),
    }