GITv

Download any tag's source as a .tar.gz

Browse files

Each tag on the tags page links to an archive of its files, and /<owner>/<name>/archive?ref= serves any revision. git archive runs on the resolved commit id, so a revision always gives the same files and times, and streams through the download slots under the repository's access rules. The response waits for the gzip header, so a git that fails at once is an error rather than a cut-off download. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 23:34
Commit
4d496f48e007
Parent
217c970

10 files changed +135−6

@@ -14,6 +14,6 @@ Deferred until a second person pushes to the server: individual accounts and rep
- [x] **File history and line links.** A file's page links to the commits that changed it (`log` limited to that path, paged like branch history). Source lines carry `#L<n>` anchors, and a "Permalink" link pins the current file to its commit id, so a copied link opens the same lines after the branch moves. A range (`?lines=10-20`) is highlighted by the server, with no JavaScript.
- [x] **Compare revisions.** `/<owner>/<name>/compare?from=<rev>&to=<rev>` shows the commits in `from..to`, the changed files, and the diff against the merge base. It reuses the commit page's diff rendering, output caps and cache. Cover a release-to-release comparison and a feature branch that has diverged from its target, and the access rules for private repositories.
- [x] **Description, default branch and index filter.** Over SSH (and as root): `description <name> <text>` writes git's `description` file, and `default-branch <name> <branch>` points `HEAD` at an existing branch. The index shows descriptions and can be filtered by name with a plain GET form (`?q=`). The repository header shows its visibility to the signed-in operator.
- [ ] **Tagged source archives.** The tags page links a `.tar.gz` of each tag, made by `git archive` and served through the download pool, under the repository's access rules. Tag annotations remain the release notes. Verify with a tagged GITv release that the archive matches `git archive` run locally.
- [x] **Tagged source archives.** The tags page links a `.tar.gz` of each tag, made by `git archive` and served through the download pool, under the repository's access rules. Tag annotations remain the release notes. Verify with a tagged GITv release that the archive matches `git archive` run locally.
- [ ] **Single-repository restore from backup.** Document restoring one repository from a retained snapshot after its trash entry was purged, and test it in `tests/backup.rs`: branches, tags, default branch and visibility come back, it can be restored under a new name, and a repository that has since taken the name is never overwritten.
- [ ] **Optional: protect a repository from history rewrites.** `protect <name> on|off` sets `receive.denyNonFastForwards` and `receive.denyDeletes` for that repository. Verify that force-pushes and branch deletion are refused while ordinary pushes still work, and that the operator's push log and reflogs are unaffected.
+4−2
@@ -3,12 +3,14 @@
Git hosting with SSH pushes, public and private repository browsing, and read-only HTTPS cloning for public repositories.
- `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `delete`, `add-key`, `keys`, `remove-key`, `trash`, `restore`, `purge`)
- `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, compare, tags), with Markdown rendering and syntax highlighting (`crates/gitv-web/src/render.rs`)
- `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, compare, tags, archive), with Markdown rendering and syntax highlighting (`crates/gitv-web/src/render.rs`)
**Linking to code.** A file's History lists the commits that changed it, and a folder's History does the same for everything inside. Permalink opens the file at the commit you're looking at, so the link keeps showing the same content after the branch moves. Click a line number to link that line (`#L12`). To link a range, add `lines=` to the address, for example `…&lines=12-20#L12`; the server marks those lines, and Permalink keeps the range.
**Comparing revisions.** `/<owner>/<name>/compare?from=v0.1.0&to=main` lists the commits `to` has that `from` lacks and the changes they make. A branch that has diverged is compared from where the two split, so the other branch's newer work isn't shown as undone. Any branch, tag or commit id works on either side, `to` defaults to the default branch, and the address can be shared. Each tag links to the changes since the previous tag in its history, and a branch's commit list links to its comparison with the default branch.
**Source archives.** Each tag on the tags page has a Source (.tar.gz) download, made by `git archive` from the tagged commit as it's requested, with every file under a `<repository>-<tag>/` folder. `/<owner>/<name>/archive?ref=<branch, tag or commit>` works for any revision. The same revision always gives the same files and times. Downloads follow the repository's visibility, and share the raw-download limits below. Tag annotations serve as release notes; there are no uploaded release assets.
**Who can read what.** Over SSH each key reaches only its owner's repositories. The web browser has one account, and whoever signs in to it can read every repository on the server. It binds to localhost only; put it behind an HTTPS reverse proxy.
Existing and newly created repositories default to private. Publish one as its SSH owner or as the server administrator:
@@ -33,7 +35,7 @@ gitv default-branch um9i my-project release
The description lives in git's own `description` file in the repository. Signed in, the repository header also shows whether it's public, and for a public repository both its HTTPS and SSH addresses.
**Limits.** The web server runs at most 16 page renders, 6 raw downloads and 4 HTTPS clones at once. Some render and download slots are kept for signed-in sessions, so anonymous visitors can't crowd out the owner. Each anonymous client (an IPv4 address or IPv6 /64, as Caddy reports it) may hold at most 4 renders, 2 downloads and 2 clones at a time. Past these limits a request gets 503 at once rather than queueing.
**Limits.** The web server runs at most 16 page renders, 6 raw or archive downloads and 4 HTTPS clones at once. Some render and download slots are kept for signed-in sessions, so anonymous visitors can't crowd out the owner. Each anonymous client (an IPv4 address or IPv6 /64, as Caddy reports it) may hold at most 4 renders, 2 downloads and 2 clones at a time. Past these limits a request gets 503 at once rather than queueing.
**Storage.** Repositories live in `/srv/gitv/repos/<owner>/<name>.git`. Owner and repository directories must be real directories: GITv refuses symlinks at either level rather than follow them out of the tree. Everything works through open directory handles: git runs inside the repository directory it opened, new repositories are built and published inside the open owner directory (never replacing anything already at the name), deletion and purging move and remove through handles without following links, and the web index lists and fingerprints repositories the same way. A path swapped for a symlink after a check can't redirect any of it.
@@ -171,7 +171,7 @@ a.entry:hover .name{color:var(--accent)}
.tag-row .tname{font:700 19px/1.25 var(--f-display);letter-spacing:-.01em;color:var(--ink);overflow-wrap:anywhere}
.tag-row .tnote,.tag-row .tmeta{grid-column:1;font-size:14px;color:var(--ink-2);overflow-wrap:anywhere}
.tag-row .tmeta{font-size:13px;display:flex;align-items:center;gap:6px 12px;flex-wrap:wrap}
.tag-row .tacts{grid-row:1 / span 3;grid-column:2;display:flex;gap:8px}
.tag-row .tacts{grid-row:1 / span 3;grid-column:2;display:flex;flex-wrap:wrap;justify-content:flex-end;gap:8px}
/* Buttons */
.button{display:inline-flex;align-items:center;gap:6px;min-height:34px;padding:0 12px;font:500 14px var(--f-text);
@@ -302,7 +302,7 @@ button.button{cursor:pointer}
.markdown{padding:4px 18px 18px}
.cmsg{padding:18px}.facts{padding:14px 18px;gap:12px 24px}
.tag-row{grid-template-columns:minmax(0,1fr)}
.tag-row .tacts{grid-row:auto;grid-column:1}
.tag-row .tacts{grid-row:auto;grid-column:1;justify-content:flex-start}
.panel-head .who{display:none}
}
@media (prefers-reduced-motion:no-preference){
@@ -101,6 +101,8 @@ enum View {
Html(String),
/// Pinned cat-file command, expected size and original download name.
Raw(Box<std::process::Command>, usize, Vec<u8>),
/// Pinned `git archive` command, and the download's file name.
Archive(Box<std::process::Command>, String),
Busy,
Redirect(String),
Missing(bool),
@@ -134,6 +136,7 @@ impl View {
View::LoginRequired => StatusCode::UNAUTHORIZED.into_response(),
View::Html(body) => html(StatusCode::OK, body),
View::Raw(cmd, size, name) => raw_response(visitor, *cmd, size, name).await,
View::Archive(cmd, name) => archive_response(visitor, *cmd, name).await,
View::Busy => StatusCode::SERVICE_UNAVAILABLE.into_response(),
View::Redirect(to) => Redirect::to(&to).into_response(),
View::Missing(signed_in) => missing(signed_in),
@@ -200,6 +203,30 @@ async fn raw_response(visitor: Visitor, command: std::process::Command, size: us
response
}
/// A source archive, streamed from `git archive` as it's made, in a download slot. Its size
/// isn't known until it's done, so it goes out chunked.
async fn archive_response(visitor: Visitor, command: std::process::Command, name: String) -> Response {
let Some(permit) = DOWNLOADS.try_acquire(visitor) else {
return StatusCode::SERVICE_UNAVAILABLE.into_response();
};
let Ok(mut output) = git_stream::Output::start(command.into()) else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
// Every gzip stream starts with a 10-byte header. Waiting for it means a git that fails at
// once (an unreadable object, say) is an error response, not a cut-off download.
let Ok(prefix) = output.prefix(10).await else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let body = output.body(prefix, None, permit, std::time::Duration::from_secs(300));
let disposition = format!("attachment; filename=\"{name}\"");
(
RAW_SECURITY,
[(header::CONTENT_TYPE, "application/gzip"), (header::CONTENT_DISPOSITION, disposition.as_str())],
body,
)
.into_response()
}
/// Git calls block, so every page renders on the blocking pool. The permit moves into the
/// blocking work itself: if the request is cancelled while rendering, the slot stays taken
/// until the work actually ends.
@@ -132,6 +132,8 @@ pub(crate) struct TagRow<'a> {
pub sha_link: String,
pub when: String,
pub browse: String,
/// The tagged files as a `.tar.gz`.
pub archive: String,
/// A comparison with the previous tag, and its label.
pub compare: Option<(String, String)>,
}
@@ -0,0 +1,48 @@
//! A revision's files as a `.tar.gz`, made by `git archive`.
use super::Repo;
use crate::View;
use crate::urls::Q;
pub(crate) fn view_archive(repo: &Repo, q: &Q) -> Option<View> {
let reference = q.get("ref")?;
let commit = repo.reader.resolve(reference)?;
let base = format!("{}-{}", repo.name, archive_label(reference, &commit));
let prefix = format!("--prefix={base}/");
let mut command = gitv_core::git_command(&repo.reader.dir);
// The commit id, not the name: what's archived is exactly what was resolved, and the
// archive's file times are that commit's time, so the same revision always gives the
// same bytes.
command.args(["archive", "--format=tar.gz", &prefix, &commit, "--"]);
Some(View::Archive(Box::new(command), format!("{base}.tar.gz")))
}
/// The revision's part of the archive's name: a branch or tag name with `refs/…` dropped, or a
/// short id for a commit id. Only letters, digits and `.`, `_`, `+`, `-` are kept, so the name
/// is safe as a file name and inside a quoted header.
pub(crate) fn archive_label(reference: &[u8], commit: &str) -> String {
let name =
reference.strip_prefix(b"refs/tags/").or_else(|| reference.strip_prefix(b"refs/heads/")).unwrap_or(reference);
if name.eq_ignore_ascii_case(commit.as_bytes()) {
return commit[..12].to_string();
}
let label: String =
name.iter().map(|&b| if b.is_ascii_alphanumeric() || b"._+-".contains(&b) { b as char } else { '-' }).collect();
let label = label.trim_matches(['-', '.']);
if label.is_empty() { commit[..12].to_string() } else { label.to_string() }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn archive_names_are_plain_file_names() {
let id = "0123456789abcdef0123456789abcdef01234567";
assert_eq!(archive_label(b"refs/tags/v1.2.0", id), "v1.2.0");
assert_eq!(archive_label(b"release/2.0", id), "release-2.0");
assert_eq!(archive_label(b"caf\xc3\xa9 \"quoted\"", id), "caf----quoted");
assert_eq!(archive_label(b"..", id), "0123456789ab");
assert_eq!(archive_label(id.to_uppercase().as_bytes(), id), "0123456789ab");
}
}
@@ -1,5 +1,6 @@
//! The repository pages. Each view reads one open repository and returns a [`View`].
mod archive;
mod blob;
mod commit;
mod compare;
@@ -20,6 +21,7 @@ use crate::html::{ago, icon, subject_or_placeholder};
use crate::repository::Reader;
use crate::urls::{Q, encode, lossy};
use crate::{View, templates};
use archive::view_archive;
use blob::view_blob;
use commit::view_commit;
use compare::view_compare;
@@ -267,6 +269,7 @@ pub(crate) fn route(owner: &str, name: &str, view: Option<&str>, q: &Q, signed_i
Some("tree") => view_tree(&repo, q),
Some("blob") => view_blob(&repo, q, false),
Some("raw") => view_blob(&repo, q, true),
Some("archive") => view_archive(&repo, q),
Some("log") => view_log(&repo, q),
Some("commit") => view_commit(&repo, q),
Some("compare") => view_compare(&repo, q),
@@ -35,6 +35,7 @@ pub(crate) fn view_tags(repo: &Repo) -> Option<View> {
sha_link: repo.sha_link(&lossy(target)),
when: ago(&lossy(stamp), &lossy(date)),
browse: repo.url_at("tree", &repo.reader.tag_ref(name), b"", ""),
archive: repo.url_at("archive", &repo.reader.tag_ref(name), b"", ""),
compare: None,
});
}
@@ -3,5 +3,5 @@
{{ masthead|safe }}
{% if rows.is_empty() %}<div class="panel empty"><h2>No tags yet</h2><p>Tag a release and push it to see it here.</p><code>git tag -a v1.0.0 -m "v1.0.0" &amp;&amp; git push origin v1.0.0</code></div>
{% else %}<div class="panel"><ul class="rows">{% for row in rows %}<li class="tag-row"><span class="tname">{{ row.name }}</span>{% if let Some(note) = row.note %}<span class="tnote">{{ note }}</span>{% endif %}<span class="tmeta">{{ row.sha_link|safe }}{{ row.when }}</span>
<span class="tacts">{% if let Some((url, label)) = row.compare %}<a class="button" href="{{ url }}">{{ label }}</a>{% endif %}<a class="button" href="{{ row.browse }}">Browse files</a></span></li>{% endfor %}</ul></div>{% endif %}
<span class="tacts">{% if let Some((url, label)) = row.compare %}<a class="button" href="{{ url }}">{{ label }}</a>{% endif %}<a class="button" href="{{ row.archive }}" download>Source (.tar.gz)</a><a class="button" href="{{ row.browse }}">Browse files</a></span></li>{% endfor %}</ul></div>{% endif %}
{% endblock %}
@@ -1160,3 +1160,49 @@ fn the_header_shows_the_description_visibility_and_clone_addresses() {
// No description: no empty paragraph.
assert!(!s.get("/ada/twin/tree").text().contains("repodesc"));
}
/// A gzip stream, decompressed by the system's gzip.
fn gunzip(data: &[u8]) -> Vec<u8> {
use std::io::Write as _;
let mut child = std::process::Command::new("gzip")
.arg("-dc")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
child.stdin.take().unwrap().write_all(data).unwrap();
let out = child.wait_with_output().unwrap();
assert!(out.status.success(), "not a gzip stream");
out.stdout
}
#[test]
fn tags_download_as_source_archives() {
let s = server();
let f = fixture();
let tags = s.get("/ada/site/tags").text();
assert!(tags.contains("href=\"/ada/site/archive?ref=v0.1.0\" download>Source (.tar.gz)"), "{tags}");
let download = s.get("/ada/site/archive?ref=refs/tags/v0.1.0");
assert_eq!(download.status, 200);
assert_eq!(download.header("content-type"), "application/gzip");
assert_eq!(download.header("content-disposition"), "attachment; filename=\"site-v0.1.0.tar.gz\"");
assert!(download.header("content-security-policy").starts_with("sandbox"));
// The same files, times and layout as git archive gives for the tag.
let repo = f.repos.join("ada/site.git");
let local =
common::git_cmd(&repo).args(["archive", "--format=tar", "--prefix=site-v0.1.0/", "v0.1.0"]).output().unwrap();
assert!(local.status.success());
let tar = gunzip(&download.body);
assert!(tar == local.stdout, "the archive differs from git archive's");
assert!(tar.windows(25).any(|w| w == b"site-v0.1.0/src/main.rs\0\0"), "files sit under the prefix");
// A commit id names the file by a short id; a revision that doesn't exist isn't served.
let by_id = s.get(&format!("/ada/site/archive?ref={}", f.first));
assert_eq!(by_id.header("content-disposition"), format!("attachment; filename=\"site-{}.tar.gz\"", &f.first[..12]));
assert_eq!(gunzip(&by_id.body).len(), tar.len());
assert_eq!(s.get("/ada/site/archive?ref=nope").status, 404);
assert_eq!(s.get("/ada/site/archive").status, 404);
// A private repository's archive needs sign-in.
assert_eq!(s.get_signed_out("/ada/site/archive?ref=refs/tags/v0.1.0").status, 303);
}