Set a repository's description and default branch, and filter the index
Browse files`description <name> <text>` and `default-branch <name> <branch>`, over SSH or as root, show or change git's own description file and HEAD. The description is replaced by rename through the repository's directory handle; the default branch must already exist and is always read as refs/heads/<name>, so names like -x or HEAD can't mean anything else. The index shows descriptions and takes a plain GET filter matching every word against owner/name and the description, applied before any git runs. The repository header shows the description, and when signed in the visibility and, for a public repository, the SSH address as well as HTTPS, since the operator pushes over SSH. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 23:31
- Commit
- 217c970b8527
- Parent
- 7f0fe6d
14 files changed +336−23
+1−1
| @@ -63,7 +63,7 @@ Three crates. `gitv` depends only on `gitv-core` and a few small crates, so buil | ||
| - Git allows any bytes but `/` and NUL in names. Query values decode to `Vec<u8>` (`urls::parse_query`), are checked with `clean_path`, and reach git as `OsStr`. | ||
| - Only display uses `lossy()`. | ||
| - Plain names that could be misread (40/64-hex, `refs/…`, `HEAD`) are linked as qualified refs (`Reader::branch_ref`/`tag_ref`). `Reader::resolve` looks ids up as objects only. | ||
| - **Visibility** is a `gitv-public` marker file in the repository directory. For a signed-out visitor, a private repository and a missing one give the same answer (`View::LoginRequired`), so existence never leaks. Smart HTTP serves public repositories only, read-only. | ||
| - **Visibility** is a `gitv-public` marker file in the repository directory. For a signed-out visitor, a private repository and a missing one give the same answer (`View::LoginRequired`), so existence never leaks. Smart HTTP serves public repositories only, read-only. The description is git's `description` file, read and replaced through the directory handle (`RepoDir::description`/`set_description`); git's `Unnamed repository` placeholder counts as none. | ||
| - **No scripts, anywhere.** | ||
| - Every HTML response sends `SECURITY` (CSP `default-src 'none'`, no `script-src`). | ||
| - Raw files get `RAW_SECURITY`, which adds `sandbox`. | ||
+1−1
| @@ -13,7 +13,7 @@ Deferred until a second person pushes to the server: individual accounts and rep | ||
| - [x] **SSH key list and revoke.** `gitv keys [owner]` lists every active key with its owner, SHA-256 fingerprint (as `ssh-keygen -l` prints it) and label. `gitv add-key --label <text>` records a label for a new key. `gitv remove-key <fingerprint>` removes exactly that key, atomically and under the same lock as `add-key`. Verify that a revoked key no longer reaches anything, that a second key for the same owner still works, that an unknown fingerprint changes nothing, and that hand-written lines (options, comments, tabs) survive a removal. | ||
| - [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. | ||
| - [ ] **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. | ||
| - [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. | ||
| - [ ] **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. | ||
+12−0
| @@ -21,6 +21,18 @@ gitv visibility um9i my-project public | ||
| Anyone can now find it on the repository index, browse its files and history, and run `git clone https://git.um9i.dev/um9i/my-project`. Use the same visibility command with `private` to require sign-in again and disable HTTPS fetches. Copies already downloaded remain with their recipients. Pushes use SSH. | ||
| **Description and default branch.** A one-line description shows under the repository's name and on the index, where it can be searched along with names. The default branch is the one the web shows first and that clones check out. Without a value, each command prints the current one: | ||
| ```sh | ||
| ssh git@git.um9i.dev description my-project A small toolbox # "" removes it | ||
| ssh git@git.um9i.dev default-branch my-project release # must be an existing branch | ||
| # Equivalent commands on the server | ||
| gitv description um9i my-project "A small toolbox" | ||
| 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. | ||
| **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. | ||
| @@ -76,6 +76,11 @@ pub fn configure(command: &mut Command) { | ||
| /// An open repository directory. Holding the directory itself, not its path, means a symlink | ||
| /// swapped in after the checks can't redirect anything: git runs inside this exact directory. | ||
| /// Git's file for a repository's one-line description, in the repository directory. | ||
| const DESCRIPTION: &str = "description"; | ||
| /// The longest description, in characters. | ||
| pub const DESCRIPTION_LIMIT: usize = 160; | ||
| pub struct RepoDir { | ||
| /// Where it was found, for messages and cache keys only; never reopened. | ||
| pub path: PathBuf, | ||
| @@ -126,6 +131,54 @@ impl RepoDir { | ||
| } | ||
| /// The open directory, for reading it by handle. | ||
| /// The repository's one-line description from git's `description` file, or `None` when | ||
| /// there's none or it still holds the placeholder `git init` writes. | ||
| pub fn description(&self) -> Option<String> { | ||
| // Non-blocking, so a FIFO planted at the name can't hang the reader; then only a | ||
| // regular file is read, and only its first kilobyte. | ||
| let flags = OFlag::O_RDONLY | OFlag::O_NOFOLLOW | OFlag::O_NONBLOCK | OFlag::O_CLOEXEC; | ||
| let fd = openat(&self.fd, DESCRIPTION, flags, Mode::empty()).ok()?; | ||
| let meta = nix::sys::stat::fstat(&fd).ok()?; | ||
| if SFlag::from_bits_truncate(meta.st_mode) & SFlag::S_IFMT != SFlag::S_IFREG { | ||
| return None; | ||
| } | ||
| let mut bytes = Vec::new(); | ||
| std::fs::File::from(fd).take(DESCRIPTION_LIMIT as u64 * 4).read_to_end(&mut bytes).ok()?; | ||
| let text = String::from_utf8_lossy(&bytes); | ||
| let line = text.lines().next().unwrap_or_default().trim(); | ||
| let placeholder = line.starts_with("Unnamed repository"); | ||
| (!line.is_empty() && !placeholder).then(|| line.chars().filter(|c| !c.is_control()).collect()) | ||
| } | ||
| /// Replace the description, or remove it with `None`. The new file is written beside the old | ||
| /// one and renamed over it inside this open directory, so a reader sees one or the other. | ||
| pub fn set_description(&self, text: Option<&str>) -> nix::Result<()> { | ||
| use std::io::Write as _; | ||
| let Some(text) = text else { | ||
| return match unlinkat(&self.fd, DESCRIPTION, UnlinkatFlags::NoRemoveDir) { | ||
| Err(nix::errno::Errno::ENOENT) => Ok(()), | ||
| result => result, | ||
| }; | ||
| }; | ||
| let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); | ||
| let temporary = format!(".{DESCRIPTION}.tmp-{}-{nanos}", std::process::id()); | ||
| let flags = OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_EXCL | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC; | ||
| let fd = openat(&self.fd, temporary.as_str(), flags, Mode::from_bits_truncate(0o644))?; | ||
| let written = (|| { | ||
| // Created with the umask applied; readers (the web service) need it world-readable. | ||
| nix::sys::stat::fchmod(&fd, Mode::from_bits_truncate(0o644))?; | ||
| let mut file = std::fs::File::from(fd); | ||
| let io = |e: std::io::Error| e.raw_os_error().map_or(nix::errno::Errno::EIO, nix::errno::Errno::from_raw); | ||
| file.write_all(format!("{text}\n").as_bytes()).map_err(io)?; | ||
| file.sync_all().map_err(io)?; | ||
| nix::fcntl::renameat(&self.fd, temporary.as_str(), &self.fd, DESCRIPTION) | ||
| })(); | ||
| if written.is_err() { | ||
| let _ = unlinkat(&self.fd, temporary.as_str(), UnlinkatFlags::NoRemoveDir); | ||
| } | ||
| written | ||
| } | ||
| pub fn handle(&self) -> BorrowedFd<'_> { | ||
| self.fd.as_fd() | ||
| } | ||
| @@ -55,7 +55,12 @@ main{max-width:1080px;margin:0 auto;padding:32px 24px 72px} | ||
| .reponame a{color:var(--ink)} | ||
| .reponame .own{font-weight:400;color:var(--ink-2)} | ||
| .reponame .sep{font-weight:300;color:var(--ink-2);opacity:.5} | ||
| .clone{display:flex;align-items:stretch;flex:0 1 380px;min-width:0} | ||
| .repoid{display:grid;gap:6px;min-width:0;flex:1 1 20em} | ||
| .repoline{display:flex;align-items:center;gap:8px 12px;flex-wrap:wrap} | ||
| .vis{padding:2px 9px;font-size:12px;font-weight:600;color:var(--ink-2);border:1px solid var(--rule);border-radius:99px} | ||
| .repodesc{margin:0;max-width:64ch;color:var(--ink-2);overflow-wrap:anywhere} | ||
| .clones{display:grid;gap:8px;flex:0 1 380px;min-width:0} | ||
| .clone{display:flex;align-items:stretch;min-width:0} | ||
| .clone span{display:flex;align-items:center;padding:0 10px;font-size:12px;font-weight:600;color:var(--ink-2); | ||
| background:var(--rule-2);border:1px solid var(--rule);border-right:0;border-radius:8px 0 0 8px} | ||
| .clone input{width:100%;min-width:0;min-height:36px;padding:0 10px;font:13px var(--f-mono);color:var(--ink); | ||
| @@ -127,6 +132,13 @@ a.entry:hover .name{color:var(--accent)} | ||
| .rname{font:700 19px/1.3 var(--f-display);overflow-wrap:anywhere} | ||
| .rname span{font-weight:400;color:var(--ink-2)} | ||
| .rlast{font-size:15px;line-height:1.4;overflow-wrap:anywhere} | ||
| .rdesc{font-size:14px;line-height:1.4;color:var(--ink-2);overflow-wrap:anywhere} | ||
| .index-filter{display:flex;gap:8px;flex-wrap:wrap;margin:-8px 0 20px} | ||
| .index-filter input{flex:1 1 10em;min-width:0;min-height:38px;padding:0 12px;font:400 15px var(--f-text);color:var(--ink); | ||
| background:var(--surface);border:1px solid var(--rule);border-radius:8px} | ||
| .index-filter .button{min-height:38px} | ||
| .index-filter input:hover{border-color:var(--ink-2)} | ||
| .index-filter input:focus-visible{outline:2px solid var(--accent);outline-offset:1px;border-color:var(--accent)} | ||
| .rwhen{font-variant-numeric:tabular-nums} | ||
| .index-empty{text-align:center;padding:clamp(40px,8vw,88px) 20px} | ||
| .index-mark{display:inline-grid;place-items:center;background:var(--accent-wash);color:var(--accent);width:60px;height:60px;border-radius:16px} | ||
| @@ -139,6 +151,7 @@ a.entry:hover .name{color:var(--accent)} | ||
| .index-columns{display:none} | ||
| .index-list .repo-row{grid-template-columns:minmax(0,1fr);gap:5px;padding:16px} | ||
| .ridentity{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 12px} | ||
| .rdesc{flex-basis:100%} | ||
| .rwhen{text-align:left} | ||
| .rwhen:empty{display:none} | ||
| } | ||
| @@ -285,7 +298,7 @@ button.button{cursor:pointer} | ||
| .bar{padding:0 16px} | ||
| main{padding:20px 16px 56px} | ||
| .reponame{font-size:27px} | ||
| .clone{flex-basis:100%} | ||
| .clones{flex-basis:100%} | ||
| .markdown{padding:4px 18px 18px} | ||
| .cmsg{padding:18px}.facts{padding:14px 18px;gap:12px 24px} | ||
| .tag-row{grid-template-columns:minmax(0,1fr)} | ||
| @@ -282,8 +282,10 @@ fn serve(port: u16) -> Result<(), String> { | ||
| let browse = Router::new() | ||
| .route( | ||
| "/", | ||
| get(|Extension(user): Extension<bool>, client: Client| { | ||
| blocking(Visitor { client, signed_in: user }, move || view_index(user)) | ||
| get(|Extension(user): Extension<bool>, client: Client, RawQuery(query): RawQuery| { | ||
| blocking(Visitor { client, signed_in: user }, move || { | ||
| view_index(user, &parse_query(query.as_deref())) | ||
| }) | ||
| }), | ||
| ) | ||
| .route("/{owner}/{name}", get(repository_page)) | ||
| @@ -23,8 +23,11 @@ pub(crate) struct Masthead<'a> { | ||
| pub owner: &'a str, | ||
| pub name: &'a str, | ||
| pub home: String, | ||
| pub protocol: &'a str, | ||
| pub address: String, | ||
| /// "Public" or "Private", shown only when signed in. | ||
| pub visibility: Option<&'static str>, | ||
| pub description: Option<String>, | ||
| /// Each way to clone it: protocol and address. | ||
| pub addresses: Vec<(&'static str, String)>, | ||
| pub tabs: Vec<Tab>, | ||
| } | ||
| @@ -258,6 +261,7 @@ pub(super) struct RepositoryRow { | ||
| pub owner: String, | ||
| pub name: String, | ||
| pub public: bool, | ||
| pub description: Option<String>, | ||
| pub subject: String, | ||
| pub when: String, | ||
| } | ||
| @@ -268,6 +272,9 @@ pub(super) struct Repositories<'a> { | ||
| pub title: &'a str, | ||
| pub signed_in: bool, | ||
| pub count: String, | ||
| /// The filter as typed, and how many repositories there are to filter. | ||
| pub filter: String, | ||
| pub total: usize, | ||
| pub rows: Vec<RepositoryRow>, | ||
| pub branch: String, | ||
| pub host: &'a str, | ||
| @@ -13,6 +13,7 @@ use super::Repo; | ||
| use crate::cache::cached; | ||
| use crate::html::{ago, icon, plural, subject_or_placeholder}; | ||
| use crate::repository::Head; | ||
| use crate::urls::{Q, param}; | ||
| use crate::{View, templates}; | ||
| /// The names in an open directory, sorted, skipping hidden ones and any that aren't UTF-8 | ||
| @@ -85,11 +86,22 @@ pub(crate) struct Row { | ||
| pub(crate) public: bool, | ||
| pub(crate) owner: String, | ||
| pub(crate) name: String, | ||
| pub(crate) description: Option<String>, | ||
| pub(crate) head: Option<Head>, | ||
| } | ||
| pub(crate) fn view_index(signed_in: bool) -> View { | ||
| /// Whether a repository matches a filter: every word of it appears, ignoring case, in the | ||
| /// repository's `owner/name` or its description. | ||
| fn matches(words: &[String], owner: &str, name: &str, description: Option<&str>) -> bool { | ||
| let haystack = format!("{owner}/{name} {}", description.unwrap_or_default()).to_lowercase(); | ||
| words.iter().all(|word| haystack.contains(word.as_str())) | ||
| } | ||
| pub(crate) fn view_index(signed_in: bool, q: &Q) -> View { | ||
| let deadline = Instant::now() + gitv_core::GIT_TIMEOUT; | ||
| let filter = param(q, "q").unwrap_or_default(); | ||
| let words: Vec<String> = filter.split_whitespace().map(str::to_lowercase).collect(); | ||
| let mut total = 0; | ||
| let mut rows = Vec::new(); | ||
| let root = open_root(); | ||
| for owner in root.as_ref().map(sorted_names).unwrap_or_default() { | ||
| @@ -105,6 +117,12 @@ pub(crate) fn view_index(signed_in: bool) -> View { | ||
| if !signed_in && !public { | ||
| continue; | ||
| } | ||
| total += 1; | ||
| // Filtered before any git runs, so a narrow filter is cheap however many there are. | ||
| let description = dir.description(); | ||
| if !matches(&words, &owner, name, description.as_deref()) { | ||
| continue; | ||
| } | ||
| dir.limit_until(deadline); | ||
| let repo = Repo::from_dir(&owner, name, dir); | ||
| // HEAD usually names a real branch; only look further when it doesn't. An empty | ||
| @@ -121,11 +139,15 @@ pub(crate) fn view_index(signed_in: bool) -> View { | ||
| }; | ||
| let head = raw.as_deref().and_then(Head::parse); | ||
| // `repo`, and with it the directory handle, is dropped here. | ||
| rows.push(Row { public, owner: owner.clone(), name: name.to_string(), head }); | ||
| rows.push(Row { public, owner: owner.clone(), name: name.to_string(), description, head }); | ||
| } | ||
| } | ||
| rows.sort_by_key(|row| Reverse(row.head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0))); | ||
| let count = plural(rows.len(), "repository", "repositories"); | ||
| let count = if words.is_empty() { | ||
| plural(rows.len(), "repository", "repositories") | ||
| } else { | ||
| format!("{} of {total}", rows.len()) | ||
| }; | ||
| let rows = rows | ||
| .into_iter() | ||
| .map(|row| { | ||
| @@ -133,7 +155,14 @@ pub(crate) fn view_index(signed_in: bool) -> View { | ||
| || ("No commits yet".into(), String::new()), | ||
| |h| (subject_or_placeholder(&h.subject).into(), ago(&h.stamp, &h.date)), | ||
| ); | ||
| templates::RepositoryRow { owner: row.owner, name: row.name, public: row.public, subject, when } | ||
| templates::RepositoryRow { | ||
| owner: row.owner, | ||
| name: row.name, | ||
| public: row.public, | ||
| description: row.description, | ||
| subject, | ||
| when, | ||
| } | ||
| }) | ||
| .collect(); | ||
| View::Html( | ||
| @@ -141,6 +170,8 @@ pub(crate) fn view_index(signed_in: bool) -> View { | ||
| title: "Repositories", | ||
| signed_in, | ||
| count, | ||
| filter: filter.trim().to_string(), | ||
| total, | ||
| rows, | ||
| branch: icon("branch"), | ||
| host: config::host(), | ||
| @@ -152,6 +183,17 @@ pub(crate) fn view_index(signed_in: bool) -> View { | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn filters_match_every_word_in_the_name_or_description() { | ||
| let words = |q: &str| q.split_whitespace().map(str::to_lowercase).collect::<Vec<_>>(); | ||
| assert!(matches(&words(""), "ada", "tools", None)); | ||
| assert!(matches(&words("TOOL"), "ada", "tools", None)); | ||
| assert!(matches(&words("ada/to"), "ada", "tools", None)); | ||
| assert!(matches(&words("small box"), "ada", "tools", Some("A small toolbox"))); | ||
| assert!(!matches(&words("small crate"), "ada", "tools", Some("A small toolbox"))); | ||
| assert!(!matches(&words("bob"), "ada", "tools", None)); | ||
| } | ||
| #[test] | ||
| fn an_incomplete_fingerprint_is_never_trusted() { | ||
| if nix::unistd::geteuid().is_root() { | ||
| @@ -144,13 +144,21 @@ impl Repo { | ||
| label, | ||
| count, | ||
| }; | ||
| let (protocol, address) = self.clone_address(); | ||
| let public = self.reader.dir.is_public(); | ||
| // Anyone may clone a public repository over HTTPS; the signed-in operator also pushes | ||
| // over SSH, so sees that address too, and whether the repository is public. | ||
| let ssh = ("SSH", format!("git@{}:{}/{}.git", config::host(), self.owner, self.name)); | ||
| let addresses = match (public, self.signed_in) { | ||
| (true, true) => vec![self.clone_address(), ssh], | ||
| _ => vec![self.clone_address()], | ||
| }; | ||
| templates::Masthead { | ||
| owner: &self.owner, | ||
| name: &self.name, | ||
| home: self.url("tree", &[]), | ||
| protocol, | ||
| address, | ||
| visibility: self.signed_in.then_some(if public { "Public" } else { "Private" }), | ||
| description: self.reader.dir.description(), | ||
| addresses, | ||
| tabs: vec![ | ||
| tab("tree", "code", "Code", None), | ||
| tab("log", "commits", "Commits", Some(commits)), | ||
| @@ -1,3 +1,4 @@ | ||
| <div class="repohead"><h1 class="reponame"><a class="own" href="/">{{ owner }}</a><span class="sep">/</span><a href="{{ home }}">{{ name }}</a></h1> | ||
| <label class="clone"><span>{{ protocol }}</span><input readonly aria-label="Clone address" value="{{ address }}"></label></div> | ||
| <nav class="tabs" aria-label="Repository">{% for tab in tabs %}<a href="{{ tab.href }}"{% if tab.current %} aria-current="page"{% endif %}>{{ tab.icon|safe }}{{ tab.label }}{% if let Some(n) = tab.count %}<span class="n">{{ n }}</span>{% endif %}</a>{% endfor %}</nav> | ||
| <div class="repohead"><div class="repoid"><div class="repoline"><h1 class="reponame"><a class="own" href="/">{{ owner }}</a><span class="sep">/</span><a href="{{ home }}">{{ name }}</a></h1>{% if let Some(visibility) = visibility %}<span class="vis">{{ visibility }}</span>{% endif %}</div> | ||
| {% if let Some(description) = description %}<p class="repodesc">{{ description }}</p>{% endif %}</div> | ||
| <div class="clones">{% for (protocol, address) in addresses %}<label class="clone"><span>{{ protocol }}</span><input readonly aria-label="{{ protocol }} clone address" value="{{ address }}"></label>{% endfor %}</div></div> | ||
| <nav class="tabs" aria-label="Repository">{% for tab in tabs %}<a href="{{ tab.href }}"{% if tab.current %} aria-current="page"{% endif %}>{{ tab.icon|safe }}{{ tab.label }}{% if let Some(n) = tab.count %}<span class="n">{{ n }}</span>{% endif %}</a>{% endfor %}</nav> | ||
| @@ -1,7 +1,10 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| <header class="index-head"><h1 class="title">Repositories</h1>{% if !rows.is_empty() %}<p class="count">{{ count }}</p>{% endif %}</header> | ||
| {% if rows.is_empty() %} | ||
| <header class="index-head"><h1 class="title">Repositories</h1>{% if total > 0 %}<p class="count">{{ count }}</p>{% endif %}</header> | ||
| {% if total > 1 || !filter.is_empty() %}<form class="index-filter" method="get" action="/" role="search"><input type="search" name="q" value="{{ filter }}" placeholder="Filter by name or description" aria-label="Filter repositories" autocapitalize="none" spellcheck="false"><button class="button" type="submit">Filter</button>{% if !filter.is_empty() %}<a class="button" href="/">Clear</a>{% endif %}</form>{% endif %} | ||
| {% if rows.is_empty() && !filter.is_empty() %} | ||
| <section class="panel index-empty"><h2>No repositories match “{{ filter }}”</h2><a class="button" href="/">Show all repositories</a></section> | ||
| {% else if rows.is_empty() %} | ||
| <section class="panel index-empty"> | ||
| <div class="index-mark">{{ branch|safe }}</div> | ||
| {% if signed_in %} | ||
| @@ -20,7 +23,8 @@ | ||
| {% for row in rows %} | ||
| <li><a class="repo-row" href="/{{ row.owner }}/{{ row.name }}/tree"> | ||
| <span class="ridentity"><span class="rname"><span>{{ row.owner }}/</span>{{ row.name }}</span> | ||
| {% if signed_in %}<small>{% if row.public %}Public{% else %}Private{% endif %}</small>{% endif %}</span> | ||
| {% if signed_in %}<small>{% if row.public %}Public{% else %}Private{% endif %}</small>{% endif %} | ||
| {% if let Some(description) = row.description %}<span class="rdesc">{{ description }}</span>{% endif %}</span> | ||
| <span class="rlast">{{ row.subject }}</span> | ||
| <span class="rwhen">{{ row.when }}</span> | ||
| </a></li> | ||
| @@ -157,6 +157,7 @@ fn fixture() -> &'static Fixture { | ||
| let out = host.git(&work, &[&["push", "-q", "ada@x:ada/site.git"][..], &refs, &extra].concat()); | ||
| assert!(out.status.success(), "{}", common::stderr(&out)); | ||
| assert!(host.admin(&["create", "ada", "empty"]).status.success()); | ||
| assert!(host.admin(&["description", "ada", "site", "Docs & <b>source</b> for the site"]).status.success()); | ||
| // The same README in a second repository: its links must stay in that repository. | ||
| let out = host.git(&work, &["push", "-q", "ada@x:ada/twin.git", &format!("{first}:refs/heads/main")]); | ||
| assert!(out.status.success(), "{}", common::stderr(&out)); | ||
| @@ -873,6 +874,12 @@ fn public_web_clone_and_visibility_changes() { | ||
| assert!(server.get("/").text().contains("/ada/secret/tree")); | ||
| let page = server.get_signed_out("/ada/sharing/tree").text(); | ||
| assert!(page.contains("https://git.example.test/ada/sharing")); | ||
| // Visitors see only the HTTPS address; the signed-in operator also sees SSH and the visibility. | ||
| assert!(!page.contains("git@git.example.test") && !page.contains("class=\"vis\""), "{page}"); | ||
| let operator = server.get("/ada/sharing/tree").text(); | ||
| assert!(operator.contains("value=\"https://git.example.test/ada/sharing\""), "{operator}"); | ||
| assert!(operator.contains("value=\"git@git.example.test:ada/sharing.git\""), "{operator}"); | ||
| assert!(operator.contains("<span class=\"vis\">Public</span>"), "{operator}"); | ||
| assert_eq!(server.get_signed_out("/ada/sharing/raw?path=hello").text(), "public content"); | ||
| // Both protocol versions clone; version 2 is what the server speaks when asked. | ||
| for version in ["0", "2"] { | ||
| @@ -1115,3 +1122,41 @@ fn the_compare_form_and_its_mistakes() { | ||
| // A private repository's comparison needs sign-in, like its other pages. | ||
| assert_eq!(s.get_signed_out("/ada/site/compare?from=v0.1.0&to=light").status, 303); | ||
| } | ||
| #[test] | ||
| fn the_index_shows_descriptions_and_filters_by_name_or_description() { | ||
| let s = server(); | ||
| let all = s.get("/").text(); | ||
| assert!( | ||
| all.contains("<span class=\"rdesc\">Docs & <b>source</b> for the site</span>"), | ||
| "{all}" | ||
| ); | ||
| assert!(all.contains("<input type=\"search\" name=\"q\" value=\"\""), "{all}"); | ||
| let total = all.matches("class=\"repo-row\"").count(); | ||
| assert!(total >= 3, "{all}"); | ||
| let by_name = s.get("/?q=TWIN").text(); | ||
| assert_eq!(by_name.matches("class=\"repo-row\"").count(), 1, "{by_name}"); | ||
| assert!(by_name.contains("href=\"/ada/twin/tree\"")); | ||
| assert!(by_name.contains(&format!("<p class=\"count\">1 of {total}</p>")), "{by_name}"); | ||
| assert!(by_name.contains("value=\"TWIN\"") && by_name.contains(">Clear</a>"), "{by_name}"); | ||
| let by_description = s.get("/?q=source+site").text(); | ||
| assert_eq!(by_description.matches("class=\"repo-row\"").count(), 1, "{by_description}"); | ||
| assert!(by_description.contains("href=\"/ada/site/tree\"")); | ||
| let none = s.get("/?q=%3Cnothing%3E").text(); | ||
| assert!(none.contains("No repositories match “<nothing>”"), "{none}"); | ||
| assert!(!none.contains("class=\"repo-row\"")); | ||
| } | ||
| #[test] | ||
| fn the_header_shows_the_description_visibility_and_clone_addresses() { | ||
| let s = server(); | ||
| let html = s.get("/ada/site/tree").text(); | ||
| assert!(html.contains("<p class=\"repodesc\">Docs & <b>source</b> for the site</p>"), "{html}"); | ||
| assert!(html.contains("<span class=\"vis\">Private</span>"), "{html}"); | ||
| assert_eq!(html.matches("class=\"clone\"").count(), 1, "a private repository clones over SSH only"); | ||
| assert!(html.contains("value=\"git@git.example.test:ada/site.git\""), "{html}"); | ||
| // No description: no empty paragraph. | ||
| assert!(!s.get("/ada/twin/tree").text().contains("repodesc")); | ||
| } | ||
| @@ -9,8 +9,8 @@ use std::process::{Command, ExitCode, Stdio}; | ||
| use base64::Engine; | ||
| use clap::{Parser, Subcommand}; | ||
| use gitv_core::{ | ||
| NAME_RULE, RepoDir, chown_tree, config, entries, git, git_command, git_in, keys_path, kind_at, open_dir_at, | ||
| open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, unix_now, valid_name, | ||
| DESCRIPTION_LIMIT, NAME_RULE, RepoDir, chown_tree, config, entries, git, git_command, git_in, keys_path, kind_at, | ||
| open_dir_at, open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, unix_now, valid_name, | ||
| }; | ||
| use nix::errno::Errno; | ||
| use nix::fcntl::{Flock, FlockArg, OFlag, RenameFlags, openat, renameat2}; | ||
| @@ -29,6 +29,8 @@ fn help() -> String { | ||
| list list your repositories | ||
| create <name> create an empty repository | ||
| visibility <name> public|private set web access | ||
| description <name> [<text>] show or set the one-line description (\"\" removes it) | ||
| default-branch <name> [<branch>] show or set the branch the web shows and clones check out | ||
| delete <name> --yes move a repository to the trash (the operator can restore it for 30 days) | ||
| Pushing to a repository that does not exist yet creates it." | ||
| ) | ||
| @@ -52,6 +54,22 @@ enum Action { | ||
| }, | ||
| /// Set repository web visibility to public or private (root) | ||
| Visibility { owner: String, name: String, visibility: String }, | ||
| /// Show or set a repository's one-line description; "" removes it (root) | ||
| Description { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| text: Option<String>, | ||
| }, | ||
| /// Show or set the branch a repository's web pages show and clones check out (root) | ||
| DefaultBranch { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| branch: Option<String>, | ||
| }, | ||
| /// Move a repository to its owner's trash (root) | ||
| Delete { | ||
| #[arg(value_parser = name)] | ||
| @@ -651,6 +669,44 @@ fn visibility(owner: &str, name: &str, visibility: &str) -> Result<(), String> { | ||
| .map_err(|e| format!("couldn't set visibility: {e}")) | ||
| } | ||
| /// Print a repository's description, or set it to `text`; an empty text removes it. | ||
| fn description(owner: &str, name: &str, text: Option<&str>) -> Result<(), String> { | ||
| let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?; | ||
| let Some(text) = text else { | ||
| if let Some(text) = repo.description() { | ||
| println!("{text}"); | ||
| } | ||
| return Ok(()); | ||
| }; | ||
| // One line of plain text: the web shows it, and a terminal may print it. | ||
| let text = text.trim(); | ||
| if text.chars().count() > DESCRIPTION_LIMIT || text.chars().any(char::is_control) { | ||
| return Err(format!("a description is one line of at most {DESCRIPTION_LIMIT} characters")); | ||
| } | ||
| repo.set_description((!text.is_empty()).then_some(text)).map_err(|e| format!("couldn't set the description: {e}")) | ||
| } | ||
| /// Print the default branch (where HEAD points), or point it at an existing `branch`. | ||
| fn default_branch(owner: &str, name: &str, branch: Option<&str>) -> Result<(), String> { | ||
| let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?; | ||
| let Some(branch) = branch else { | ||
| let head = git(&repo, &["symbolic-ref", "HEAD"]).map_err(|_| "HEAD doesn't name a branch".to_string())?; | ||
| let head = head.strip_suffix(b"\n").unwrap_or(&head); | ||
| println!("{}", String::from_utf8_lossy(head.strip_prefix(b"refs/heads/").unwrap_or(head))); | ||
| return Ok(()); | ||
| }; | ||
| // Qualified, so a name like `-x` or `HEAD` can only ever mean a branch, and checked as a | ||
| // ref name before git is asked whether that branch exists. | ||
| let full = format!("refs/heads/{branch}"); | ||
| let exists = git(&repo, &["check-ref-format", &full]).is_ok() | ||
| && git(&repo, &["rev-parse", "--verify", "--quiet", &format!("{full}^{{commit}}")]).is_ok(); | ||
| if !exists { | ||
| return Err(format!("there's no branch named {branch}; push it first")); | ||
| } | ||
| git(&repo, &["symbolic-ref", "HEAD", &full]).map_err(|_| "couldn't set the default branch".to_string())?; | ||
| Ok(()) | ||
| } | ||
| /// Handle one SSH request from a key registered to owner. | ||
| fn serve(owner: &str, command: &str) -> Result<u8, String> { | ||
| let args = | ||
| @@ -660,6 +716,11 @@ fn serve(owner: &str, command: &str) -> Result<u8, String> { | ||
| [] | ["help"] => println!("{}", help()), | ||
| [program @ ("git-upload-pack" | "git-receive-pack"), path] => return serve_git(owner, program, path), | ||
| ["visibility", name, value] => visibility(owner, name, value)?, | ||
| // Unquoted words are one description: `description tools A small toolbox`. | ||
| ["description", name] => description(owner, name, None)?, | ||
| ["description", name, text @ ..] => description(owner, name, Some(&text.join(" ")))?, | ||
| ["default-branch", name] => default_branch(owner, name, None)?, | ||
| ["default-branch", name, branch] => default_branch(owner, name, Some(branch))?, | ||
| ["list"] => { | ||
| // Listed and checked through one handle on the owner's directory. | ||
| let directory = open_owner(owner); | ||
| @@ -926,6 +987,8 @@ fn run() -> Result<u8, String> { | ||
| Action::Restore { owner, entry, as_name } => restore(&owner, &entry, as_name.as_deref())?, | ||
| Action::Purge { older_than_days } => purge(older_than_days)?, | ||
| Action::Visibility { owner, name, visibility: value } => visibility(&owner, &name, &value)?, | ||
| Action::Description { owner, name, text } => description(&owner, &name, text.as_deref())?, | ||
| Action::DefaultBranch { owner, name, branch } => default_branch(&owner, &name, branch.as_deref())?, | ||
| Action::AddKey { owner, public_key, label } => add_key(&owner, &public_key, label.as_deref())?, | ||
| Action::Keys { owner } => list_keys(owner.as_deref())?, | ||
| Action::RemoveKey { fingerprint } => remove_key(&fingerprint)?, | ||
| @@ -745,3 +745,66 @@ fn key_labels_stay_on_one_line() { | ||
| } | ||
| assert!(!host.keys.exists(), "no key was written"); | ||
| } | ||
| #[test] | ||
| fn descriptions_are_set_shown_and_removed() { | ||
| let host = Host::new("ssh-description"); | ||
| assert!(host.ssh("ada", "create tools").status.success()); | ||
| // `git init` writes a placeholder, which doesn't count as a description. | ||
| let out = host.ssh("ada", "description tools"); | ||
| assert!(out.status.success() && stdout(&out).is_empty(), "{}", stdout(&out)); | ||
| assert!(host.ssh("ada", "description tools A small toolbox").status.success()); | ||
| assert_eq!(stdout(&host.ssh("ada", "description tools")), "A small toolbox\n"); | ||
| assert_eq!(fs::read_to_string(host.repo("ada", "tools").join("description")).unwrap(), "A small toolbox\n"); | ||
| // Quoted, as one argument, from the admin command too. | ||
| let out = host.admin(&["description", "ada", "tools", " Tools for ada "]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&host.ssh("ada", "description tools")), "Tools for ada\n"); | ||
| for bad in ["description tools 'two\nlines'", &format!("description tools {}", "x".repeat(161))] { | ||
| let out = host.ssh("ada", bad); | ||
| assert!(!out.status.success(), "{bad} was accepted"); | ||
| assert!(stderr(&out).contains("one line of at most 160"), "{}", stderr(&out)); | ||
| } | ||
| assert_eq!(stdout(&host.ssh("ada", "description tools")), "Tools for ada\n", "a refusal changes nothing"); | ||
| assert!(host.ssh("ada", "description tools ''").status.success()); | ||
| assert!(!host.repo("ada", "tools").join("description").exists()); | ||
| // Only the owner's own repositories. | ||
| assert!(!host.ssh("bob", "description tools Mine now").status.success()); | ||
| let leftovers: Vec<_> = fs::read_dir(host.repo("ada", "tools")) | ||
| .unwrap() | ||
| .map(|e| e.unwrap().file_name().into_string().unwrap()) | ||
| .filter(|n| n.starts_with(".description")) | ||
| .collect(); | ||
| assert!(leftovers.is_empty(), "{leftovers:?}"); | ||
| } | ||
| #[test] | ||
| fn the_default_branch_can_be_chosen_among_existing_branches() { | ||
| let host = Host::new("ssh-default-branch"); | ||
| let dir = work("ssh-default-branch-work", "main"); | ||
| git(&dir, &["branch", "release"]); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main", "release"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "main\n"); | ||
| let out = host.ssh("ada", "default-branch tools release"); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "release\n"); | ||
| let head = common::git_cmd(&host.repo("ada", "tools")).args(["symbolic-ref", "HEAD"]).output().unwrap(); | ||
| assert_eq!(head.stdout, b"refs/heads/release\n"); | ||
| // Names that aren't existing branches, or aren't branch names at all, change nothing. | ||
| for bad in ["missing", "-x", "../main", "HEAD", "refs/heads/main", "main^"] { | ||
| let out = host.ssh("ada", &format!("default-branch tools '{bad}'")); | ||
| assert!(!out.status.success(), "{bad} was accepted"); | ||
| assert!(stderr(&out).contains("no branch named"), "{bad}: {}", stderr(&out)); | ||
| } | ||
| assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "release\n"); | ||
| let out = host.admin(&["default-branch", "ada", "tools", "main"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "main\n"); | ||
| assert!(!host.ssh("bob", "default-branch tools release").status.success()); | ||
| } | ||