Style the web browser with light and dark themes
Browse filesSet the browser in Red Hat Display, Text and Mono, embedded in the gitv-web binary with the stylesheet so the server needs no font packages. Pages follow the system colour scheme and gain a repository header with tabs, a branch and tag menu, breadcrumbs, line-numbered code, a Markdown preview toggle, relative times, tag chips in history, and per-file diffs with line numbers. Syntax colours now come from the stylesheet instead of syntect's bundled themes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 11:07
- Commit
- f1cb563bb51c
- Parent
- 8776577
10 files changed +795−291
+0−110
| @@ -234,18 +234,6 @@ dependencies = [ | ||
| "cfg-if", | ||
| ] | ||
| [[package]] | ||
| name = "deranged" | ||
| version = "0.5.9" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" | ||
| [[package]] | ||
| name = "equivalent" | ||
| version = "1.0.3" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" | ||
| [[package]] | ||
| name = "fancy-regex" | ||
| version = "0.16.2" | ||
| @@ -322,12 +310,6 @@ dependencies = [ | ||
| "tokio", | ||
| ] | ||
| [[package]] | ||
| name = "hashbrown" | ||
| version = "0.17.2" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" | ||
| [[package]] | ||
| name = "heck" | ||
| version = "0.5.0" | ||
| @@ -419,16 +401,6 @@ dependencies = [ | ||
| "tower-service", | ||
| ] | ||
| [[package]] | ||
| name = "indexmap" | ||
| version = "2.14.2" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" | ||
| dependencies = [ | ||
| "equivalent", | ||
| "hashbrown", | ||
| ] | ||
| [[package]] | ||
| name = "is_terminal_polyfill" | ||
| version = "1.70.2" | ||
| @@ -447,12 +419,6 @@ version = "0.2.191" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" | ||
| [[package]] | ||
| name = "linked-hash-map" | ||
| version = "0.5.6" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" | ||
| [[package]] | ||
| name = "log" | ||
| version = "0.4.35" | ||
| @@ -510,12 +476,6 @@ dependencies = [ | ||
| "libc", | ||
| ] | ||
| [[package]] | ||
| name = "num-conv" | ||
| version = "0.2.2" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" | ||
| [[package]] | ||
| name = "once_cell" | ||
| version = "1.21.4" | ||
| @@ -540,25 +500,6 @@ version = "0.2.18" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" | ||
| [[package]] | ||
| name = "plist" | ||
| version = "1.10.4" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "d86a77b7d9cdebd9643c180c158748db7d894b24a3935ed4b5843e698ae086eb" | ||
| dependencies = [ | ||
| "base64", | ||
| "indexmap", | ||
| "quick-xml", | ||
| "serde", | ||
| "time", | ||
| ] | ||
| [[package]] | ||
| name = "powerfmt" | ||
| version = "0.2.1" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" | ||
| [[package]] | ||
| name = "proc-macro2" | ||
| version = "1.0.107" | ||
| @@ -586,15 +527,6 @@ version = "0.11.0" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" | ||
| [[package]] | ||
| name = "quick-xml" | ||
| version = "0.42.0" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" | ||
| dependencies = [ | ||
| "memchr", | ||
| ] | ||
| [[package]] | ||
| name = "quote" | ||
| version = "1.0.47" | ||
| @@ -769,14 +701,11 @@ dependencies = [ | ||
| "flate2", | ||
| "fnv", | ||
| "once_cell", | ||
| "plist", | ||
| "regex-syntax", | ||
| "serde", | ||
| "serde_derive", | ||
| "serde_json", | ||
| "thiserror", | ||
| "walkdir", | ||
| "yaml-rust", | ||
| ] | ||
| [[package]] | ||
| @@ -799,36 +728,6 @@ dependencies = [ | ||
| "syn", | ||
| ] | ||
| [[package]] | ||
| name = "time" | ||
| version = "0.3.55" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" | ||
| dependencies = [ | ||
| "deranged", | ||
| "num-conv", | ||
| "powerfmt", | ||
| "serde_core", | ||
| "time-core", | ||
| "time-macros", | ||
| ] | ||
| [[package]] | ||
| name = "time-core" | ||
| version = "0.1.9" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" | ||
| [[package]] | ||
| name = "time-macros" | ||
| version = "0.2.32" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" | ||
| dependencies = [ | ||
| "num-conv", | ||
| "time-core", | ||
| ] | ||
| [[package]] | ||
| name = "tokio" | ||
| version = "1.54.1" | ||
| @@ -960,15 +859,6 @@ dependencies = [ | ||
| "windows-link", | ||
| ] | ||
| [[package]] | ||
| name = "yaml-rust" | ||
| version = "0.4.5" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" | ||
| dependencies = [ | ||
| "linked-hash-map", | ||
| ] | ||
| [[package]] | ||
| name = "zlib-rs" | ||
| version = "0.6.8" | ||
+1−1
| @@ -11,5 +11,5 @@ html-escape = "0.3.1" | ||
| nix = { version = "0.32.0", features = ["user", "fs"] } | ||
| pulldown-cmark = { version = "0.13.6", default-features = false, features = ["html"] } | ||
| shlex = "2.0.1" | ||
| syntect = { version = "5.3.0", default-features = false, features = ["default-fancy"] } | ||
| syntect = { version = "5.3.0", default-features = false, features = ["default-syntaxes", "html", "regex-fancy"] } | ||
| tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net"] } | ||
+2−0
| @@ -5,6 +5,8 @@ Private Git hosting over OpenSSH, plus a read-only web browser. | ||
| - `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `delete`, `add-key`) | ||
| - `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, tags), with Markdown rendering and syntax highlighting (`src/render.rs`) | ||
| The browser follows the system's light or dark setting. Its stylesheet (`assets/style.css`) and the Red Hat Display, Text and Mono fonts (`assets/fonts`, SIL Open Font License) are built into the `gitv-web` binary, so the server needs no font packages. | ||
| ## Run locally | ||
| Set `GITV_REPOS` (and optionally `GITV_KEYS`) to point at a local tree. When `GITV_REPOS` is set, admin commands run without root. | ||
assets/fonts/OFL.txtAdded
+93−0
| @@ -0,0 +1,93 @@ | ||
| Google Inc. | ||
| This Font Software is licensed under the SIL Open Font License, Version 1.1. | ||
| This license is copied below, and is also available with a FAQ at: | ||
| http://scripts.sil.org/OFL | ||
| ----------------------------------------------------------- | ||
| SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 | ||
| ----------------------------------------------------------- | ||
| PREAMBLE | ||
| The goals of the Open Font License (OFL) are to stimulate worldwide | ||
| development of collaborative font projects, to support the font creation | ||
| efforts of academic and linguistic communities, and to provide a free and | ||
| open framework in which fonts may be shared and improved in partnership | ||
| with others. | ||
| The OFL allows the licensed fonts to be used, studied, modified and | ||
| redistributed freely as long as they are not sold by themselves. The | ||
| fonts, including any derivative works, can be bundled, embedded, | ||
| redistributed and/or sold with any software provided that any reserved | ||
| names are not used by derivative works. The fonts and derivatives, | ||
| however, cannot be released under any other type of license. The | ||
| requirement for fonts to remain under this license does not apply | ||
| to any document created using the fonts or their derivatives. | ||
| DEFINITIONS | ||
| "Font Software" refers to the set of files released by the Copyright | ||
| Holder(s) under this license and clearly marked as such. This may | ||
| include source files, build scripts and documentation. | ||
| "Reserved Font Name" refers to any names specified as such after the | ||
| copyright statement(s). | ||
| "Original Version" refers to the collection of Font Software components as | ||
| distributed by the Copyright Holder(s). | ||
| "Modified Version" refers to any derivative made by adding to, deleting, | ||
| or substituting -- in part or in whole -- any of the components of the | ||
| Original Version, by changing formats or by porting the Font Software to a | ||
| new environment. | ||
| "Author" refers to any designer, engineer, programmer, technical | ||
| writer or other person who contributed to the Font Software. | ||
| PERMISSION & CONDITIONS | ||
| Permission is hereby granted, free of charge, to any person obtaining | ||
| a copy of the Font Software, to use, study, copy, merge, embed, modify, | ||
| redistribute, and sell modified and unmodified copies of the Font | ||
| Software, subject to the following conditions: | ||
| 1) Neither the Font Software nor any of its individual components, | ||
| in Original or Modified Versions, may be sold by itself. | ||
| 2) Original or Modified Versions of the Font Software may be bundled, | ||
| redistributed and/or sold with any software, provided that each copy | ||
| contains the above copyright notice and this license. These can be | ||
| included either as stand-alone text files, human-readable headers or | ||
| in the appropriate machine-readable metadata fields within text or | ||
| binary files as long as those fields can be easily viewed by the user. | ||
| 3) No Modified Version of the Font Software may use the Reserved Font | ||
| Name(s) unless explicit written permission is granted by the corresponding | ||
| Copyright Holder. This restriction only applies to the primary font name as | ||
| presented to the users. | ||
| 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font | ||
| Software shall not be used to promote, endorse or advertise any | ||
| Modified Version, except to acknowledge the contribution(s) of the | ||
| Copyright Holder(s) and the Author(s) or with their explicit written | ||
| permission. | ||
| 5) The Font Software, modified or unmodified, in part or in whole, | ||
| must be distributed entirely under this license, and must not be | ||
| distributed under any other license. The requirement for fonts to | ||
| remain under this license does not apply to any document created | ||
| using the Font Software. | ||
| TERMINATION | ||
| This license becomes null and void if any of the above conditions are | ||
| not met. | ||
| DISCLAIMER | ||
| THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF | ||
| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT | ||
| OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE | ||
| COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | ||
| INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL | ||
| DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
| FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM | ||
| OTHER DEALINGS IN THE FONT SOFTWARE. | ||
+0−0
Binary file changed.
+0−0
Binary file changed.
+0−0
Binary file changed.
assets/style.cssAdded
+227−0
| @@ -0,0 +1,227 @@ | ||
| @font-face{font-family:"Red Hat Display";src:url(/fonts/display.woff2) format("woff2");font-weight:300 900;font-display:swap} | ||
| @font-face{font-family:"Red Hat Text";src:url(/fonts/text.woff2) format("woff2");font-weight:300 700;font-display:swap} | ||
| @font-face{font-family:"Red Hat Mono";src:url(/fonts/mono.woff2) format("woff2");font-weight:300 700;font-display:swap} | ||
| :root{ | ||
| color-scheme:light; | ||
| --page:#f6f7f9;--surface:#fff;--sunk:#f9fafb;--ink:#161a20;--ink-2:#5b6472;--rule:#e2e6ea;--rule-2:#eef0f3; | ||
| --accent:#0f6b5f;--accent-wash:#e4f2ef;--target:#fff5d1; | ||
| --add:#e6f4ea;--add-ink:#17663a;--add-num:#d2ebda;--del:#fcebea;--del-ink:#a32a2a;--del-num:#f6d6d4;--hunk:#eef3f6; | ||
| --t-keyword:#7a3e9d;--t-string:#1c6b3e;--t-comment:#6a7280;--t-constant:#9c4612;--t-name:#0e5a85;--t-support:#0f6b5f; | ||
| --shadow:0 12px 32px -10px rgb(16 20 24 / .22); | ||
| --f-display:"Red Hat Display",ui-sans-serif,system-ui,sans-serif; | ||
| --f-text:"Red Hat Text",ui-sans-serif,system-ui,sans-serif; | ||
| --f-mono:"Red Hat Mono",ui-monospace,SFMono-Regular,Menlo,monospace; | ||
| } | ||
| @media (prefers-color-scheme:dark){:root{ | ||
| color-scheme:dark; | ||
| --page:#101418;--surface:#171c22;--sunk:#14181d;--ink:#e5e8ec;--ink-2:#9aa3af;--rule:#262d36;--rule-2:#1e242b; | ||
| --accent:#5fc9b6;--accent-wash:#16302c;--target:#3a3317; | ||
| --add:#122b1c;--add-ink:#8fd6a5;--add-num:#163522;--del:#341a1b;--del-ink:#f2a3a0;--del-num:#3f2022;--hunk:#18222b; | ||
| --t-keyword:#d1a8f0;--t-string:#8fd5a6;--t-comment:#8b95a3;--t-constant:#f0b27a;--t-name:#80c6ef;--t-support:#5fc9b6; | ||
| --shadow:0 12px 32px -10px rgb(0 0 0 / .6); | ||
| }} | ||
| *{box-sizing:border-box} | ||
| html{-webkit-text-size-adjust:100%} | ||
| body{margin:0;background:var(--page);color:var(--ink);font:400 16px/1.55 var(--f-text)} | ||
| a{color:var(--accent);text-decoration:none;text-underline-offset:.18em} | ||
| a:hover{text-decoration:underline} | ||
| :focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:4px} | ||
| code,pre,kbd,.mono{font-family:var(--f-mono)} | ||
| .skip{position:absolute;left:16px;top:-48px;background:var(--surface);padding:8px 12px;border-radius:6px;z-index:20} | ||
| .skip:focus{top:8px} | ||
| .ic{width:16px;height:16px;flex:none;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linecap:round;stroke-linejoin:round} | ||
| /* Top bar */ | ||
| .top{background:var(--surface);border-bottom:1px solid var(--rule)} | ||
| .bar{display:flex;align-items:center;justify-content:space-between;gap:16px;max-width:1080px;height:56px;margin:0 auto;padding:0 24px} | ||
| .mark{font:800 20px/1 var(--f-display);letter-spacing:-.02em;color:var(--ink)} | ||
| .mark:hover{text-decoration:none;color:var(--accent)} | ||
| .host{font-family:var(--f-mono);font-size:13px;color:var(--ink-2)} | ||
| main{max-width:1080px;margin:0 auto;padding:32px 24px 72px} | ||
| /* Page and repository headings */ | ||
| .pagehead{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;margin:0 0 20px} | ||
| .title{font:700 30px/1.15 var(--f-display);letter-spacing:-.02em;margin:0} | ||
| .count{margin:0;color:var(--ink-2)} | ||
| .repohead{display:flex;align-items:center;justify-content:space-between;gap:14px 28px;flex-wrap:wrap;margin:0 0 14px} | ||
| .reponame{font:800 34px/1.1 var(--f-display);letter-spacing:-.025em;margin:0;display:flex;align-items:baseline; | ||
| gap:6px;flex-wrap:wrap;min-width:0;overflow-wrap:anywhere} | ||
| .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} | ||
| .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); | ||
| background:var(--surface);border:1px solid var(--rule);border-radius:0 8px 8px 0} | ||
| .tabs{display:flex;gap:4px;margin:0 0 20px;border-bottom:1px solid var(--rule);overflow-x:auto;scrollbar-width:none} | ||
| .tabs a{display:flex;align-items:center;gap:8px;min-height:44px;padding:0 14px;margin-bottom:-1px;color:var(--ink-2); | ||
| font-weight:500;white-space:nowrap;border-bottom:2px solid transparent} | ||
| .tabs a:hover{color:var(--ink);text-decoration:none;border-bottom-color:var(--rule)} | ||
| .tabs a[aria-current]{color:var(--ink);border-bottom-color:var(--accent)} | ||
| .tabs .n{font-size:12px;font-weight:600;line-height:18px;padding:0 7px;border-radius:99px;color:var(--ink-2); | ||
| background:var(--rule-2);font-variant-numeric:tabular-nums} | ||
| /* Branch menu and path */ | ||
| .locator{display:flex;align-items:center;gap:8px 14px;flex-wrap:wrap;margin:0 0 12px;min-height:38px} | ||
| .refmenu{position:relative} | ||
| .refmenu summary{list-style:none;display:inline-flex;align-items:center;gap:8px;min-height:36px;padding:0 10px 0 12px; | ||
| font:500 14px var(--f-mono);background:var(--surface);border:1px solid var(--rule);border-radius:8px;cursor:pointer} | ||
| .refmenu summary::-webkit-details-marker{display:none} | ||
| .refmenu summary:hover,.refmenu[open] summary{border-color:var(--ink-2)} | ||
| .refmenu summary .ic{color:var(--ink-2)} | ||
| .menu{position:absolute;z-index:10;top:calc(100% + 6px);left:0;min-width:240px;max-width:min(360px,90vw);max-height:360px; | ||
| overflow:auto;padding:6px;background:var(--surface);border:1px solid var(--rule);border-radius:10px;box-shadow:var(--shadow)} | ||
| .menu h2{font:600 12px/1.3 var(--f-text);color:var(--ink-2);margin:8px 10px 4px} | ||
| .menu h2:first-child{margin-top:4px} | ||
| .menu a{display:block;padding:7px 10px;border-radius:6px;color:var(--ink);font:13px var(--f-mono);overflow-wrap:anywhere} | ||
| .menu a:hover{background:var(--sunk);text-decoration:none} | ||
| .menu a[aria-current]{background:var(--accent-wash);color:var(--accent);font-weight:600} | ||
| .crumbs{display:flex;align-items:center;flex-wrap:wrap;gap:2px 8px;min-width:0;font:14px var(--f-mono);color:var(--ink-2)} | ||
| .crumbs a{font-weight:500} | ||
| .crumbs b{color:var(--ink);font-weight:600;overflow-wrap:anywhere} | ||
| .crumbs .sep{opacity:.6} | ||
| /* Panels and rows */ | ||
| .panel{background:var(--surface);border:1px solid var(--rule);border-radius:10px;overflow:hidden;margin:0 0 24px} | ||
| .panel-head{display:flex;align-items:center;justify-content:space-between;gap:8px 16px;flex-wrap:wrap;min-height:48px; | ||
| padding:8px 16px;font-size:14px;background:var(--sunk);border-bottom:1px solid var(--rule)} | ||
| .panel-head .lead{display:flex;align-items:center;gap:10px;min-width:0;flex:1} | ||
| .panel-head .lead b{font-weight:600;overflow-wrap:anywhere} | ||
| .panel-head .who{white-space:nowrap} | ||
| .panel-head .side{display:flex;align-items:center;gap:12px;color:var(--ink-2);font-size:13px;white-space:nowrap} | ||
| .subject{color:var(--ink);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| .quiet{color:var(--ink-2)} | ||
| .rows{list-style:none;margin:0;padding:0} | ||
| .rows li + li{border-top:1px solid var(--rule-2)} | ||
| .entry{display:flex;align-items:center;gap:10px;min-height:42px;padding:6px 16px;color:var(--ink)} | ||
| a.entry:hover{background:var(--sunk);text-decoration:none} | ||
| a.entry:hover .name{color:var(--accent)} | ||
| .entry .name{flex:1;min-width:0;overflow-wrap:anywhere} | ||
| .entry .ic{color:var(--ink-2)} | ||
| .entry.dir .ic{color:var(--accent);fill:var(--accent-wash)} | ||
| .sha{font:500 12.5px var(--f-mono);padding:2px 7px;border-radius:6px;white-space:nowrap; | ||
| color:var(--accent);background:var(--accent-wash)} | ||
| .sha:hover{text-decoration:none;box-shadow:inset 0 0 0 1px var(--accent)} | ||
| .repo-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:2px 20px;align-items:center;padding:14px 18px;color:var(--ink)} | ||
| .repo-row:hover{background:var(--sunk);text-decoration:none} | ||
| .repo-row:hover .rname{color:var(--accent)} | ||
| .rname{font:700 18px/1.3 var(--f-display);letter-spacing:-.01em;overflow-wrap:anywhere} | ||
| .rname span{font-weight:400;color:var(--ink-2)} | ||
| .rlast{grid-column:1;font-size:14px;color:var(--ink-2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| .rwhen{grid-row:1 / span 2;grid-column:2;font-size:13px;color:var(--ink-2);white-space:nowrap} | ||
| .commit-row{display:flex;align-items:center;gap:14px;min-height:58px;padding:10px 16px} | ||
| .commit-row .cmain{flex:1;min-width:0} | ||
| .commit-row .csubj{color:var(--ink);font-weight:500;overflow-wrap:anywhere} | ||
| .commit-row .csubj:hover{color:var(--accent)} | ||
| .commit-row .cmeta{display:block;margin-top:2px;font-size:13px;color:var(--ink-2)} | ||
| .tagchip{display:inline-flex;align-items:center;gap:4px;margin-left:6px;padding:0 8px 0 6px;font:500 12px/20px var(--f-mono); | ||
| color:var(--ink);background:var(--surface);border:1px solid var(--rule);border-radius:99px;vertical-align:1px} | ||
| .tagchip .ic{width:12px;height:12px;color:var(--accent)} | ||
| .tagchip:hover{border-color:var(--accent);text-decoration:none} | ||
| .pager{display:flex;justify-content:space-between;gap:12px} | ||
| .tag-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:4px 18px;align-items:center;padding:16px 18px} | ||
| .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} | ||
| /* Buttons */ | ||
| .button{display:inline-flex;align-items:center;gap:6px;min-height:34px;padding:0 12px;font:500 14px var(--f-text); | ||
| color:var(--ink);background:var(--surface);border:1px solid var(--rule);border-radius:8px;white-space:nowrap} | ||
| .button:hover{border-color:var(--ink-2);text-decoration:none} | ||
| .segmented{display:inline-flex;border:1px solid var(--rule);border-radius:8px;overflow:hidden} | ||
| .segmented a{display:flex;align-items:center;min-height:32px;padding:0 12px;font-size:14px;font-weight:500;color:var(--ink-2)} | ||
| .segmented a + a{border-left:1px solid var(--rule)} | ||
| .segmented a:hover{color:var(--ink);background:var(--sunk);text-decoration:none} | ||
| .segmented a[aria-current]{color:var(--accent);background:var(--accent-wash)} | ||
| /* Code */ | ||
| .code-view{display:grid;grid-template-columns:auto minmax(0,1fr);font:13.5px/1.6 var(--f-mono);tab-size:4} | ||
| .code-view pre{margin:0;padding:12px 0;font:inherit} | ||
| .code-view .gutter{padding:12px 14px 12px 18px;text-align:right;color:var(--ink-2);opacity:.7;user-select:none; | ||
| border-right:1px solid var(--rule-2);background:var(--sunk)} | ||
| .code-view .code{padding-left:18px;padding-right:24px;overflow-x:auto;white-space:pre} | ||
| .note{padding:28px 20px;text-align:center;color:var(--ink-2)} | ||
| /* Syntax tokens (syntect scope classes) */ | ||
| .hl-keyword,.hl-storage{color:var(--t-keyword)} | ||
| .hl-entity.hl-name{color:var(--t-name)} | ||
| .hl-support{color:var(--t-support)} | ||
| .hl-constant{color:var(--t-constant)} | ||
| .hl-string,.hl-string *{color:var(--t-string)} | ||
| .hl-comment,.hl-comment *{color:var(--t-comment);font-style:italic} | ||
| .hl-markup.hl-heading{color:var(--ink);font-weight:700} | ||
| .hl-markup.hl-bold{font-weight:700}.hl-markup.hl-italic{font-style:italic} | ||
| .hl-markup.hl-inserted{color:var(--add-ink)}.hl-markup.hl-deleted{color:var(--del-ink)} | ||
| /* Markdown */ | ||
| .markdown{padding:8px 32px 28px;max-width:84ch;overflow-wrap:anywhere} | ||
| .markdown h1,.markdown h2,.markdown h3,.markdown h4{font-family:var(--f-display);letter-spacing:-.015em;line-height:1.25;margin:28px 0 10px} | ||
| .markdown h1{font-size:28px} | ||
| .markdown h2{font-size:21px;padding-bottom:6px;border-bottom:1px solid var(--rule-2)} | ||
| .markdown h3{font-size:17px} | ||
| .markdown p,.markdown ul,.markdown ol{margin:0 0 14px} | ||
| .markdown li + li{margin-top:4px} | ||
| .markdown ul.contains-task-list{list-style:none;padding-left:4px} | ||
| .markdown pre{margin:0 0 16px;padding:12px 14px;overflow-x:auto;font-size:13.5px;line-height:1.55; | ||
| background:var(--sunk);border:1px solid var(--rule-2);border-radius:8px} | ||
| .markdown :not(pre) > code{font-size:.875em;padding:1px 4px;border-radius:4px;background:var(--rule-2)} | ||
| .markdown blockquote{margin:0 0 16px;padding:2px 0 2px 16px;color:var(--ink-2);border-left:3px solid var(--rule)} | ||
| .markdown hr{margin:24px 0;border:0;border-top:1px solid var(--rule)} | ||
| .markdown table{display:block;max-width:100%;overflow-x:auto;margin:0 0 16px;border-collapse:collapse;font-size:14.5px} | ||
| .markdown th,.markdown td{padding:7px 12px;text-align:left;vertical-align:top;border:1px solid var(--rule)} | ||
| .markdown th{font-weight:600;background:var(--sunk)} | ||
| .markdown img{max-width:100%} | ||
| /* Commit */ | ||
| .cmsg{padding:24px 28px 22px} | ||
| .ctitle{font:700 clamp(22px,3.4vw,28px)/1.2 var(--f-display);letter-spacing:-.015em;margin:0 0 10px;max-width:42ch;overflow-wrap:anywhere} | ||
| .cbody{margin:0;max-width:72ch;font:15px/1.6 var(--f-text);color:var(--ink-2);white-space:pre-wrap;overflow-wrap:anywhere} | ||
| .facts{display:flex;flex-wrap:wrap;gap:12px 36px;margin:0;padding:16px 28px;font-size:14px;background:var(--sunk);border-top:1px solid var(--rule)} | ||
| .facts dt{font-size:12.5px;font-weight:600;color:var(--ink-2);margin-bottom:2px} | ||
| .facts dd{margin:0;overflow-wrap:anywhere} | ||
| .changes{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;margin:32px 0 12px;font:700 19px/1.3 var(--f-display)} | ||
| .plus,.minus{font:600 14px var(--f-text);font-variant-numeric:tabular-nums} | ||
| .plus{color:var(--add-ink)}.minus{color:var(--del-ink)} | ||
| .status{font-size:12px;font-weight:600;padding:1px 8px;border-radius:99px;color:var(--ink-2);background:var(--rule-2)} | ||
| .diff-wrap{overflow-x:auto} | ||
| .diff{width:100%;border-collapse:collapse;font:13px/1.55 var(--f-mono)} | ||
| .diff td{padding:0;vertical-align:top} | ||
| .diff .num{width:1%;min-width:3.5em;padding:0 10px;text-align:right;color:var(--ink-2);white-space:nowrap;user-select:none; | ||
| font-variant-numeric:tabular-nums} | ||
| .diff .num::before{content:attr(data-n)} | ||
| .diff .line{padding:0 16px 0 6px;white-space:pre} | ||
| .diff .line::before{content:attr(data-s);display:inline-block;width:1.3em;color:var(--ink-2);user-select:none} | ||
| .diff .add .line{background:var(--add);color:var(--add-ink)}.diff .add .num{background:var(--add-num)} | ||
| .diff .del .line{background:var(--del);color:var(--del-ink)}.diff .del .num{background:var(--del-num)} | ||
| .diff .hunk td{padding:4px 16px;color:var(--ink-2);background:var(--hunk)} | ||
| /* Empty and missing */ | ||
| .empty{padding:48px 24px;text-align:center;color:var(--ink-2)} | ||
| .empty h2{margin:0 0 6px;font:700 20px/1.3 var(--f-display);color:var(--ink)} | ||
| .empty code{display:inline-block;margin-top:10px;padding:6px 10px;font-size:13px;color:var(--ink);overflow-wrap:anywhere; | ||
| background:var(--sunk);border:1px solid var(--rule);border-radius:8px} | ||
| .notfound{max-width:52ch;padding:48px 0} | ||
| .notfound .count{margin:8px 0 20px} | ||
| @media (max-width:640px){ | ||
| .bar{padding:0 16px} | ||
| main{padding:20px 16px 56px} | ||
| .reponame{font-size:27px} | ||
| .clone{flex-basis:100%} | ||
| .markdown{padding:4px 18px 18px} | ||
| .cmsg{padding:18px}.facts{padding:14px 18px;gap:12px 24px} | ||
| .repo-row,.tag-row{grid-template-columns:minmax(0,1fr)} | ||
| .rwhen,.tag-row .tacts{grid-row:auto;grid-column:1} | ||
| .panel-head .who{display:none} | ||
| } | ||
| @media (prefers-reduced-motion:no-preference){ | ||
| a.entry,.repo-row,.tabs a,.button,.segmented a,.refmenu summary,.menu a{transition:background-color .12s,border-color .12s,color .12s} | ||
| } | ||
+469−162
| @@ -1,21 +1,28 @@ | ||
| //! Read-only web browser for GITv repositories, served on localhost behind Caddy. | ||
| use std::collections::HashMap; | ||
| use std::fmt::Write as _; | ||
| use std::path::PathBuf; | ||
| use std::time::{SystemTime, UNIX_EPOCH}; | ||
| use axum::extract::{Path, Query}; | ||
| use axum::http::{StatusCode, header}; | ||
| use axum::response::{IntoResponse, Redirect, Response}; | ||
| use axum::{Router, routing::get}; | ||
| use clap::{Parser, Subcommand}; | ||
| use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc}; | ||
| use gitv::render; | ||
| use gitv::{HOST, git, repos_root, valid_name}; | ||
| use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc}; | ||
| static STYLESHEET: std::sync::LazyLock<String> = std::sync::LazyLock::new(render::stylesheet); | ||
| const STYLESHEET: &str = include_str!("../../assets/style.css"); | ||
| const FONT_DISPLAY: &[u8] = include_bytes!("../../assets/fonts/display.woff2"); | ||
| const FONT_TEXT: &[u8] = include_bytes!("../../assets/fonts/text.woff2"); | ||
| const FONT_MONO: &[u8] = include_bytes!("../../assets/fonts/mono.woff2"); | ||
| const FAVICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#0f6b5f"/><g fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round"><circle cx="11" cy="9" r="2.6"/><circle cx="11" cy="23" r="2.6"/><circle cx="22" cy="12" r="2.6"/><path d="M11 11.6v8.8M22 14.6c0 4-3.4 5-11 6"/></g></svg>"##; | ||
| const PAGE: usize = 50; | ||
| const RAW_LIMIT: usize = 50 << 20; | ||
| const DIFF_LIMIT: usize = 2 << 20; | ||
| #[derive(Parser)] | ||
| #[command(about = "Read-only web browser for GITv repositories")] | ||
| @@ -42,32 +49,142 @@ enum View { | ||
| Missing, | ||
| } | ||
| const SECURITY: [(header::HeaderName, &str); 4] = [ | ||
| (header::CONTENT_SECURITY_POLICY, | ||
| "default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'"), | ||
| (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), | ||
| (header::REFERRER_POLICY, "no-referrer"), | ||
| (header::CACHE_CONTROL, "no-store"), | ||
| ]; | ||
| impl IntoResponse for View { | ||
| fn into_response(self) -> Response { | ||
| let headers = [ | ||
| (header::CONTENT_SECURITY_POLICY, "default-src 'none'; style-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'"), | ||
| (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), | ||
| (header::REFERRER_POLICY, "no-referrer"), | ||
| (header::CACHE_CONTROL, "no-store"), | ||
| ]; | ||
| let html = [(header::CONTENT_TYPE, "text/html; charset=utf-8")]; | ||
| match self { | ||
| View::Html(body) => (headers, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body).into_response(), | ||
| View::Raw(data, kind) => (headers, [(header::CONTENT_TYPE, kind)], data).into_response(), | ||
| View::Html(body) => (SECURITY, html, body).into_response(), | ||
| View::Raw(data, kind) => (SECURITY, [(header::CONTENT_TYPE, kind)], data).into_response(), | ||
| View::Redirect(to) => Redirect::to(&to).into_response(), | ||
| View::Missing => (StatusCode::NOT_FOUND, headers, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], | ||
| page("Not found", "<h1>Nothing here</h1><p>That repository, branch, file or commit doesn’t exist, \ | ||
| or the link is malformed.</p><p><a href=\"/\">Back to repositories</a></p>")) | ||
| .into_response(), | ||
| View::Missing => (StatusCode::NOT_FOUND, SECURITY, html, view_missing()).into_response(), | ||
| } | ||
| } | ||
| } | ||
| fn static_file(kind: &'static str, data: &'static [u8]) -> Response { | ||
| ([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "max-age=86400")], data).into_response() | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Helpers | ||
| fn icon(name: &str) -> String { | ||
| let path = match name { | ||
| "dir" => r#"<path d="M2 4.5c0-.6.4-1 1-1h3.2l1.4 1.5H13c.6 0 1 .4 1 1v6.5c0 .6-.4 1-1 1H3c-.6 0-1-.4-1-1z"/>"#, | ||
| "file" => r#"<path d="M4 1.8h5.3L12.5 5v9.2H4z"/><path d="M9 1.8v3.5h3.5"/>"#, | ||
| "branch" => r#"<circle cx="4.5" cy="3.5" r="1.6"/><circle cx="4.5" cy="12.5" r="1.6"/><circle cx="11.5" cy="5" r="1.6"/><path d="M4.5 5.1v5.8M11.5 6.6c0 2.6-2.2 3.3-7 4.3"/>"#, | ||
| "tag" => r#"<path d="M2 2.5h5.3l6.2 6.2-4.8 4.8-6.7-6.7z"/><circle cx="5" cy="5.5" r="1"/>"#, | ||
| "book" => r#"<path d="M2.5 3h4c.8 0 1.5.7 1.5 1.5V13c0-.6-.5-1-1-1h-4.5zM13.5 3h-4c-.8 0-1.5.7-1.5 1.5V13c0-.6.5-1 1-1h4.5z"/>"#, | ||
| "code" => r#"<path d="M5.5 4.5 2 8l3.5 3.5M10.5 4.5 14 8l-3.5 3.5"/>"#, | ||
| "commits" => r#"<circle cx="8" cy="8" r="2.4"/><path d="M1.5 8h4.1M10.4 8h4.1"/>"#, | ||
| "chevron" => r#"<path d="M4.5 6.5 8 10l3.5-3.5"/>"#, | ||
| "up" => r#"<path d="M8 13V3.5M4 7.5l4-4 4 4"/>"#, | ||
| _ => "", | ||
| }; | ||
| format!(r#"<svg class="ic" viewBox="0 0 16 16" aria-hidden="true">{path}</svg>"#) | ||
| } | ||
| fn encode(value: &str) -> String { | ||
| value | ||
| .bytes() | ||
| .map(|b| match b { | ||
| b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => (b as char).to_string(), | ||
| _ => format!("%{b:02X}"), | ||
| }) | ||
| .collect() | ||
| } | ||
| /// A repository-relative path with no `..`, empty or absolute parts. | ||
| fn clean_path(value: &str) -> Option<String> { | ||
| let parts: Vec<&str> = value.split('/').filter(|p| !p.is_empty()).collect(); | ||
| if parts.iter().any(|p| *p == "." || *p == ".." || p.contains('\0')) { | ||
| return None; | ||
| } | ||
| Some(parts.join("/")) | ||
| } | ||
| fn parent_of(path: &str) -> &str { | ||
| path.rsplit_once('/').map_or("", |(p, _)| p) | ||
| } | ||
| fn file_name(path: &str) -> &str { | ||
| path.rsplit('/').next().unwrap_or(path) | ||
| } | ||
| /// "3 hours ago" for recent times, the calendar date (as git printed it) after a month. | ||
| fn ago(stamp: &str, date: &str) -> String { | ||
| let Ok(then) = stamp.parse::<u64>() else { return date.to_string() }; | ||
| let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); | ||
| let span = now.saturating_sub(then); | ||
| let unit = |n: u64, word: &str| format!("{n} {word}{} ago", if n == 1 { "" } else { "s" }); | ||
| match span { | ||
| 0..60 => "just now".into(), | ||
| 60..3600 => unit(span / 60, "minute"), | ||
| 3600..86400 => unit(span / 3600, "hour"), | ||
| 86400..2_592_000 => unit(span / 86400, "day"), | ||
| _ => date.to_string(), | ||
| } | ||
| } | ||
| fn plural(count: usize, one: &str, many: &str) -> String { | ||
| format!("{count} {}", if count == 1 { one } else { many }) | ||
| } | ||
| fn size(bytes: usize) -> String { | ||
| match bytes { | ||
| 0..1024 => plural(bytes, "byte", "bytes"), | ||
| 1024..1_048_576 => format!("{:.1} KB", bytes as f64 / 1024.0), | ||
| _ => format!("{:.1} MB", bytes as f64 / 1_048_576.0), | ||
| } | ||
| } | ||
| fn page(title: &str, body: &str) -> String { | ||
| format!( | ||
| r##"<!doctype html><html lang="en"><head><meta charset="utf-8"> | ||
| <meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| <title>{title} | GITv</title> | ||
| <link rel="stylesheet" href="/style.css"><link rel="icon" href="/favicon.svg" type="image/svg+xml"> | ||
| <link rel="preload" href="/fonts/display.woff2" as="font" type="font/woff2" crossorigin> | ||
| <link rel="preload" href="/fonts/text.woff2" as="font" type="font/woff2" crossorigin></head> | ||
| <body><a class="skip" href="#main">Skip to content</a> | ||
| <header class="top"><div class="bar"><a class="mark" href="/">GITv</a><span class="host">{HOST}</span></div></header> | ||
| <main id="main">{body}</main></body></html>"##, | ||
| title = esc(title) | ||
| ) | ||
| } | ||
| fn view_missing() -> String { | ||
| page("Not found", r#"<section class="notfound"><h1 class="title">Nothing here</h1> | ||
| <p class="count">That repository, branch, file or commit doesn’t exist, or the link is malformed.</p> | ||
| <a class="button" href="/">Back to repositories</a></section>"#) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Repository access | ||
| struct Repo { | ||
| owner: String, | ||
| name: String, | ||
| path: PathBuf, | ||
| } | ||
| /// The newest commit on a ref: full hash, subject, author, unix time, short date. | ||
| struct Head { | ||
| oid: String, | ||
| subject: String, | ||
| author: String, | ||
| stamp: String, | ||
| date: String, | ||
| } | ||
| impl Repo { | ||
| fn open(owner: &str, name: &str) -> Option<Repo> { | ||
| if !(valid_name(owner) && valid_name(name)) { | ||
| @@ -82,11 +199,8 @@ impl Repo { | ||
| } | ||
| fn url(&self, view: &str, query: &[(&str, &str)]) -> String { | ||
| let query: Vec<String> = query | ||
| .iter() | ||
| .filter(|(_, v)| !v.is_empty()) | ||
| .map(|(k, v)| format!("{k}={}", encode(v))) | ||
| .collect(); | ||
| let query: Vec<String> = | ||
| query.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k}={}", encode(v))).collect(); | ||
| let base = format!("/{}/{}/{view}", self.owner, self.name); | ||
| if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) } | ||
| } | ||
| @@ -95,6 +209,12 @@ impl Repo { | ||
| self.git(&["symbolic-ref", "--short", "HEAD"]).map_or("HEAD".into(), |s| s.trim().into()) | ||
| } | ||
| fn list_refs(&self, namespace: &str) -> Vec<String> { | ||
| self.git(&["for-each-ref", "--format=%(refname:short)", namespace]) | ||
| .map(|s| s.lines().map(str::to_string).collect()) | ||
| .unwrap_or_default() | ||
| } | ||
| /// The commit a ref names, rejecting anything that could read as an option or range. | ||
| fn resolve(&self, reference: &str) -> Option<String> { | ||
| let ok = (1..=200).contains(&reference.len()) | ||
| @@ -108,11 +228,28 @@ impl Repo { | ||
| self.git(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).map(|s| s.trim().into()) | ||
| } | ||
| /// (oid, subject, author, timestamp) of the newest commit on rev. | ||
| fn latest(&self, rev: &str) -> Option<[String; 4]> { | ||
| let out = self.git(&["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct", rev, "--"])?; | ||
| let fields: Vec<&str> = out.trim_end().split('\x1f').collect(); | ||
| <[&str; 4]>::try_from(fields).ok().map(|f| f.map(String::from)) | ||
| fn latest(&self, rev: &str) -> Option<Head> { | ||
| let out = self.git(&["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", rev, "--"])?; | ||
| let f: Vec<&str> = out.trim_end().split('\x1f').collect(); | ||
| let [oid, subject, author, stamp, date] = <[&str; 5]>::try_from(f).ok()?; | ||
| Some(Head { oid: oid.into(), subject: subject.into(), author: author.into(), stamp: stamp.into(), date: date.into() }) | ||
| } | ||
| fn commit_count(&self, rev: &str) -> usize { | ||
| self.git(&["rev-list", "--count", rev, "--"]).and_then(|s| s.trim().parse().ok()).unwrap_or(0) | ||
| } | ||
| /// Tag names grouped by the commit they point at, for labelling history. | ||
| fn tags_by_commit(&self) -> HashMap<String, Vec<String>> { | ||
| let mut found: HashMap<String, Vec<String>> = HashMap::new(); | ||
| let out = self.git(&["for-each-ref", "--format=%(refname:short) %(objectname) %(*objectname)", "refs/tags"]); | ||
| for line in out.unwrap_or_default().lines() { | ||
| let parts: Vec<&str> = line.split_whitespace().collect(); | ||
| if let [name, direct, rest @ ..] = parts.as_slice() { | ||
| found.entry(rest.first().unwrap_or(direct).to_string()).or_default().push(name.to_string()); | ||
| } | ||
| } | ||
| found | ||
| } | ||
| /// Render a Markdown file from directory `dir`, linking repository paths at `reference`. | ||
| @@ -128,44 +265,85 @@ impl Repo { | ||
| }) | ||
| } | ||
| fn header(&self) -> String { | ||
| let r = |v| self.url(v, &[]); | ||
| /// Name, clone address and tabs, shared by every repository page. | ||
| fn masthead(&self, active: &str, reference: &str) -> String { | ||
| let commits = self.resolve(reference).map_or(0, |c| self.commit_count(&c)); | ||
| let tags = self.list_refs("refs/tags").len(); | ||
| let tab = |view: &str, glyph: &str, label: &str, count: Option<usize>| { | ||
| let current = if view == active { r#" aria-current="page""# } else { "" }; | ||
| let query: &[(&str, &str)] = if view == "tags" { &[] } else { &[("ref", reference)] }; | ||
| let badge = count.map_or(String::new(), |n| format!(r#"<span class="n">{n}</span>"#)); | ||
| format!(r#"<a href="{}"{current}>{}{label}{badge}</a>"#, attr(&self.url(view, query)), icon(glyph)) | ||
| }; | ||
| format!( | ||
| "<h1><a href=\"/\">GITv</a> / {owner} / {name}</h1>\ | ||
| <p>Clone: <code>git@{HOST}:{owner}/{name}.git</code></p>\ | ||
| <nav><a href=\"{}\">Code</a> · <a href=\"{}\">Commits</a> · <a href=\"{}\">Tags</a></nav><hr>", | ||
| attr(&r("tree")), attr(&r("log")), attr(&r("tags")), | ||
| owner = esc(&self.owner), name = esc(&self.name), | ||
| r#"<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>SSH</span><input readonly aria-label="Clone address" value="git@{HOST}:{owner}/{name}.git"></label></div> | ||
| <nav class="tabs" aria-label="Repository">{}{}{}</nav>"#, | ||
| tab("tree", "code", "Code", None), | ||
| tab("log", "commits", "Commits", Some(commits)), | ||
| tab("tags", "tag", "Tags", Some(tags)), | ||
| owner = esc(&self.owner), | ||
| name = esc(&self.name), | ||
| home = attr(&self.url("tree", &[])), | ||
| ) | ||
| } | ||
| } | ||
| fn encode(value: &str) -> String { | ||
| value | ||
| .bytes() | ||
| .map(|b| match b { | ||
| b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => (b as char).to_string(), | ||
| _ => format!("%{b:02X}"), | ||
| }) | ||
| .collect() | ||
| } | ||
| /// Branch and tag menu, then the path as breadcrumbs. | ||
| fn locator(&self, view: &str, reference: &str, path: &str) -> String { | ||
| let item = |name: &String| { | ||
| let current = if name == reference { r#" aria-current="true""# } else { "" }; | ||
| let href = self.url(view, &[("ref", name), ("path", path)]); | ||
| format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(name)) | ||
| }; | ||
| let branches: String = self.list_refs("refs/heads").iter().map(item).collect(); | ||
| let tags: String = self.list_refs("refs/tags").iter().map(item).collect(); | ||
| let mut menu = format!("<h2>Branches</h2>{branches}"); | ||
| if !tags.is_empty() { | ||
| menu += &format!("<h2>Tags</h2>{tags}"); | ||
| } | ||
| let mut crumbs = String::new(); | ||
| if path.is_empty() { | ||
| let _ = write!(crumbs, "<b>{}</b>", esc(&self.name)); | ||
| } else { | ||
| let _ = write!(crumbs, r#"<a href="{}">{}</a>"#, attr(&self.url("tree", &[("ref", reference)])), esc(&self.name)); | ||
| let parts: Vec<&str> = path.split('/').collect(); | ||
| for (i, part) in parts.iter().enumerate() { | ||
| crumbs += r#"<span class="sep">/</span>"#; | ||
| if i + 1 == parts.len() { | ||
| let _ = write!(crumbs, "<b>{}</b>", esc(part)); | ||
| } else { | ||
| let href = self.url("tree", &[("ref", reference), ("path", &parts[..=i].join("/"))]); | ||
| let _ = write!(crumbs, r#"<a href="{}">{}</a>"#, attr(&href), esc(part)); | ||
| } | ||
| } | ||
| } | ||
| format!( | ||
| r#"<div class="locator"><details class="refmenu"><summary>{}{}{}</summary><div class="menu">{menu}</div></details> | ||
| <nav class="crumbs" aria-label="Path">{crumbs}</nav></div>"#, | ||
| icon("branch"), | ||
| esc(reference), | ||
| icon("chevron"), | ||
| ) | ||
| } | ||
| /// A repository-relative path with no `..`, empty or absolute parts. | ||
| fn clean_path(value: &str) -> Option<String> { | ||
| let parts: Vec<&str> = value.split('/').filter(|p| !p.is_empty()).collect(); | ||
| if parts.iter().any(|p| *p == "." || *p == ".." || p.contains('\0')) { | ||
| return None; | ||
| fn sha_link(&self, oid: &str) -> String { | ||
| format!(r#"<a class="sha" href="{}">{}</a>"#, attr(&self.url("commit", &[("id", oid)])), &oid[..oid.len().min(7)]) | ||
| } | ||
| Some(parts.join("/")) | ||
| } | ||
| fn page(title: &str, body: &str) -> String { | ||
| format!( | ||
| "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\ | ||
| <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\ | ||
| <title>{} · GITv</title><link rel=\"stylesheet\" href=\"/style.css\"></head><body>{body}</body></html>", | ||
| esc(title) | ||
| ) | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Views | ||
| fn sorted_dir(path: &std::path::Path) -> Vec<String> { | ||
| let mut names: Vec<String> = std::fs::read_dir(path) | ||
| .into_iter() | ||
| .flatten() | ||
| .flatten() | ||
| .filter_map(|e| e.file_name().into_string().ok()) | ||
| .filter(|n| !n.starts_with('.')) | ||
| .collect(); | ||
| names.sort(); | ||
| names | ||
| } | ||
| fn view_index() -> View { | ||
| @@ -176,59 +354,46 @@ fn view_index() -> View { | ||
| let Some(name) = entry.strip_suffix(".git") else { continue }; | ||
| let Some(repo) = Repo::open(&owner, name) else { continue }; | ||
| let head = repo.latest(&repo.default_ref()); | ||
| let stamp: i64 = head.as_ref().and_then(|h| h[3].parse().ok()).unwrap_or(0); | ||
| rows.push((stamp, repo, head)); | ||
| rows.push((head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0), repo, head)); | ||
| } | ||
| } | ||
| rows.sort_by(|a, b| b.0.cmp(&a.0)); | ||
| let items: String = rows | ||
| .iter() | ||
| .map(|(_, repo, head)| { | ||
| let last = head.as_ref().map_or("No commits yet".into(), |h| esc(&h[1]).into_owned()); | ||
| format!("<li><a href=\"{}\">{}/{}</a> — {last}</li>", | ||
| attr(&repo.url("tree", &[])), esc(&repo.owner), esc(&repo.name)) | ||
| let (last, when) = head.as_ref().map_or(("No commits yet".into(), String::new()), |h| { | ||
| (esc(&h.subject).into_owned(), ago(&h.stamp, &h.date)) | ||
| }); | ||
| format!( | ||
| r#"<li><a class="repo-row" href="{}"><span class="rname"><span>{}/</span>{}</span><span class="rlast">{last}</span><span class="rwhen">{when}</span></a></li>"#, | ||
| attr(&repo.url("tree", &[])), esc(&repo.owner), esc(&repo.name) | ||
| ) | ||
| }) | ||
| .collect(); | ||
| let listing = if items.is_empty() { | ||
| format!("<p>No repositories yet. Push to a new name and GITv creates it:</p>\ | ||
| <pre>git push git@{HOST}:um9i/my-project.git main</pre>") | ||
| format!(r#"<div class="panel empty"><h2>No repositories yet</h2><p>Push to a new name and GITv creates the repository.</p> | ||
| <code>git push git@{HOST}:um9i/my-project.git main</code></div>"#) | ||
| } else { | ||
| format!("<ul>{items}</ul>") | ||
| format!(r#"<div class="panel"><ul class="rows">{items}</ul></div>"#) | ||
| }; | ||
| View::Html(page("Repositories", &format!("<h1>GITv repositories ({})</h1>{listing}", rows.len()))) | ||
| } | ||
| fn sorted_dir(path: &std::path::Path) -> Vec<String> { | ||
| let mut names: Vec<String> = std::fs::read_dir(path) | ||
| .into_iter() | ||
| .flatten() | ||
| .flatten() | ||
| .filter_map(|e| e.file_name().into_string().ok()) | ||
| .filter(|n| !n.starts_with('.')) | ||
| .collect(); | ||
| names.sort(); | ||
| names | ||
| let count = plural(rows.len(), "repository", "repositories"); | ||
| View::Html(page("Repositories", &format!( | ||
| r#"<div class="pagehead"><h1 class="title">Repositories</h1><p class="count">{count}</p></div>{listing}"#))) | ||
| } | ||
| fn view_tree(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref()); | ||
| let path = clean_path(q.get("path").map_or("", String::as_str))?; | ||
| let mut body = repo.header(); | ||
| let Some(commit) = repo.resolve(&reference) else { | ||
| // An empty repository has no commits to show yet. | ||
| if repo.git(&["for-each-ref", "--count=1", "refs/heads"]).is_some_and(|s| s.trim().is_empty()) { | ||
| body += "<p>This repository is empty. Push a branch to get started.</p>"; | ||
| return Some(View::Html(page(&repo.name, &body))); | ||
| if !repo.list_refs("refs/heads").is_empty() { | ||
| return None; | ||
| } | ||
| return None; | ||
| let body = repo.masthead("tree", &reference) + &format!( | ||
| r#"<div class="panel empty"><h2>This repository is empty</h2><p>Push a branch to get started.</p> | ||
| <code>git push git@{HOST}:{}/{}.git main</code></div>"#, esc(&repo.owner), esc(&repo.name)); | ||
| return Some(View::Html(page(&format!("{}/{}", repo.owner, repo.name), &body))); | ||
| }; | ||
| let spec = format!("{commit}:{path}"); | ||
| let listing = repo.git(&["ls-tree", "-z", &spec])?; | ||
| body += &format!("<p>Ref: <b>{}</b> · Path: /{}</p>", esc(&reference), esc(&path)); | ||
| if !path.is_empty() { | ||
| let parent = path.rsplit_once('/').map_or("", |(p, _)| p); | ||
| body += &format!("<p><a href=\"{}\">..</a></p>", attr(&repo.url("tree", &[("ref", &reference), ("path", parent)]))); | ||
| } | ||
| let listing = repo.git(&["ls-tree", "-z", &format!("{commit}:{path}")])?; | ||
| let mut entries: Vec<(bool, String)> = listing | ||
| .split('\0') | ||
| .filter_map(|line| { | ||
| @@ -236,28 +401,60 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> { | ||
| Some((meta.split(' ').nth(1)? == "tree", name.to_string())) | ||
| }) | ||
| .collect(); | ||
| entries.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); | ||
| body += "<ul>"; | ||
| entries.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.to_lowercase().cmp(&b.1.to_lowercase()))); | ||
| let mut body = repo.masthead("tree", &reference) + &repo.locator("tree", &reference, &path); | ||
| body += r#"<div class="panel">"#; | ||
| let path_arg: Vec<&str> = if path.is_empty() { vec![] } else { vec![path.as_str()] }; | ||
| let mut args = vec!["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", commit.as_str(), "--"]; | ||
| args.extend(path_arg); | ||
| if let Some(head) = repo.git(&args).and_then(|out| { | ||
| let f: Vec<String> = out.trim_end().split('\x1f').map(String::from).collect(); | ||
| let [oid, subject, author, stamp, date] = <[String; 5]>::try_from(f).ok()?; | ||
| Some(Head { oid, subject, author, stamp, date }) | ||
| }) { | ||
| let _ = write!(body, | ||
| r#"<div class="panel-head"><div class="lead"><b class="who">{}</b><a class="subject" href="{}">{}</a></div><div class="side">{}<span>{}</span></div></div>"#, | ||
| esc(&head.author), attr(&repo.url("commit", &[("id", &head.oid)])), esc(&head.subject), | ||
| repo.sha_link(&head.oid), ago(&head.stamp, &head.date)); | ||
| } | ||
| body += r#"<ul class="rows">"#; | ||
| if !path.is_empty() { | ||
| let up = repo.url("tree", &[("ref", &reference), ("path", parent_of(&path))]); | ||
| let _ = write!(body, r#"<li><a class="entry" href="{}">{}<span class="name">..</span></a></li>"#, attr(&up), icon("up")); | ||
| } | ||
| for (is_dir, name) in &entries { | ||
| let full = if path.is_empty() { name.clone() } else { format!("{path}/{name}") }; | ||
| let view = if *is_dir { "tree" } else { "blob" }; | ||
| let (view, class, glyph) = if *is_dir { ("tree", "entry dir", "dir") } else { ("blob", "entry", "file") }; | ||
| let href = repo.url(view, &[("ref", &reference), ("path", &full)]); | ||
| body += &format!("<li><a href=\"{}\">{}{}</a></li>", attr(&href), esc(name), if *is_dir { "/" } else { "" }); | ||
| let _ = write!(body, r#"<li><a class="{class}" href="{}">{}<span class="name">{}</span></a></li>"#, | ||
| attr(&href), icon(glyph), esc(name)); | ||
| } | ||
| body += "</ul>"; | ||
| body += "</ul></div>"; | ||
| let readme = entries.iter().find(|(d, n)| !d && n.to_ascii_lowercase().starts_with("readme")); | ||
| if let Some((_, readme)) = readme { | ||
| let full = if path.is_empty() { readme.clone() } else { format!("{path}/{readme}") }; | ||
| if let Some(text) = repo.git(&["cat-file", "blob", &format!("{commit}:{full}")]) { | ||
| body += &format!("<h2>{}</h2>", esc(readme)); | ||
| body += &if render::is_markdown(readme) { | ||
| format!("<article class=\"markdown\">{}</article>", repo.markdown(&text, &path, &reference)) | ||
| let content = if render::is_markdown(readme) { | ||
| format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, &path, &reference)) | ||
| } else { | ||
| format!("<pre class=\"code\">{}</pre>", render::highlight(readme, &text)) | ||
| code_view(readme, &text) | ||
| }; | ||
| let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#, | ||
| icon("book"), esc(readme)); | ||
| } | ||
| } | ||
| Some(View::Html(page(&repo.name, &body))) | ||
| let title = if path.is_empty() { format!("{}/{}", repo.owner, repo.name) } else { format!("{path} at {reference}") }; | ||
| Some(View::Html(page(&title, &body))) | ||
| } | ||
| /// Highlighted source with a line-number gutter. | ||
| fn code_view(path: &str, text: &str) -> String { | ||
| let lines = text.lines().count().max(1); | ||
| let gutter: String = (1..=lines).map(|n| format!("{n}\n")).collect(); | ||
| format!(r#"<div class="code-view"><pre class="gutter" aria-hidden="true">{gutter}</pre><pre class="code">{}</pre></div>"#, | ||
| render::highlight(path, text)) | ||
| } | ||
| fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { | ||
| @@ -282,36 +479,34 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { | ||
| }; | ||
| return Some(View::Raw(data.into_iter().take(RAW_LIMIT).collect(), kind)); | ||
| } | ||
| let as_code = q.get("view").is_some_and(|v| v == "code"); | ||
| let parent = path.rsplit_once('/').map_or("", |(p, _)| p); | ||
| let mut body = repo.header(); | ||
| body += &format!( | ||
| "<p>Ref: <b>{}</b> · <a href=\"{}\">{}/</a>{} · {} bytes · <a href=\"{}\">raw</a></p>", | ||
| esc(&reference), | ||
| attr(&repo.url("tree", &[("ref", &reference), ("path", parent)])), | ||
| esc(parent), | ||
| esc(path.rsplit('/').next().unwrap_or(&path)), | ||
| data.len(), | ||
| attr(&repo.url("raw", &[("ref", &reference), ("path", &path)])), | ||
| ); | ||
| let text = String::from_utf8_lossy(&data); | ||
| if binary { | ||
| body += "<p>Binary file not shown.</p>"; | ||
| } else if render::is_markdown(&path) { | ||
| let toggle = |label: &str, view: &str| { | ||
| format!("<a href=\"{}\">{label}</a>", attr(&repo.url("blob", &[("ref", &reference), ("path", &path), ("view", view)]))) | ||
| let markdown = !binary && render::is_markdown(&path); | ||
| let as_code = !markdown || q.get("view").is_some_and(|v| v == "code"); | ||
| let mut side = String::new(); | ||
| if markdown { | ||
| let link = |label: &str, view: &str, on: bool| { | ||
| let current = if on { r#" aria-current="true""# } else { "" }; | ||
| let href = repo.url("blob", &[("ref", &reference), ("path", &path), ("view", view)]); | ||
| format!(r#"<a href="{}"{current}>{label}</a>"#, attr(&href)) | ||
| }; | ||
| if as_code { | ||
| body += &format!("<p>{} · <b>Code</b></p><pre class=\"code\">{}</pre>", | ||
| toggle("Preview", ""), render::highlight(&path, &text)); | ||
| } else { | ||
| body += &format!("<p><b>Preview</b> · {}</p><article class=\"markdown\">{}</article>", | ||
| toggle("Code", "code"), repo.markdown(&text, parent, &reference)); | ||
| } | ||
| } else { | ||
| body += &format!("<pre class=\"code\">{}</pre>", render::highlight(&path, &text)); | ||
| let _ = write!(side, r#"<span class="segmented">{}{}</span>"#, link("Preview", "", !as_code), link("Code", "code", as_code)); | ||
| } | ||
| Some(View::Html(page(&path, &body))) | ||
| let _ = write!(side, r#"<a class="button" href="{}">Raw</a>"#, attr(&repo.url("raw", &[("ref", &reference), ("path", &path)]))); | ||
| let facts = if binary { size(data.len()) } else { | ||
| format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(data.len())) | ||
| }; | ||
| let content = if binary { | ||
| r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#.to_string() | ||
| } else if as_code { | ||
| code_view(&path, &text) | ||
| } else { | ||
| format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, parent_of(&path), &reference)) | ||
| }; | ||
| let body = repo.masthead("tree", &reference) + &repo.locator("blob", &reference, &path) + &format!( | ||
| r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b><span class="quiet">{facts}</span></div><div class="side">{side}</div></div>{content}</section>"#, | ||
| icon("file"), esc(file_name(&path))); | ||
| Some(View::Html(page(&format!("{path} at {reference}"), &body))) | ||
| } | ||
| fn view_log(repo: &Repo, q: &Q) -> Option<View> { | ||
| @@ -320,60 +515,171 @@ fn view_log(repo: &Repo, q: &Q) -> Option<View> { | ||
| let commit = repo.resolve(&reference)?; | ||
| let out = repo.git(&[ | ||
| "log", &format!("-n{}", PAGE + 1), &format!("--skip={}", number * PAGE), | ||
| "--format=%H%x1f%h%x1f%s%x1f%an%x1f%ad", "--date=short", &commit, "--", | ||
| "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", &commit, "--", | ||
| ])?; | ||
| let lines: Vec<&str> = out.lines().collect(); | ||
| let mut body = repo.header() + &format!("<h2>Commits on {}</h2><ul>", esc(&reference)); | ||
| let tags = repo.tags_by_commit(); | ||
| let mut rows = String::new(); | ||
| for line in lines.iter().take(PAGE) { | ||
| let f: Vec<&str> = line.split('\x1f').collect(); | ||
| if f.len() != 5 { | ||
| let Ok([oid, subject, author, stamp, date]) = <[&str; 5]>::try_from(line.split('\x1f').collect::<Vec<_>>()) else { | ||
| continue; | ||
| } | ||
| body += &format!("<li><a href=\"{}\"><code>{}</code></a> {} — {} on {}</li>", | ||
| attr(&repo.url("commit", &[("id", f[0])])), f[1], esc(f[2]), esc(f[3]), esc(f[4])); | ||
| } | ||
| body += "</ul><p>"; | ||
| let page_str = |n: usize| n.to_string(); | ||
| if number > 0 { | ||
| body += &format!("<a href=\"{}\">Newer</a> ", attr(&repo.url("log", &[("ref", &reference), ("page", &page_str(number - 1))]))); | ||
| }; | ||
| let chips: String = tags.get(oid).into_iter().flatten().map(|t| { | ||
| format!(r#"<a class="tagchip" href="{}">{}{}</a>"#, attr(&repo.url("tree", &[("ref", t)])), icon("tag"), esc(t)) | ||
| }).collect(); | ||
| let _ = write!(rows, | ||
| r#"<li class="commit-row"><div class="cmain"><a class="csubj" href="{}">{}</a>{chips}<span class="cmeta">{} committed {}</span></div>{}</li>"#, | ||
| attr(&repo.url("commit", &[("id", oid)])), esc(subject), esc(author), ago(stamp, date), repo.sha_link(oid)); | ||
| } | ||
| let mut pager = String::new(); | ||
| let page_link = |n: usize, label: &str| { | ||
| format!(r#"<a class="button" href="{}">{label}</a>"#, attr(&repo.url("log", &[("ref", &reference), ("page", &n.to_string())]))) | ||
| }; | ||
| pager += &if number > 0 { page_link(number - 1, "Newer") } else { "<span></span>".into() }; | ||
| if lines.len() > PAGE { | ||
| body += &format!("<a href=\"{}\">Older</a>", attr(&repo.url("log", &[("ref", &reference), ("page", &page_str(number + 1))]))); | ||
| pager += &page_link(number + 1, "Older"); | ||
| } | ||
| let body = repo.masthead("log", &reference) + &repo.locator("log", &reference, "") + &format!( | ||
| r#"<div class="panel"><ul class="rows">{rows}</ul></div><nav class="pager" aria-label="Pages">{pager}</nav>"#); | ||
| Some(View::Html(page(&format!("Commits on {reference}"), &body))) | ||
| } | ||
| struct FileDiff { | ||
| name: String, | ||
| status: &'static str, | ||
| rows: Vec<(&'static str, String, String, String)>, | ||
| added: usize, | ||
| removed: usize, | ||
| binary: bool, | ||
| } | ||
| /// Split `git show` patch output into files of (class, old number, new number, text) rows. | ||
| fn parse_diff(text: &str) -> Vec<FileDiff> { | ||
| let mut files: Vec<FileDiff> = Vec::new(); | ||
| let (mut old, mut new) = (0usize, 0usize); | ||
| for line in text.lines() { | ||
| if let Some(rest) = line.strip_prefix("diff --git ") { | ||
| let name = rest.rsplit_once(" b/").map_or(rest, |(_, b)| b).to_string(); | ||
| files.push(FileDiff { name, status: "", rows: Vec::new(), added: 0, removed: 0, binary: false }); | ||
| continue; | ||
| } | ||
| let Some(file) = files.last_mut() else { continue }; | ||
| let in_hunk = !file.rows.is_empty(); | ||
| if !in_hunk && line.starts_with("new file mode") { | ||
| file.status = "Added"; | ||
| } else if !in_hunk && line.starts_with("deleted file mode") { | ||
| file.status = "Deleted"; | ||
| } else if !in_hunk && line.starts_with("rename from ") { | ||
| file.status = "Renamed"; | ||
| } else if !in_hunk && line.starts_with("Binary files ") { | ||
| file.binary = true; | ||
| } else if line.starts_with("@@") { | ||
| let nums: Vec<usize> = line | ||
| .split_whitespace() | ||
| .skip(1) | ||
| .take(2) | ||
| .map(|r| r.trim_start_matches(['-', '+']).split(',').next().and_then(|n| n.parse().ok()).unwrap_or(0)) | ||
| .collect(); | ||
| (old, new) = (nums.first().copied().unwrap_or(0), nums.get(1).copied().unwrap_or(0)); | ||
| file.rows.push(("hunk", String::new(), String::new(), line.to_string())); | ||
| } else if !in_hunk { | ||
| continue; | ||
| } else if let Some(t) = line.strip_prefix('+') { | ||
| file.rows.push(("add", String::new(), new.to_string(), t.to_string())); | ||
| new += 1; | ||
| file.added += 1; | ||
| } else if let Some(t) = line.strip_prefix('-') { | ||
| file.rows.push(("del", old.to_string(), String::new(), t.to_string())); | ||
| old += 1; | ||
| file.removed += 1; | ||
| } else if let Some(t) = line.strip_prefix(' ') { | ||
| file.rows.push(("ctx", old.to_string(), new.to_string(), t.to_string())); | ||
| old += 1; | ||
| new += 1; | ||
| } | ||
| } | ||
| body += "</p>"; | ||
| Some(View::Html(page(&format!("Commits · {}", repo.name), &body))) | ||
| files | ||
| } | ||
| fn view_commit(repo: &Repo, q: &Q) -> Option<View> { | ||
| let id = q.get("id")?; | ||
| if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) { | ||
| if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { | ||
| return None; | ||
| } | ||
| let commit = repo.resolve(id)?; | ||
| let show = repo.git(&["show", "--no-color", "--format=commit %H%nAuthor: %an <%ae>%nDate: %aD%n%n%B", "--patch", "--stat", &commit])?; | ||
| let body = repo.header() + &format!("<pre class=\"code\">{}</pre>", render::highlight("commit.diff", &show)); | ||
| Some(View::Html(page(&format!("Commit {}", &commit[..12]), &body))) | ||
| let meta = repo.git(&["show", "-s", "--date=format:%-d %b %Y, %H:%M", | ||
| "--format=%H%x1f%P%x1f%an%x1f%ae%x1f%ad%x1f%s%x1f%b", &commit])?; | ||
| let f: Vec<&str> = meta.splitn(7, '\x1f').collect(); | ||
| let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?; | ||
| let patch = git(&repo.path, &["show", "--format=", "--no-color", "-M", "--patch", &commit]).ok()?; | ||
| let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::<Vec<_>>().join(" "); | ||
| let mut body = repo.masthead("log", &repo.default_ref()); | ||
| let message = message.trim(); | ||
| let _ = write!(body, r#"<section class="panel"><div class="cmsg"><h2 class="ctitle">{}</h2>{}</div><dl class="facts"> | ||
| <div><dt>Author</dt><dd>{} <span class="quiet">{}</span></dd></div><div><dt>Date</dt><dd>{}</dd></div> | ||
| <div><dt>Commit</dt><dd><span class="sha">{}</span></dd></div>{}</dl></section>"#, | ||
| esc(subject), | ||
| if message.is_empty() { String::new() } else { format!(r#"<p class="cbody">{}</p>"#, esc(message)) }, | ||
| esc(author), esc(email), esc(date), &oid[..12], | ||
| if parent_links.is_empty() { String::new() } else { format!("<div><dt>Parent</dt><dd>{parent_links}</dd></div>") }); | ||
| if patch.len() > DIFF_LIMIT { | ||
| body += r#"<p class="note">This commit’s changes are too large to show here.</p>"#; | ||
| } else { | ||
| let files = parse_diff(&String::from_utf8_lossy(&patch)); | ||
| let (added, removed) = files.iter().fold((0, 0), |(a, r), f| (a + f.added, r + f.removed)); | ||
| let _ = write!(body, r#"<h2 class="changes">{} changed <span class="plus">+{added}</span><span class="minus">−{removed}</span></h2>"#, | ||
| plural(files.len(), "file", "files")); | ||
| for file in &files { | ||
| let status = if file.status.is_empty() { String::new() } else { format!(r#"<span class="status">{}</span>"#, file.status) }; | ||
| let link = repo.url(if file.status == "Deleted" { "log" } else { "blob" }, &[("ref", oid), ("path", &file.name)]); | ||
| let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<a href="{}"><b>{}</b></a>{status}</div><div class="side"><span class="plus">+{}</span><span class="minus">−{}</span></div></div>"#, | ||
| icon("file"), attr(&link), esc(&file.name), file.added, file.removed); | ||
| if file.binary { | ||
| body += r#"<p class="note">Binary file changed.</p>"#; | ||
| } else if file.rows.is_empty() { | ||
| body += r#"<p class="note">No content changes.</p>"#; | ||
| } else { | ||
| body += r#"<div class="diff-wrap"><table class="diff">"#; | ||
| for (class, o, n, text) in &file.rows { | ||
| if *class == "hunk" { | ||
| let _ = write!(body, r#"<tr class="hunk"><td colspan="3">{}</td></tr>"#, esc(text)); | ||
| } else { | ||
| let sign = match *class { "add" => "+", "del" => "-", _ => " " }; | ||
| let _ = write!(body, r#"<tr class="{class}"><td class="num" data-n="{o}"></td><td class="num" data-n="{n}"></td><td class="line" data-s="{sign}">{}</td></tr>"#, esc(text)); | ||
| } | ||
| } | ||
| body += "</table></div>"; | ||
| } | ||
| body += "</section>"; | ||
| } | ||
| } | ||
| Some(View::Html(page(subject, &body))) | ||
| } | ||
| fn view_tags(repo: &Repo) -> Option<View> { | ||
| let out = repo.git(&["for-each-ref", "--sort=-creatordate", | ||
| "--format=%(refname:short)%1f%(creatordate:short)%1f%(contents:subject)", "refs/tags"])?; | ||
| let mut body = repo.header() + "<h2>Tags</h2><ul>"; | ||
| let mut count = 0; | ||
| "--format=%(refname:short)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:short)%1f%(contents:subject)%1f%(objecttype)", | ||
| "refs/tags"])?; | ||
| let mut rows = String::new(); | ||
| for line in out.lines() { | ||
| let f: Vec<&str> = line.split('\x1f').collect(); | ||
| if f.len() != 3 { | ||
| let Ok([name, direct, peeled, stamp, date, note, kind]) = <[&str; 7]>::try_from(line.split('\x1f').collect::<Vec<_>>()) else { | ||
| continue; | ||
| } | ||
| count += 1; | ||
| body += &format!("<li><a href=\"{}\">{}</a> {} {}</li>", | ||
| attr(&repo.url("tree", &[("ref", f[0])])), esc(f[0]), esc(f[1]), esc(f[2])); | ||
| } | ||
| if count == 0 { | ||
| body += "<li>No tags yet.</li>"; | ||
| }; | ||
| let target = if peeled.is_empty() { direct } else { peeled }; | ||
| let note = if kind == "tag" && !note.is_empty() { format!(r#"<span class="tnote">{}</span>"#, esc(note)) } else { String::new() }; | ||
| let _ = write!(rows, r#"<li class="tag-row"><span class="tname">{}</span>{note}<span class="tmeta">{}{}</span> | ||
| <span class="tacts"><a class="button" href="{}">Browse files</a></span></li>"#, | ||
| esc(name), repo.sha_link(target), ago(stamp, date), attr(&repo.url("tree", &[("ref", name)]))); | ||
| } | ||
| body += "</ul>"; | ||
| Some(View::Html(page(&format!("Tags · {}", repo.name), &body))) | ||
| let listing = if rows.is_empty() { | ||
| r#"<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" && git push origin v1.0.0</code></div>"#.to_string() | ||
| } else { | ||
| format!(r#"<div class="panel"><ul class="rows">{rows}</ul></div>"#) | ||
| }; | ||
| let body = repo.masthead("tags", &repo.default_ref()) + &listing; | ||
| Some(View::Html(page(&format!("Tags in {}/{}", repo.owner, repo.name), &body))) | ||
| } | ||
| fn route(owner: &str, name: &str, view: Option<&str>, q: &Q) -> View { | ||
| @@ -401,10 +707,11 @@ async fn main() { | ||
| let Action::Serve { port } = Cli::parse().action; | ||
| let app = Router::new() | ||
| .route("/", get(|| blocking(view_index))) | ||
| .route("/style.css", get(|| async { | ||
| ([(header::CONTENT_TYPE, "text/css; charset=utf-8"), (header::CACHE_CONTROL, "max-age=3600")], | ||
| STYLESHEET.as_str()) | ||
| })) | ||
| .route("/style.css", get(|| async { static_file("text/css; charset=utf-8", STYLESHEET.as_bytes()) })) | ||
| .route("/favicon.svg", get(|| async { static_file("image/svg+xml", FAVICON.as_bytes()) })) | ||
| .route("/fonts/display.woff2", get(|| async { static_file("font/woff2", FONT_DISPLAY) })) | ||
| .route("/fonts/text.woff2", get(|| async { static_file("font/woff2", FONT_TEXT) })) | ||
| .route("/fonts/mono.woff2", get(|| async { static_file("font/woff2", FONT_MONO) })) | ||
| .route("/{owner}/{name}", get(|Path((o, n)): Path<(String, String)>, Query(q): Query<Q>| | ||
| blocking(move || route(&o, &n, None, &q)))) | ||
| .route("/{owner}/{name}/{view}", get(|Path((o, n, v)): Path<(String, String, String)>, Query(q): Query<Q>| | ||
+3−18
| @@ -1,13 +1,12 @@ | ||
| //! Syntax highlighting and Markdown rendering for the web browser. | ||
| //! | ||
| //! Highlighting emits CSS classes rather than inline styles, so the page's | ||
| //! `style-src 'self'` policy holds; [`stylesheet`] supplies the colours. | ||
| //! Highlighting emits syntect scope classes (`hl-keyword`, `hl-string`, ...) rather than | ||
| //! inline styles, so the page's `style-src 'self'` policy holds; the site stylesheet colours them. | ||
| use std::sync::LazyLock; | ||
| use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd}; | ||
| use syntect::highlighting::ThemeSet; | ||
| use syntect::html::{ClassStyle, ClassedHTMLGenerator, css_for_theme_with_class_style}; | ||
| use syntect::html::{ClassStyle, ClassedHTMLGenerator}; | ||
| use syntect::parsing::{SyntaxReference, SyntaxSet}; | ||
| use syntect::util::LinesWithEndings; | ||
| @@ -18,20 +17,6 @@ const CLASSES: ClassStyle = ClassStyle::SpacedPrefixed { prefix: "hl-" }; | ||
| static SYNTAXES: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines); | ||
| /// Highlighting colours for light and dark schemes. | ||
| pub fn stylesheet() -> String { | ||
| let themes = ThemeSet::load_defaults(); | ||
| let light = css_for_theme_with_class_style(&themes.themes["InspiredGitHub"], CLASSES).unwrap_or_default(); | ||
| let dark = css_for_theme_with_class_style(&themes.themes["base16-ocean.dark"], CLASSES).unwrap_or_default(); | ||
| format!( | ||
| ":root{{color-scheme:light dark}}\n{light}\n@media (prefers-color-scheme:dark){{\n{dark}\n}}\n\ | ||
| pre.code{{padding:8px 12px;overflow:auto}}\n\ | ||
| .markdown table{{border-collapse:collapse}}\n\ | ||
| .markdown th,.markdown td{{border:1px solid #8884;padding:4px 8px}}\n\ | ||
| .markdown img{{max-width:100%}}\n" | ||
| ) | ||
| } | ||
| /// The syntax for a file, by extension, whole file name, then shebang or modeline. | ||
| fn syntax_for(path: &str, first_line: &str) -> Option<&'static SyntaxReference> { | ||
| let file = path.rsplit('/').next().unwrap_or(path); | ||