Code simplification
26 files changed, 677 insertions(+), 1146 deletions(-)
@@ -914,18 +914,14 @@
"clap",
"flate2",
"gix",
"linkify",
"md5",
"mime_guess",
"notify",
"pulldown-cmark",
"rust-embed",
"serde",
"serde_json",
"tar",
"thiserror",
"time",
"timeago",
"tokio",
"v_htmlescape",
]
@@ -2157,15 +2153,6 @@
]
[[package]]
name = "isolang"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe50d48c77760c55188549098b9a7f6e37ae980c586a24693d6b01c3b2010c3c"
dependencies = [
"phf",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2278,15 +2265,6 @@
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "linkify"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92f9ae2f3d31697697311f016320fe984127e636b45cf5eb5c175b7eb103dadb"
dependencies = [
"memchr",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2476,24 +2454,6 @@
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "phf"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"
dependencies = [
"phf_shared",
]
[[package]]
name = "phf_shared"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"
dependencies = [
"siphasher",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2881,12 +2841,6 @@
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "siphasher"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
[[package]]
name = "slab"
@@ -3034,16 +2988,6 @@
dependencies = [
"num-conv",
"time-core",
]
[[package]]
name = "timeago"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46c29b13d230e9cd58513d38701a661fc06e1215398937532a2d938ecca6f219"
dependencies = [
"chrono",
"isolang",
]
[[package]]
@@ -12,18 +12,14 @@
clap = { version = "4.6.4", default-features = false, features = ["derive", "usage", "help", "std", "cargo", "env"] }
flate2 = "1.1.9"
gix = { version = "0.86.0", features = ["serde", "tracing", "parallel", "blob-diff", "revision"] }
linkify = "0.11.0"
md5 = "0.8.1"
mime_guess = "2.0.5"
notify = "8.2.0"
pulldown-cmark = "0.13.4"
rust-embed = "8.12.0"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
tar = "0.4.46"
thiserror = "2.0.19"
time = "0.3.55"
timeago = "0.6.1"
tokio = "1.53.1"
v_htmlescape = { version = "0.15.8", default-features = false, features = ["bytes-buf"] }
@@ -12,7 +12,7 @@
};
use tokio::sync::mpsc;
use crate::git::repository::Repository;
use crate::{error::Error, git::repository::Repository};
pub struct App {
pub repos_dir: String,
@@ -28,15 +28,14 @@
let (tx, mut rx) = mpsc::unbounded_channel::<Event>();
let mut watcher = notify::recommended_watcher(move |res: notify::Result<Event>| {
match res {
let mut watcher =
notify::recommended_watcher(move |res: notify::Result<Event>| match res {
Ok(event) => {
let _ = tx.send(event);
}
Err(e) => eprintln!("repo watcher error: {e}"),
}
})
.expect("Failed to create repo directory watcher");
})
.expect("Failed to create repo directory watcher");
watcher
.watch(Path::new(&repos_dir), RecursiveMode::NonRecursive)
@@ -147,13 +146,18 @@
}
}
pub fn find_repo(&self, name: String) -> Option<Repository> {
pub fn find_repo(&self, name: &str) -> Option<Repository> {
self.repos
.read()
.ok()?
.iter()
.find(|r| r.name == name)
.cloned()
}
pub fn get_repo(&self, name: &str) -> Result<Repository, Error> {
self.find_repo(name)
.ok_or_else(|| Error::NotFound("Repo not found".to_string()))
}
}
@@ -1,10 +1,18 @@
use actix_web::{HttpResponse, ResponseError, http::StatusCode};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("operation failed")]
Failed,
#[error("not found: {0}")]
#[error("{0}")]
NotFound(String),
#[error(transparent)]
Render(#[from] askama::Error),
#[error(transparent)]
Anyhow(#[from] anyhow::Error),
#[error(transparent)]
Utf8(#[from] std::str::Utf8Error),
@@ -71,4 +79,22 @@
#[error(transparent)]
Boxed(#[from] Box<dyn std::error::Error + Send + Sync>),
}
impl ResponseError for Error {
fn status_code(&self) -> StatusCode {
match self {
Self::NotFound(_) => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status_code()).body(self.to_string())
}
}
pub fn render_html<T: askama::Template>(template: &T) -> Result<HttpResponse, Error> {
let html = template.render()?;
Ok(HttpResponse::Ok().content_type("text/html").body(html))
}
@@ -3,7 +3,7 @@
};
pub use crate::app::App;
pub use crate::error::Error;
pub use crate::error::{Error, render_html};
pub use crate::git::{
self, GitSignature, branch::Branch, commit::Commit, refs::Ref, repository::Repository, tag::Tag,
};
@@ -1,5 +1,7 @@
/* ==========================================================================
1. Design Tokens (Catppuccin Mocha Palette)
========================================================================== */
:root {
/* Catppuccin Mocha palette */
--base: #1e1d2d;
--mantle: #181825;
--crust: #11111b;
@@ -27,7 +29,7 @@
--green: #a6e3a1;
--teal: #94e2d5;
--sky: #89dceb;
--saphhire: #74c7ec;
--sapphire: #74c7ec;
--blue: #89b4fa;
--lavender: #b4befe;
@@ -42,13 +44,15 @@
--light_grey: #605f6f;
}
/* ==========================================================================
2. Base & Typography
========================================================================== */
* {
box-sizing: border-box;
}
body {
font-family: 'Maple Mono NF', monospace;
/* font-family: 'BigBlueTerm437 Nerd Font', monospace; */
font-size: 1rem;
margin: 0;
background: var(--base);
@@ -70,40 +74,54 @@
color: var(--text);
}
table {
border-collapse: collapse;
width: 100%;
overflow: hidden;
a {
color: var(--peach);
padding: 5px;
text-decoration: none;
}
td.msg {
display: flex;
align-items: center;
gap: 0.4em;
overflow: hidden; /* needed for ellipsis to take effect */
a:hover,
a:active,
a.active {
color: var(--crust);
background: var(--peach);
}
td.msg .msg-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 0; /* flex children don't shrink below content size by default — this overrides that */
code {
background: var(--black2);
color: var(--green);
padding: 2px 6px;
}
td.author {
white-space: nowrap;
pre {
color: var(--text);
background: var(--surface0);
border: 1px var(--surface1) solid;
font-size: 14px;
padding: 6px 10px;
}
pre code {
color: var(--text);
background: var(--surface0);
padding: 0;
}
/* ==========================================================================
3. Global Tables & Forms
========================================================================== */
table {
border-collapse: collapse;
width: 100%;
overflow: hidden;
}
th {
text-align: left;
white-space: nowrap;
}
tbody tr.no-background:nth-child(even),
tbody tr.no-background:nth-child(odd),
tbody tr.no-background:hover {
background: transparent;
color: var(--peach);
font-weight: 600;
letter-spacing: 0.05em;
}
td {
@@ -112,6 +130,17 @@
padding: 0.75rem 1rem;
}
td a {
color: var(--text);
}
td.mode,
th.mode {
width: 10ch;
font-family: monospace;
white-space: nowrap;
}
tbody tr:nth-child(even) {
background: var(--one_bg);
}
@@ -124,18 +153,18 @@
background: var(--surface0);
}
th {
color: var(--peach);
font-weight: 600;
font-style: bold;
letter-spacing: 0.05em;
tbody tr.no-background:nth-child(even),
tbody tr.no-background:nth-child(odd),
tbody tr.no-background:hover {
background: transparent;
}
td.form {
text-align: right;
}
td.form input {
td.form input,
td.form select {
color: var(--text);
background: var(--surface0);
border: 1px solid var(--surface1);
@@ -143,168 +172,201 @@
padding: 5px;
}
td.form select {
color: var(--text);
background: var(--surface0);
border: 1px solid var(--surface1);
border-radius: 0;
padding: 5px;
/* ==========================================================================
4. Header & Navigation Tabs
========================================================================== */
td.logo {
width: 96px;
vertical-align: top;
}
td.logo img {
width: 96px;
height: 96px;
}
td.main {
font-size: 200%;
padding-left: 10px;
white-space: nowrap;
}
td.sub {
color: var(--subtext0);
border-top: solid 2px var(--surface1);
padding-left: 10px;
}
.tabs {
margin-top: 2rem;
background: var(--black2);
}
.tabs a,
td a {
.tabs a {
color: var(--text);
}
.commit-info {
margin-top: 2rem;
max-width: fit-content;
background: transparent;
.tree-breadcrumb {
background: var(--black2);
padding: 5px;
}
.commit-info tr:nth-child(odd),
.commit-info tr:nth-child(even),
.commit-info tr:hover{
background-color: transparent;
.show_more a,
.pagination a {
color: var(--peach);
font-size: 18px;
}
.commit-info td {
padding: 0.20rem 1rem 0.20rem 0rem;
.show_more a:hover,
.pagination a:hover {
color: var(--crust);
}
.commit-info a {
color: var(--peach);
.pagination {
margin-top: 1rem;
text-align: center;
font-size: 20px;
}
.commit-subject {
padding: 1rem 0;
/* ==========================================================================
5. Metadata Badges, Avatars & Status Indicators
========================================================================== */
.fresh {
color: var(--green);
font-weight: 600;
}
.commit-subject h1 {
font-weight: bold;
font-size: 120%;
.recent {
color: var(--overlay1);
}
.commit-subject h4 {
font-weight: bold;
color: var(--overlay1);
.stale {
color: var(--surface2);
}
.tree-breadcrumb {
background: var(--black2);
padding: 5px;
.description {
color: var(--subtext1);
font-style: italic;
}
code {
background: var(--black2);
color: var(--green);
padding: 2px 6px;
.folder {
color: var(--peach);
}
pre {
color: var(--text);
.clone-url {
background: var(--surface0);
border: 1px var(--surface1) solid;
font-size: 14px;
padding: 6px 10px;
color: var(--peach);
padding: 4px 10px;
font-size: 0.85em;
}
pre code {
.badge_head {
background: var(--crust);
color: var(--text);
background: var(--surface0);
padding: 0;
border: 1px solid var(--red);
padding: 2px 8px;
}
a {
color: var(--peach);
padding: 5px;
text-decoration: none;
.badge_branch {
background: var(--crust);
color: var(--text);
border: 1px solid var(--green);
padding: 2px 8px;
}
a:hover,
a:active,
a.active {
color: var(--crust);
background: var(--peach);
.badge_branch:hover,
.badge_head:hover {
color: var(--peach);
background: var(--crust);
}
.fresh {
.green {
color: var(--green);
font-weight: 600;
}
.recent {
color: var(--overlay1);
}
.stale {
color: var(--surface2);
.red {
color: var(--red);
}
.description {
color: var(--subtext1);
font-style: italic;
span.avatar img.inline {
width: 20px;
height: 20px;
vertical-align: top;
}
span.avatar img.onhover {
display: none;
border: 1px solid var(--surface1);
padding: 0px;
padding: 0;
width: 128px;
height: 128px;
}
span.avatar img.inline {
width: 20px;
height: 20px;
vertical-align: top;
}
span.avatar:hover>img.onhover {
span.avatar:hover > img.onhover {
display: block;
position: absolute;
margin-left: 1.5em;
background-color: var(--crust);
}
.folder {
color: var(--peach);
/* ==========================================================================
6. Commit View & Message Cell
========================================================================== */
td.msg {
display: flex;
align-items: center;
gap: 0.4em;
overflow: hidden;
}
td.logo {
width: 96px;
vertical-align: top;
td.msg .msg-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 0;
}
td.logo img {
width: 96px;
height: 96px;
td.author {
white-space: nowrap;
}
td.main {
font-size: 200%;
padding-left: 10px;
white-space: nowrap;
.commit-info {
margin-top: 2rem;
max-width: fit-content;
background: transparent;
}
td.sub {
color: var(--subtext0);
border-top: solid 2px var(--surface1);
padding-left: 10px;
.commit-info tr:nth-child(odd),
.commit-info tr:nth-child(even),
.commit-info tr:hover {
background-color: transparent;
}
td.mode, th.mode {
width: 10ch;
font-family: monospace;
white-space: nowrap;
.commit-info td {
padding: 0.20rem 1rem 0.20rem 0;
}
/* === Blob metadata bar === */
.commit-info a {
color: var(--peach);
}
.commit-subject {
padding: 1rem 0;
}
.commit-subject h1 {
font-weight: bold;
font-size: 120%;
}
.commit-subject h4 {
font-weight: bold;
color: var(--overlay1);
}
/* ==========================================================================
7. Tree & Blob View
========================================================================== */
.blob-meta {
display: flex;
align-items: center;
@@ -331,7 +393,7 @@
.blob-meta .size {
white-space: nowrap;
color: var(--subtext1);
margin-left: auto; /* pushes size + raw-link to the right edge */
margin-left: auto;
}
.blob-table {
@@ -342,7 +404,7 @@
.blob-table tr:nth-child(odd),
.blob-table tr:nth-child(even),
.blob-table tr:hover{
.blob-table tr:hover {
background-color: transparent;
}
@@ -351,7 +413,7 @@
text-align: right;
padding: 0 0.8em;
color: var(--overlay0);
user-select: none; /* selecting code shouldn't drag line numbers along with it */
user-select: none;
border-right: 1px solid var(--surface1);
vertical-align: top;
white-space: nowrap;
@@ -368,87 +430,20 @@
background: none;
border: none;
padding: 0;
white-space: pre-wrap; /* wraps long lines instead of forcing horizontal scroll */
white-space: pre-wrap;
word-break: break-all;
}
.clone-url {
background: var(--surface0);
color: var(--peach);
padding: 4px 10px;
font-size: 0.85em;
}
.show_more a,
.pagination a{
color: var(--peach);
font-size: 18px;
}
.show_more a:hover,
.pagination a:hover{
color: var(--crust);
}
.pagination {
margin-top: 1rem;
text-align: center;
font-size: 20px;
}
.badge_head {
background: var(--crust);
color: var(--text);
border: 1px solid var(--red);
padding: 2px 8px;
}
.badge_branch {
background: var(--crust);
color: var(--text);
border: 1px solid var(--green);
padding: 2px 8px;
}
.badge_branch:hover,
.badge_head:hover {
color: var(--peach);
background: var(--crust);
}
.green {
color: var(--green);
}
.red {
color: var(--red);
}
.mt-1 {
margin-top: 1rem;
}
.mt-2 {
margin-top: 2rem;
}
.mt-3 {
margin-top: 3rem;
}
.mt-4 {
margin-top: 4rem;
}
.mt-5 {
margin-top: 5rem;
}
/* ==========================================================================
8. Diff & Diffstat
========================================================================== */
table.diffstat {
background: var(--surface0);
border: 1px var(--surface1) solid;
max-width: 50%;
min-width: 50%;
}
table.diffstat td {
padding: 0.2em 0.2em 0.1em 0.1em;
}
@@ -456,7 +451,7 @@
.diffstat tr,
.diffstat tr:nth-child(odd),
.diffstat tr:nth-child(even),
.diffstat tr:hover{
.diffstat tr:hover {
background-color: transparent;
}
@@ -506,11 +501,6 @@
color: var(--blue);
}
.diff-addition::before, .diff-deletion::before, .diff-context::before {
display: inline-block;
color: #888;
}
.diff-file-header {
font-weight: bold;
}
@@ -523,31 +513,35 @@
background: #2b3038;
color: var(--green);
display: block;
}
&::before {
content: '+ ';
}
.diff-addition::before {
content: '+ ';
display: inline-block;
color: #888;
}
.diff-deletion {
background: #332839;
color: var(--red);
display: block;
&::before {
content: '- ';
}
}
.diff-context {
&::before {
content: ' ';
}
.diff-deletion::before {
content: '- ';
display: inline-block;
color: #888;
}
/* NOTE: Markdown */
.diff-context::before {
content: ' ';
display: inline-block;
color: #888;
}
/* ==========================================================================
9. Markdown & Readme
========================================================================== */
.readme h1,
.readme h2,
.readme h3,
@@ -563,10 +557,9 @@
padding-bottom: 0.3rem;
}
/* Paragraph */
.readme p {
font-size: 14px;
color: var(--catppuccin-subtext1);
color: var(--subtext1);
}
.readme hr {
@@ -28,43 +28,22 @@
{% endif %}
{% endmacro %}
{% macro repo_tabs(repo: Repository, current_ref: Ref, query: PageQuery, active: str) %}
{% macro repo_tabs(repo: Repository, current_ref: Ref, query: PageQuery, active: str) %}
<tr>
<td>
{% decl parameters %}
{% if let Some(id) = query.id %}
{% let parameters %}?id={{ id }}{% endlet %}
<a href="/{{ repo.name }}/about/" class="{% if active == "about" %}active{% endif %}">about</a>
<a href="/{{ repo.name }}/" class="{% if active == "summary" %}active{% endif %}">summary</a>
<a href="/{{ repo.name }}/refs/{{ parameters }}" class="{% if active == "refs" %}active{% endif %}">refs</a>
<a href="/{{ repo.name }}/log/" class="{% if active == "log" %}active{% endif %}">log</a>
<a href="/{{ repo.name }}/tree/{{ parameters }}" class="{% if active == "tree" %}active{% endif %}">tree</a>
<a href="/{{ repo.name }}/commit/{{ parameters }}" class="{% if active == "commit" %}active{% endif %}">commit</a>
<a href="/{{ repo.name }}/diff/{{ parameters }}" class="{% if active == "diff" %}active{% endif %}">diff</a>
{% else if let Some(head) = query.head %}
{% let parameters %}?h={{ head }}{% endlet %}
<a href="/{{ repo.name }}/about/{{ parameters }}" class="{% if active == "about" %}active{% endif %}">about</a>
<a href="/{{ repo.name }}/" class="{% if active == "summary" %}active{% endif %}">summary</a>
<a href="/{{ repo.name }}/refs/" class="{% if active == "refs" %}active{% endif %}">refs</a>
<a href="/{{ repo.name }}/log/{{ parameters }}" class="{% if active == "log" %}active{% endif %}">log</a>
<a href="/{{ repo.name }}/tree/{{ parameters }}" class="{% if active == "tree" %}active{% endif %}">tree</a>
<a href="/{{ repo.name }}/commit/{{ parameters }}" class="{% if active == "commit" %}active{% endif %}">commit</a>
<a href="/{{ repo.name }}/diff/{{ parameters }}" class="{% if active == "diff" %}active{% endif %}">diff</a>
{% else %}
<a href="/{{ repo.name }}/about/" class="{% if active == "about" %}active{% endif %}">about</a>
<a href="/{{ repo.name }}/" class="{% if active == "summary" %}active{% endif %}">summary</a>
<a href="/{{ repo.name }}/refs/" class="{% if active == "refs" %}active{% endif %}">refs</a>
<a href="/{{ repo.name }}/log/" class="{% if active == "log" %}active{% endif %}">log</a>
<a href="/{{ repo.name }}/tree/" class="{% if active == "tree" %}active{% endif %}">tree</a>
<a href="/{{ repo.name }}/commit/" class="{% if active == "commit" %}active{% endif %}">commit</a>
<a href="/{{ repo.name }}/diff/" class="{% if active == "diff" %}active{% endif %}">diff</a>
{% endif %}
<a href="/{{ repo.name }}/about/{{ query.head_param() }}" class="{% if active == "about" %}active{% endif %}">about</a>
<a href="/{{ repo.name }}/" class="{% if active == "summary" %}active{% endif %}">summary</a>
<a href="/{{ repo.name }}/refs/{{ query.id_param() }}" class="{% if active == "refs" %}active{% endif %}">refs</a>
<a href="/{{ repo.name }}/log/{{ query.head_param() }}" class="{% if active == "log" %}active{% endif %}">log</a>
<a href="/{{ repo.name }}/tree/{{ query.id_or_head_param() }}" class="{% if active == "tree" %}active{% endif %}">tree</a>
<a href="/{{ repo.name }}/commit/{{ query.id_or_head_param() }}" class="{% if active == "commit" %}active{% endif %}">commit</a>
<a href="/{{ repo.name }}/diff/{{ query.id_or_head_param() }}" class="{% if active == "diff" %}active{% endif %}">diff</a>
</td>
<td class="form">
<form method="get" action="/{{ repo.name }}/log/">
<select name="qt">
<option value="msg" selected>msg</option>
<option value="author" >author</option>
<option value="author">author</option>
<option value="committer">committer</option>
</select>
<input type="search" name="v" size="10" value="">
@@ -74,6 +53,40 @@
</tr>
{% endmacro %}
{% macro diff_view(repo, diff, query) %}
<table class="diffstat">
<tbody>
{% for file_diff in diff.file_diffs %}
<tr>
<td class="mode">{{ file_diff.mode }}</td>
<td class="upd">
<a href="/{{ repo.name }}/diff/{{ file_diff.path }}{% if let Some(id) = query.id %}?id={{ id }}{% endif %}" class="{{ file_diff.state }}">{{ file_diff.path }}</a>
</td>
<td class="right">{{ file_diff.total }}</td>
<td class="graph">
<table summary="file diffstat" style="width: {{ file_diff.total_percentage }}%">
<tbody>
<tr>
{% if file_diff.total != 0 %}
{% if file_diff.insertions_percentage > 0.0 %}
<td class="diffstat-addition" style="width: {{ file_diff.insertions_percentage }}%;"></td>
{% endif %}
{% if file_diff.deletions_percentage > 0.0 %}
<td class="diffstat-deletion" style="width: {{ file_diff.deletions_percentage }}%;"></td>
{% endif %}
{% endif %}
</tr>
</tbody>
</table>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<pre class="diff">{{ diff.stats }}
{{ diff.output|safe }}</pre>
{% endmacro %}
{% macro branches(branches, branches_has_more, has_prev, page, mode) %}
<thead>
<tr>
@@ -107,9 +120,9 @@
{% if has_prev %}
{% let offset = offset.saturating_sub(PAGE_SIZE) %}
{% if offset > 0 %}
<a href="/{{ repo.name }}/refs/heada/?ofs={{ offset }}">[prev]</a>
<a href="/{{ repo.name }}/refs/heads/?ofs={{ offset }}">[prev]</a>
{% else %}
<a href="/{{ repo.name }}/refs/heada/">[prev]</a>
<a href="/{{ repo.name }}/refs/heads/">[prev]</a>
{% endif %}
{% endif %}
@@ -12,12 +12,15 @@
impl<'repo> Branch<'repo> {
pub fn from_gix(mut reference: Reference<'repo>) -> Result<Branch<'repo>, Error> {
let commit = reference.peel_to_commit()?;
let author = GitSignature::from_gix(commit.author()?);
let time = Time::new(commit.time()?);
let last_commit = Commit::from_gix(commit)?;
Ok(Branch {
name: reference.name().shorten().to_string(),
last_commit: Commit::from_gix(commit.clone())?,
author: GitSignature::from_gix(commit.author()?),
time: Time::new(commit.time()?),
last_commit,
author,
time,
gix: reference,
})
}
@@ -43,20 +43,7 @@
}
pub fn branch_name(&self, repo: &Repository) -> Result<Option<String>, Error> {
let mut branch_name: Option<String> = None;
let gix_repo = repo.gix();
let references = gix_repo.references()?;
let local_branches = references.local_branches()?;
for branch in local_branches {
let mut branch = branch?;
let commit_id = branch.peel_to_commit()?.id().to_string();
if commit_id == self.id {
branch_name = Some(branch.name().shorten().to_string())
}
}
Ok(branch_name)
Ok(self.branch_tips(repo)?.into_iter().next())
}
pub fn branch_tips(&self, repo: &Repository) -> Result<Vec<String>, Error> {
@@ -72,31 +59,49 @@
}
impl Repository {
/// Looks up a Commit by its 40-character hex SHA-1 hash.
pub fn find_commit<'repo>(
&self,
gix_repo: &'repo gix::Repository,
id: &str,
) -> Result<Commit<'repo>, Error> {
let oid = gix::ObjectId::from_str(id)?;
Commit::from_gix(gix_repo.find_commit(oid)?)
}
/// Resolves a Commit either from an explicit `?id=<sha>` query parameter,
/// or by peeling the active branch/tag reference (`current_ref`) to its latest commit.
pub fn resolve_commit<'repo>(
&self,
gix_repo: &'repo gix::Repository,
id: Option<&str>,
current_ref: &Ref,
) -> Result<Commit<'repo>, Error> {
Commit::from_gix(
gix_repo
.find_commit(gix::ObjectId::from_str(id)?)?
.to_owned(),
)
if let Some(id) = id {
self.find_commit(gix_repo, id)
} else {
let mut reference = gix_repo.find_reference(¤t_ref.name)?;
Commit::from_gix(reference.peel_to_commit()?)
}
}
/// Returns the latest commit on `HEAD` (or falls back to the first valid reference in the repo).
pub fn last_commit<'repo>(
&self,
gix_repo: &'repo gix::Repository,
) -> Result<Option<Commit<'repo>>, Error> {
for reference in gix_repo.references()?.all()? {
let Ok(commit) = reference?.peel_to_commit() else {
continue;
};
if let Ok(commit) = gix_repo.head_commit() {
return Ok(Some(Commit::from_gix(commit)?));
}
for reference in gix_repo.references()?.all()? {
if let Ok(commit) = reference?.peel_to_commit() {
return Ok(Some(Commit::from_gix(commit)?));
}
}
Ok(None)
}
/// Builds a map of `commit_sha -> [branch_names]` for every local branch (`refs/heads/*`).
pub fn branch_tips_by_commit(&self) -> Result<HashMap<String, Vec<String>>, Error> {
let gix_repo = self.gix();
let references = gix_repo.references()?;
@@ -113,6 +118,8 @@
Ok(map)
}
/// Walks the commit graph backwards starting from `current_ref` (like `git log`),
/// sorted newest-first by commit timestamp, with optional filtering and pagination.
pub fn commits<'repo>(
&self,
gix_repo: &'repo gix::Repository,
@@ -121,8 +128,15 @@
limit: usize,
filter: Option<&dyn Fn(&Commit) -> bool>,
) -> Result<(Vec<Commit<'repo>>, bool), Error> {
// 1. Parse the branch/tag name (e.g. "main") into its starting commit ObjectId
let start = gix_repo.rev_parse_single(current_ref.name.as_bstr())?;
let revwalk = gix_repo.rev_walk([start]).all()?;
// 2. Walk parent links backwards from `start`, ordered by commit time
let revwalk = gix_repo
.rev_walk([start])
.sorting(gix::revision::walk::Sorting::ByCommitTime(
Default::default(),
))
.all()?;
let mut commits: Vec<Commit> = Vec::new();
let mut has_next = false;
@@ -59,7 +59,7 @@
pub fn diff(
&self,
repo: &Repository,
limit_file: Option<String>,
limit_file: Option<&str>,
format: DiffFormat,
) -> Result<Diff, Error> {
match format {
@@ -68,36 +68,32 @@
}
}
/// Computes the diff between this commit and its first parent commit (or an empty tree if this is the initial commit).
fn diff_with<F: DiffFormatter>(
&self,
repo: &Repository,
limit_file: Option<String>,
limit_file: Option<&str>,
formatter: F,
) -> Result<Diff, Error> {
const WIDTH: usize = 80;
let mut diff = Diff::default();
let gix_repo = repo.gix();
// Phase 1: Get this commit's root directory Tree and its first parent's root directory Tree.
// If the commit has no parents (the very first commit in the repo), compare against an empty Tree.
let current_tree = self.gix.tree()?;
let parent_tree = self
.gix
.ancestors()
.first_parent_only()
.all()?
.nth(1)
.transpose()?
.map(|v| v.object())
.transpose()?
.map(|v| v.tree())
.transpose()?
.unwrap_or_else(|| gix_repo.empty_tree());
// hoisted out of the per-change closure — it's the same for every
// file in this commit, no need to recompute it each time.
let parent_id = self.gix.parent_ids().next().map(|id| id.to_string());
let first_parent = self.gix.parent_ids().next();
let parent_tree = match first_parent {
Some(id) => id.object()?.into_commit().tree()?,
None => gix_repo.empty_tree(),
};
let parent_id = first_parent.map(|id| id.to_string());
let commit_id = self.gix.id.to_string();
let mut resource_cache = repo.gix().diff_resource_cache_for_tree_diff()?;
// `tree_diff_cache` is held by the tree-walker while iterating directory changes;
// `blob_diff_cache` is used inside the callback to diff individual file contents (Blobs).
let mut tree_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;
let mut blob_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;
let mut changes = parent_tree.changes()?;
changes.options(|opts| {
@@ -105,21 +101,15 @@
});
changes.for_each_to_obtain_tree_with_cache(
¤t_tree,
&mut gix_repo.diff_resource_cache_for_tree_diff()?,
&mut tree_diff_cache,
|change| {
DiffBuilder {
output: &mut diff.output,
resource_cache: &mut resource_cache,
resource_cache: &mut blob_diff_cache,
diffs: &mut diff.file_diffs,
formatter: &formatter,
}
.handle(
change,
repo,
parent_id.as_deref(),
&commit_id,
limit_file.clone(),
)
.handle(change, repo, parent_id.as_deref(), &commit_id, limit_file)
},
)?;
@@ -187,34 +177,20 @@
}
writeln!(diff.stats)?;
diff.file_diffs = diff
.file_diffs
.into_iter()
.map(|f| {
let total_percentage = if diff.total < 100 && diff.total > 0 {
diff.total as f64
} else if diff.total > 0 {
(f.total as f64) * 100.0 / (diff.total as f64)
} else {
0.0
};
let (insertions_percentage, deletions_percentage) = if f.total > 0 {
(
(f.insertions as f64) * 100.0 / (f.total as f64),
(f.deletions as f64) * 100.0 / (f.total as f64),
)
} else {
(0.0, 0.0)
};
FileDiff {
total_percentage,
insertions_percentage,
deletions_percentage,
..f
}
})
.collect();
for f in &mut diff.file_diffs {
f.total_percentage = if diff.total < 100 && diff.total > 0 {
diff.total as f64
} else if diff.total > 0 {
(f.total as f64) * 100.0 / (diff.total as f64)
} else {
0.0
};
if f.total > 0 {
f.insertions_percentage = (f.insertions as f64) * 100.0 / (f.total as f64);
f.deletions_percentage = (f.deletions as f64) * 100.0 / (f.total as f64);
}
}
Ok(diff)
}
@@ -261,7 +237,7 @@
repo: &Repository,
parent_id: Option<&str>,
commit_id: &str,
limit_file: Option<String>,
limit_file: Option<&str>,
) -> anyhow::Result<gix::object::tree::diff::Action> {
if !change.entry_mode().is_blob_or_symlink() {
return Ok(gix::object::tree::diff::Action::Continue(()));
@@ -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(¤t_ref.name.to_string())?
.find_reference(¤t_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(¤t_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")
}
@@ -1,5 +1,5 @@
use anyhow::Context;
use gix::objs::{Kind, TagRef};
use gix::objs::Kind;
use crate::prelude::*;
@@ -8,6 +8,16 @@
Tree(String),
}
impl TaggedObject {
fn from_kind_and_id(kind: Kind, id: String) -> Option<Self> {
match kind {
Kind::Commit => Some(Self::Commit(id)),
Kind::Tree => Some(Self::Tree(id)),
_ => None,
}
}
}
pub struct Tag {
pub name: String,
pub id: String,
@@ -18,70 +28,68 @@
}
impl Tag {
/// Builds a `Tag` from a `refs/tags/*` Git reference.
///
/// Git has two types of tags:
/// 1. **Annotated tags** (`git tag -a`): store a dedicated Tag object with a tagger, date, and message.
/// 2. **Lightweight tags** (`git tag`): just a reference pointing directly at a Commit (no Tag object).
pub fn from_gix(mut gix: gix::Reference<'_>) -> anyhow::Result<Tag> {
let tag = match gix.peel_to_tag() {
Ok(tag) => tag.detach().data,
Err(error) => Self::lightweight_tag_object_data(&mut gix).with_context(|| {
format!("Couldn't get to a tag from the given reference: {error}")
})?,
};
let tag_ref = TagRef::from_bytes(&tag, gix::hash::Kind::shortest())?;
let message = tag_ref.message.to_string();
let tagged_object = match tag_ref.target_kind {
Kind::Commit => Some(TaggedObject::Commit(tag_ref.target.to_string())),
Kind::Tree => Some(TaggedObject::Tree(tag_ref.target.to_string())),
_ => None,
};
let time: Time;
let mut tagger: Option<GitSignature> = None;
if let Some(sig) = tag_ref.tagger()? {
tagger = Some(GitSignature::from_gix(sig))
}
if let Some(ref tagger) = tagger {
time = tagger.time.clone()
let name = gix.name().shorten().to_string();
if let Ok(tag_obj) = gix.peel_to_tag() {
// Case 1: Annotated tag
let tag_ref = tag_obj.decode()?;
let message = tag_ref.message.to_string();
let tagged_object =
TaggedObject::from_kind_and_id(tag_ref.target_kind, tag_ref.target.to_string());
let tagger = tag_ref.tagger()?.map(GitSignature::from_gix);
let time = match &tagger {
Some(t) => t.time.clone(),
None => Self::commit_time(&mut gix)?,
};
Ok(Tag {
name,
id: gix.id().to_string(),
message,
tagger,
tagged_object,
time,
})
} else {
time = Time::new(
gix.peel_to_commit()
.with_context(|| "Couldn't get to a commit from the given reference!")?
.time()?,
)
// Case 2: Lightweight tag (points directly to a Commit or Tree)
let target = gix
.follow_to_object()
.context("Failed to resolve lightweight tag target")?;
let target_kind = target.header()?.kind();
let tagged_object = TaggedObject::from_kind_and_id(target_kind, target.to_string());
let time = Self::commit_time(&mut gix)?;
Ok(Tag {
name,
id: gix.id().to_string(),
message: String::new(),
tagger: None,
tagged_object,
time,
})
}
Ok(Tag {
name: gix.name().shorten().to_string(),
id: gix.id().to_string(),
message,
tagger,
tagged_object,
time,
})
}
fn lightweight_tag_object_data(reference: &mut gix::Reference) -> anyhow::Result<Vec<u8>> {
let target = reference
.follow_to_object()
.context("Failed to resolve lightweight tag target")?;
let tag_name = reference.name().shorten();
let target_kind = target.header()?.kind();
if target_kind == Kind::Tag {
anyhow::bail!("reference resolves to an annotated tag object");
}
Ok(format!("object {target}\ntype {target_kind}\ntag {tag_name}\n\n").into_bytes())
fn commit_time(gix: &mut gix::Reference<'_>) -> anyhow::Result<Time> {
let commit = gix
.peel_to_commit()
.context("Couldn't get to a commit from the given reference!")?;
Ok(Time::new(commit.time()?))
}
}
impl Repository {
pub fn find_tag(&self, name: &str) -> anyhow::Result<Tag> {
let gix_repo = self.gix();
Tag::from_gix(
gix_repo
.find_reference(&format!("tags/{}", name))?
.to_owned(),
)
let reference = gix_repo.find_reference(&format!("tags/{name}"))?;
Tag::from_gix(reference)
}
pub fn tags(&self, offset: usize, limit: usize) -> anyhow::Result<(Vec<Tag>, bool)> {
@@ -98,7 +106,7 @@
break;
}
let rev = rev.unwrap();
let rev = rev.map_err(|e| anyhow::anyhow!(e))?;
tags.push(Tag::from_gix(rev)?);
}
Ok((tags, has_next))
@@ -58,12 +58,11 @@
let kind = mode.kind();
let size = if matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
entry
.object()
.context("failed to load blob object")?
.try_into_blob()
self.gix
.repo
.find_header(entry.oid())
.ok()
.map(|blob| blob.data.len() as u64)
.map(|h| h.size())
} else {
None
};
@@ -24,7 +24,7 @@
}
let name = path.into_inner();
let repo = match data.find_repo(name) {
let repo = match data.find_repo(&name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
@@ -62,7 +62,7 @@
body: Bytes,
) -> ActixResult<HttpResponse> {
let name = path.into_inner();
let repo = match data.find_repo(name) {
let repo = match data.find_repo(&name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
@@ -77,7 +77,7 @@
body: Bytes,
) -> ActixResult<HttpResponse> {
let name = path.into_inner();
let repo = match data.find_repo(name) {
let repo = match data.find_repo(&name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
@@ -26,6 +26,32 @@
pub offset: Option<usize>,
}
impl PageQuery {
pub fn id_param(&self) -> String {
match &self.id {
Some(id) => format!("?id={id}"),
None => String::new(),
}
}
pub fn head_param(&self) -> String {
match (&self.id, &self.head) {
(None, Some(head)) => format!("?h={head}"),
_ => String::new(),
}
}
pub fn id_or_head_param(&self) -> String {
if let Some(id) = &self.id {
format!("?id={id}")
} else if let Some(head) = &self.head {
format!("?h={head}")
} else {
String::new()
}
}
}
#[derive(Template)]
#[template(path = "repositorys.html")]
struct ReposPage {
@@ -61,35 +61,5 @@
<h4>{{ commit.body()? }}</h4>
</div>
<h3><a href="/{{ repo.name }}/diff/?id={{ commit.id }}">Diffstat</a></h3>
<table class="diffstat">
<tbody>
{% for file_diff in diff.file_diffs %}
<tr>
<td class="mode">{{ file_diff.mode }}</td>
<td class="upd">
<a href="/{{ repo.name }}/diff/{{ file_diff.path }}{% if let Some(id) = query.id %}?id={{ id }}{% endif %}" class="{{ file_diff.state }}">{{ file_diff.path }}</a>
</td>
<td class="right">{{ file_diff.total }}</td>
<td class="graph">
<table summary="file diffstat" style="width: {{ file_diff.total_percentage }}%">
<tbody>
<tr>
{% if file_diff.total != 0 %}
{% if file_diff.insertions_percentage > 0.0 %}
<td class="diffstat-addition" style="width: {{ file_diff.insertions_percentage }}%;"></td>
{% endif %}
{% if file_diff.deletions_percentage > 0.0 %}
<td class="diffstat-deletion" style="width: {{ file_diff.deletions_percentage }}%;"></td>
{% endif %}
{% endif %}
</tr>
</tbody>
</table>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<pre class="diff">{{ diff.stats }}
{{ diff.output|safe }}</pre>
{{ macros::diff_view(repo, diff, query) }}
{% endblock %}
@@ -12,35 +12,5 @@
{% block content %}
<h3><a href="/{{ repo.name }}/diff/">Diffstat</a>{% if let Some(file_path) = file_path %} <strong>(limited to '{{ file_path }}')</strong>{% endif %}</h3>
<table class="diffstat">
<tbody>
{% for file_diff in diff.file_diffs %}
<tr>
<td class="mode">{{ file_diff.mode }}</td>
<td class="upd">
<a href="/{{ repo.name }}/diff/{{ file_diff.path }}{% if let Some(id) = query.id %}?id={{ id }}{% endif %}" class="{{ file_diff.state }}">{{ file_diff.path }}</a>
</td>
<td class="right">{{ file_diff.total }}</td>
<td class="graph">
<table summary="file diffstat" style="width: {{ file_diff.total_percentage }}%">
<tbody>
<tr>
{% if file_diff.total != 0 %}
{% if file_diff.insertions_percentage > 0.0 %}
<td class="diffstat-addition" style="width: {{ file_diff.insertions_percentage }}%;"></td>
{% endif %}
{% if file_diff.deletions_percentage > 0.0 %}
<td class="diffstat-deletion" style="width: {{ file_diff.deletions_percentage }}%;"></td>
{% endif %}
{% endif %}
</tr>
</tbody>
</table>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<pre class="diff">{{ diff.stats }}
{{ diff.output|safe }}</pre>
{{ macros::diff_view(repo, diff, query) }}
{% endblock %}
@@ -15,35 +15,17 @@
path: web::Path<String>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
let name = path.into_inner();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let branch_names = match repo.branch_names() {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
) -> Result<HttpResponse, Error> {
let repo = data.get_repo(&path)?;
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let readme_html = repo.readme().map(|raw| markdown::render(&raw));
let rendered = AboutPage {
render_html(&AboutPage {
repo,
current_ref,
branch_names,
readme_html,
query,
}
.render();
match rendered {
Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)),
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
})
}
@@ -20,53 +20,21 @@
path: web::Path<String>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
let name = path.into_inner();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
) -> Result<HttpResponse, Error> {
let repo = data.get_repo(&path)?;
let gix_repo = repo.gix();
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let branch_names = match repo.branch_names() {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let commit: Commit = if let Some(id) = query.clone().into_inner().id {
match repo.find_commit(&gix_repo, &id) {
Ok(c) => c,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
} else {
match gix_repo.find_reference(¤t_ref.name.to_string()) {
Ok(mut r) => match r.peel_to_commit() {
Ok(c) => Commit::from_gix(c).unwrap(),
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
},
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
};
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let commit = repo.resolve_commit(&gix_repo, query.id.as_deref(), ¤t_ref)?;
let diff = commit.diff(&repo, None, DiffFormat::Plain)?;
let diff: Diff = match commit.diff(&repo, None, DiffFormat::Plain) {
Ok(d) => d,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let rendered = CommitPage {
render_html(&CommitPage {
repo: &repo,
branch_names,
current_ref,
commit,
diff,
query,
}
.render();
match rendered {
Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)),
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
})
}
@@ -24,55 +24,24 @@
path: web::Path<(String, Option<String>)>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
) -> Result<HttpResponse, Error> {
let (name, file_path) = path.into_inner();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
let repo = data.get_repo(&name)?;
let gix_repo = repo.gix();
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let branch_names = match repo.branch_names() {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let commit: Commit = if let Some(id) = query.clone().into_inner().id {
match repo.find_commit(&gix_repo, &id) {
Ok(c) => c,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
} else {
match gix_repo.find_reference(&format!("heads/{}", current_ref.name)) {
Ok(mut r) => match r.peel_to_commit() {
Ok(c) => Commit::from_gix(c).unwrap(),
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
},
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
};
let diff: Diff = match commit.diff(&repo, file_path.clone(), DiffFormat::Plain) {
Ok(d) => d,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let rendered = DiffPage {
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let commit = repo.resolve_commit(&gix_repo, query.id.as_deref(), ¤t_ref)?;
let diff = commit.diff(&repo, file_path.as_deref(), DiffFormat::Plain)?;
render_html(&DiffPage {
repo: &repo,
branch_names,
current_ref,
file_path,
diff,
query,
}
.render();
match rendered {
Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)),
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
})
}
#[get("/{repo}/patch/")]
@@ -80,64 +49,37 @@
path: web::Path<String>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
let name = path.into_inner();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
) -> Result<HttpResponse, Error> {
let repo = data.get_repo(&path)?;
let gix_repo = repo.gix();
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let commit: Commit = if let Some(id) = query.clone().into_inner().id {
match repo.find_commit(&gix_repo, &id) {
Ok(c) => c,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
} else {
match gix_repo.find_reference(&format!("heads/{}", current_ref.name)) {
Ok(mut r) => match r.peel_to_commit() {
Ok(c) => Commit::from_gix(c).unwrap(),
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
},
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
};
let diff: Diff = match commit.diff(&repo, None, DiffFormat::Patch) {
Ok(d) => d,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let current_ref = Ref::resolve(&repo, &query)?;
let commit = repo.resolve_commit(&gix_repo, query.id.as_deref(), ¤t_ref)?;
let diff = commit.diff(&repo, None, DiffFormat::Patch)?;
let mut data = BytesMut::new();
writeln!(data, "From {} Mon Sep 17 00:00:00 2001", commit.id).unwrap();
writeln!(data, "From {} Mon Sep 17 00:00:00 2001", commit.id)?;
writeln!(
data,
"From: {} <{}>",
commit.author.name, commit.author.email
)
.unwrap();
)?;
write!(data, "Date: ").unwrap();
write!(data, "Date: ")?;
let mut writer = data.writer();
commit.author.time.format_rfc(&mut writer);
let mut data = writer.into_inner();
writeln!(data).unwrap();
writeln!(data, "Subject: [PATCH] {}\n", commit.summary().unwrap()).unwrap();
write!(data, "{}", commit.body().unwrap()).unwrap();
writeln!(data)?;
writeln!(data, "---").unwrap();
writeln!(data, "Subject: [PATCH] {}\n", commit.summary()?)?;
write!(data, "{}", commit.body()?)?;
writeln!(data, "---")?;
data.extend_from_slice(diff.stats.as_bytes());
data.extend_from_slice(b"\n");
data.extend_from_slice(diff.output.as_bytes());
writeln!(data, "--\ngit-rs {}", crate_version!()).unwrap();
writeln!(data, "--\ngit-rs {}", crate_version!())?;
Ok(HttpResponse::Ok().content_type("text").body(data))
}
@@ -21,105 +21,37 @@
path: web::Path<String>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
let name = path.into_inner();
) -> Result<HttpResponse, Error> {
let query = query.into_inner();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
let repo = data.get_repo(&path)?;
let gix_repo = repo.gix();
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let branch_names = match repo.branch_names() {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let offset = query.offset.unwrap_or(0);
let has_prev = offset >= 1;
let (mut commits, mut has_next): (Vec<Commit<'_>>, bool) = (Vec::new(), false);
if let Some(ref qt) = query.query_type {
match qt.as_str() {
"msg" => {
if let Some(ref v) = query.value {
(commits, has_next) = match repo.commits(
&gix_repo,
¤t_ref,
offset,
PAGE_SIZE,
Some(&|c| {
c.summary()
.unwrap()
.to_string()
.to_lowercase()
.contains(&v.to_lowercase())
}),
) {
Ok(c) => c,
Err(e) => {
return Ok(HttpResponse::InternalServerError().body(e.to_string()));
}
};
}
}
"author" => {
if let Some(ref v) = query.value {
(commits, has_next) = match repo.commits(
&gix_repo,
¤t_ref,
offset,
PAGE_SIZE,
Some(&|c| c.author.name.to_lowercase().contains(&v.to_lowercase())),
) {
Ok(c) => c,
Err(e) => {
return Ok(HttpResponse::InternalServerError().body(e.to_string()));
}
};
}
let value_lower = query.value.as_deref().unwrap_or_default().to_lowercase();
let filter: Option<&dyn Fn(&Commit) -> bool> =
match (query.query_type.as_deref(), query.value.is_some()) {
(Some("msg"), true) => Some(&|c| {
c.summary()
.map(|s| s.to_string().to_lowercase().contains(&value_lower))
.unwrap_or(false)
}),
(Some("author"), true) => {
Some(&|c| c.author.name.to_lowercase().contains(&value_lower))
}
"committer" => {
if let Some(ref v) = query.value {
(commits, has_next) = match repo.commits(
&gix_repo,
¤t_ref,
offset,
PAGE_SIZE,
Some(&|c| c.committer.name.to_lowercase().contains(&v.to_lowercase())),
) {
Ok(c) => c,
Err(e) => {
return Ok(HttpResponse::InternalServerError().body(e.to_string()));
}
};
}
(Some("committer"), true) => {
Some(&|c| c.committer.name.to_lowercase().contains(&value_lower))
}
_ => {
(commits, has_next) =
match repo.commits(&gix_repo, ¤t_ref, offset, PAGE_SIZE, None) {
Ok(c) => c,
Err(e) => {
return Ok(HttpResponse::InternalServerError().body(e.to_string()));
}
}
}
};
} else {
(commits, has_next) = match repo.commits(&gix_repo, ¤t_ref, offset, PAGE_SIZE, None) {
Ok(c) => c,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
_ => None,
};
}
let (commits, has_next) = repo.commits(&gix_repo, ¤t_ref, offset, PAGE_SIZE, filter)?;
let rendered = LogPage {
render_html(&LogPage {
repo: &repo,
branch_names,
current_ref,
@@ -128,10 +60,5 @@
has_prev,
has_next,
query,
}
.render();
match rendered {
Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)),
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
})
}
@@ -25,147 +25,42 @@
path: web::Path<(String, String)>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
) -> Result<HttpResponse, Error> {
let (name, mode) = path.into_inner();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
let repo = data.get_repo(&name)?;
let gix_repo = repo.gix();
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let branch_names = match repo.branch_names() {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let offset = query.offset.unwrap_or(0);
let has_prev = offset >= 1;
let rendered = match mode.as_ref() {
let (branches, branches_has_more, tags, tags_has_more, has_prev) = match mode.as_str() {
"heads" => {
let (branches, branches_has_more) = match repo.branches(&gix_repo, offset, PAGE_SIZE) {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
RefsPage {
repo: &repo,
current_ref,
offset,
mode,
branch_names,
branches,
tags: Vec::new(),
has_prev,
branches_has_more,
tags_has_more: false,
query,
}
.render()
let (branches, has_more) = repo.branches(&gix_repo, offset, PAGE_SIZE)?;
(branches, has_more, Vec::new(), false, offset >= 1)
}
"tags" => {
let (tags, tags_has_more) = match repo.tags(offset, PAGE_SIZE) {
Ok(t) => t,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
RefsPage {
repo: &repo,
current_ref,
offset,
mode,
branch_names,
branches: Vec::new(),
tags,
has_prev,
branches_has_more: false,
tags_has_more,
query,
}
.render()
let (tags, has_more) = repo.tags(offset, PAGE_SIZE)?;
(Vec::new(), false, tags, has_more, offset >= 1)
}
&_ => {
let (branches, branches_has_more) = match repo.branches(&gix_repo, 0, PAGE_SIZE / 2) {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let (tags, tags_has_more) = match repo.tags(0, PAGE_SIZE / 2) {
Ok(t) => t,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
RefsPage {
repo: &repo,
current_ref,
offset,
mode,
branch_names,
branches,
tags,
has_prev: false,
branches_has_more,
tags_has_more,
query,
}
.render()
_ => {
let (branches, branches_has_more) = repo.branches(&gix_repo, 0, PAGE_SIZE / 2)?;
let (tags, tags_has_more) = repo.tags(0, PAGE_SIZE / 2)?;
(branches, branches_has_more, tags, tags_has_more, false)
}
};
match rendered {
Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)),
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
}
// #[get("/{repo}/archive/{tag}.tar.gz")]
// pub async fn archive_tar_gz(
// path: web::Path<(String, String)>,
// data: web::Data<App>,
// ) -> ActixResult<HttpResponse> {
// let (name, tag) = path.into_inner();
// let repo = match data.find_repo(name) {
// Some(r) => r,
// None => return Ok(HttpResponse::NotFound().body("Repo not found")),
// };
//
// match repo.archive_tar_gz(&tag) {
// Ok(bytes) => Ok(HttpResponse::Ok()
// .content_type("application/gzip")
// .append_header((
// "Content-Disposition",
// format!("attachment; filename=\"{}-{}.tar.gz\"", repo.name, tag),
// ))
// .body(bytes)),
// // Most failures here are "no such tag" rather than a real server
// // fault — 404 reads truer than 500 for a download endpoint.
// Err(e) => Ok(HttpResponse::NotFound().body(e.to_string())),
// }
// }
//
// #[get("/{repo}/archive/{tag}.zip")]
// pub async fn archive_zip(
// path: web::Path<(String, String)>,
// data: web::Data<App>,
// ) -> ActixResult<HttpResponse> {
// let (name, tag) = path.into_inner();
// let repo = match data.find_repo(&name) {
// Some(r) => r,
// None => return Ok(HttpResponse::NotFound().body("Repo not found")),
// };
//
// match repo.archive_zip(&tag) {
// Ok(bytes) => Ok(HttpResponse::Ok()
// .content_type("application/zip")
// .append_header((
// "Content-Disposition",
// format!("attachment; filename=\"{}-{}.zip\"", repo.name, tag),
// ))
// .body(bytes)),
// Err(e) => Ok(HttpResponse::NotFound().body(e.to_string())),
// }
// }
render_html(&RefsPage {
repo: &repo,
current_ref,
offset,
mode,
branch_names,
branches,
tags,
has_prev,
branches_has_more,
tags_has_more,
query,
})
}
@@ -5,23 +5,11 @@
path: web::Path<String>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
let name = path.into_inner();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
) -> Result<HttpResponse, Error> {
let repo = data.get_repo(&path)?;
let current_ref = Ref::resolve(&repo, &query)?;
let (bytes, filename) = repo.archive(¤t_ref, &query.id)?;
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let (bytes, filename) = match repo.archive(¤t_ref, &query.id) {
Ok(result) => (result.0, result.1),
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
Ok(HttpResponse::Ok()
.content_type("application/gzip")
.append_header((
@@ -30,51 +18,3 @@
))
.body(bytes))
}
// #[get("/{repo}/archive/{tag}.tar.gz")]
// pub async fn archive_tar_gz(
// path: web::Path<(String, String)>,
// data: web::Data<App>,
// ) -> ActixResult<HttpResponse> {
// let (name, tag) = path.into_inner();
// let repo = match data.find_repo(name) {
// Some(r) => r,
// None => return Ok(HttpResponse::NotFound().body("Repo not found")),
// };
//
// match repo.archive_tar_gz(&tag) {
// Ok(bytes) => Ok(HttpResponse::Ok()
// .content_type("application/gzip")
// .append_header((
// "Content-Disposition",
// format!("attachment; filename=\"{}-{}.tar.gz\"", repo.name, tag),
// ))
// .body(bytes)),
// // Most failures here are "no such tag" rather than a real server
// // fault — 404 reads truer than 500 for a download endpoint.
// Err(e) => Ok(HttpResponse::NotFound().body(e.to_string())),
// }
// }
//
// #[get("/{repo}/archive/{tag}.zip")]
// pub async fn archive_zip(
// path: web::Path<(String, String)>,
// data: web::Data<App>,
// ) -> ActixResult<HttpResponse> {
// let (name, tag) = path.into_inner();
// let repo = match data.find_repo(&name) {
// Some(r) => r,
// None => return Ok(HttpResponse::NotFound().body("Repo not found")),
// };
//
// match repo.archive_zip(&tag) {
// Ok(bytes) => Ok(HttpResponse::Ok()
// .content_type("application/zip")
// .append_header((
// "Content-Disposition",
// format!("attachment; filename=\"{}-{}.zip\"", repo.name, tag),
// ))
// .body(bytes)),
// Err(e) => Ok(HttpResponse::NotFound().body(e.to_string())),
// }
// }
@@ -26,40 +26,18 @@
path: web::Path<String>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
let name = path.into_inner();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
) -> Result<HttpResponse, Error> {
let repo = data.get_repo(&path)?;
let gix_repo = repo.gix();
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let branch_names = match repo.branch_names() {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let (branches, branches_has_more) = match repo.branches(&gix_repo, 0, SUMMARY_LIMIT) {
Ok(c) => c,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let (tags, tags_has_more) = match repo.tags(0, SUMMARY_LIMIT) {
Ok(t) => t,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let (branches, branches_has_more) = repo.branches(&gix_repo, 0, SUMMARY_LIMIT)?;
let (tags, tags_has_more) = repo.tags(0, SUMMARY_LIMIT)?;
let (commits, commits_has_more) =
match repo.commits(&gix_repo, ¤t_ref, 0, SUMMARY_LIMIT, None) {
Ok(c) => c,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
repo.commits(&gix_repo, ¤t_ref, 0, SUMMARY_LIMIT, None)?;
let rendered = SummaryPage {
render_html(&SummaryPage {
repo: &repo,
current_ref,
offset: 0,
@@ -71,11 +49,5 @@
commits,
commits_has_more,
query,
}
.render();
match rendered {
Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)),
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
})
}
@@ -15,44 +15,24 @@
path: web::Path<String>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
let name = path.into_inner();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
) -> Result<HttpResponse, Error> {
let repo = data.get_repo(&path)?;
let gix_repo = repo.gix();
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let branch_names = match repo.branch_names() {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let tag: Tag = if let Some(head) = query.clone().into_inner().head {
match repo.find_tag(&head) {
Ok(c) => c,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let tag = if let Some(ref head) = query.head {
repo.find_tag(head)?
} else {
match gix_repo.find_reference(&format!("heads/{}", current_ref.name)) {
Ok(r) => Tag::from_gix(r).unwrap(),
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
let reference = gix_repo.find_reference(&format!("heads/{}", current_ref.name))?;
Tag::from_gix(reference)?
};
let rendered = TagPage {
render_html(&TagPage {
repo: &repo,
branch_names,
current_ref,
tag,
query,
}
.render();
match rendered {
Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)),
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
})
}
@@ -23,32 +23,16 @@
path: web::Path<(String, String)>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
) -> Result<HttpResponse, Error> {
let (name, filepath) = path.into_inner();
let filepath = filepath.trim_matches('/').to_string(); // fixes the double-slash bug from before
let filepath = filepath.trim_matches('/').to_string();
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
let repo = data.get_repo(&name)?;
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let kind = repo.resolve_path(¤t_ref, &filepath)?;
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let branch_names = match repo.branch_names() {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
// was `&ref_name` (undefined) — should reference the resolved ref
let kind = match repo.resolve_path(¤t_ref, &filepath) {
Ok(k) => k,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let rendered = TreePage {
render_html(&TreePage {
repo,
branch_names,
current_ref,
@@ -57,13 +41,7 @@
filepath,
kind,
query,
}
.render();
match rendered {
Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)),
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
})
}
#[get("/{repo}/raw/{path:.*}")]
@@ -71,49 +49,15 @@
info: web::Path<(String, String)>,
query: web::Query<PageQuery>,
data: web::Data<App>,
) -> ActixResult<HttpResponse> {
) -> Result<HttpResponse, Error> {
let (name, path) = info.into_inner();
let path = path.trim_matches('/');
let repo = match data.find_repo(name) {
Some(r) => r,
None => return Ok(HttpResponse::NotFound().body("Repo not found")),
};
let gix_repo = repo.gix();
let current_ref = match Ref::resolve(&repo, &query) {
Ok(r) => r,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
match repo.resolve_path(¤t_ref, path) {
Ok(PathView::Blob(blob)) => {
// Re-read content rather than store it on Blob — keeps Blob
// light for the tree-view case, which only needs metadata + lines.
let object_id = match gix::ObjectId::from_hex(blob.id.as_bytes()) {
Ok(id) => id,
Err(e) => {
return Ok(
HttpResponse::InternalServerError().body(format!("invalid object id: {e}"))
);
}
};
let object = match gix_repo.find_object(object_id) {
Ok(o) => o,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
let blob_obj = match object.try_into_blob() {
Ok(b) => b,
Err(e) => return Ok(HttpResponse::InternalServerError().body(e.to_string())),
};
Ok(HttpResponse::Ok()
.content_type("text/plain; charset=utf-8")
.body(blob_obj.data.clone()))
}
Ok(PathView::Tree(_)) => Ok(HttpResponse::BadRequest().body("path is a directory")),
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
let repo = data.get_repo(&name)?;
let current_ref = Ref::resolve(&repo, &query)?;
match repo.read_raw_blob(¤t_ref, &path)? {
Some(bytes) => Ok(HttpResponse::Ok()
.content_type("text/plain; charset=utf-8")
.body(bytes)),
None => Ok(HttpResponse::BadRequest().body("path is a directory")),
}
}