1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
mod archive;
mod blob;
mod commit;
mod compare;
mod index;
mod log;
mod tags;
mod tree;
use std::ffi::OsStr;
use std::fmt::Write as _;
use std::os::unix::ffi::OsStrExt;
use std::time::Instant;
use gitv_core::{RepoDir, config, repo_dir};
use gitv_web::render;
use crate::html::{ago, icon, subject_or_placeholder};
use crate::repository::Reader;
use crate::urls::{Q, encode, lossy};
use crate::{View, templates};
use archive::view_archive;
use blob::view_blob;
use commit::view_commit;
use compare::view_compare;
use log::view_log;
use tags::view_tags;
use tree::view_tree;
pub(crate) use commit::FileDiff;
pub(crate) use index::view_index;
pub(crate) const PAGE: usize = 50;
pub(crate) const RAW_LIMIT: usize = 50 << 20;
pub(crate) const SHOW_LIMIT: usize = 1 << 20;
pub(crate) const DIFF_LIMIT: usize = 2 << 20;
pub(crate) struct Repo {
pub(crate) signed_in: bool,
pub(crate) owner: String,
pub(crate) name: String,
pub(crate) reader: Reader,
}
impl Repo {
pub(crate) fn open(owner: &str, name: &str) -> Option<Repo> {
let mut dir = repo_dir(owner, name)?;
dir.limit_until(Instant::now() + gitv_core::GIT_TIMEOUT);
Some(Repo::from_dir(owner, name, dir))
}
pub(crate) fn from_dir(owner: &str, name: &str, dir: RepoDir) -> Repo {
Repo { signed_in: false, reader: Reader::new(dir), owner: owner.into(), name: name.into() }
}
pub(crate) fn clone_address(&self) -> (&'static str, String) {
if self.reader.dir.is_public() {
("HTTPS", format!("https://{}/{}/{}", config::host(), self.owner, self.name))
} else {
("SSH", format!("git@{}:{}/{}.git", config::host(), self.owner, self.name))
}
}
pub(crate) 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.as_bytes()))).collect();
let base = format!("/{}/{}/{view}", self.owner, self.name);
if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) }
}
pub(crate) fn reference(&self, q: &Q) -> Vec<u8> {
q.get("ref").cloned().unwrap_or_else(|| self.reader.default_ref())
}
pub(crate) fn url_at(&self, view: &str, reference: &[u8], path: &[u8], extra: &str) -> String {
let mut url = self.url(view, &[]);
if !reference.is_empty() {
let _ = write!(url, "?ref={}", encode(reference));
}
if !path.is_empty() {
url.push(if url.contains('?') { '&' } else { '?' });
let _ = write!(url, "path={}", encode(path));
}
if !extra.is_empty() {
url.push(if url.contains('?') { '&' } else { '?' });
url.push_str(extra);
}
url
}
pub(crate) fn entry_commit(&self, record: &str) -> Option<templates::EntryCommit> {
let mut fields = record.splitn(6, '\0');
let oid = fields.next()?;
let stamp = fields.next()?;
let datetime = fields.next()?;
let full_date = fields.next()?;
let subject = subject_or_placeholder(fields.next()?);
let message = fields.next()?.trim_end();
Some(templates::EntryCommit {
url: self.url("commit", &[("id", oid)]),
subject: subject.into(),
message: if message.is_empty() { subject } else { message }.into(),
when: ago(stamp, full_date.split(',').next().unwrap_or(full_date)),
full_date: full_date.into(),
datetime: datetime.into(),
})
}
pub(crate) fn key(&self, kind: &str, oid: &str, extra: &str) -> String {
format!("{kind}:{}/{}:{oid}:{extra}", self.owner, self.name)
}
pub(crate) fn markdown(&self, source: &str, dir: &[u8], reference: &[u8]) -> String {
render::markdown(source, dir, &|path, image| {
if image {
self.url_at("raw", reference, path, "")
} else if path.is_empty() {
self.url_at("tree", reference, b"", "")
} else {
self.url_at("blob", reference, path, "")
}
})
}
pub(crate) fn masthead(&self, active: &str, reference: &[u8], commit: Option<&str>) -> String {
let commit = commit.map(str::to_string).or_else(|| self.reader.resolve(reference));
let commits = commit.map_or(0, |c| self.reader.commit_count(&c));
let tab = |view: &str, glyph: &str, label: &'static str, count: Option<usize>| templates::Tab {
href: self.url_at(view, if view == "tags" { b"" } else { reference }, b"", ""),
current: view == active,
icon: icon(glyph),
label,
count,
};
let public = self.reader.dir.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", &[]),
visibility: self.signed_in.then_some(if public { "Public" } else { "Private" }),
protected: self.signed_in && self.reader.dir.is_protected(),
description: self.reader.dir.description(),
addresses,
tabs: vec![
tab("tree", "code", "Code", None),
tab("log", "commits", "Commits", Some(commits)),
tab("tags", "tag", "Tags", Some(self.reader.tags().len())),
],
}
.to_string()
}
pub(crate) fn locator(&self, view: &str, reference: &[u8], path: &[u8]) -> String {
let item = |link: Vec<u8>, name: &'_ [u8]| templates::MenuItem {
href: self.url_at(view, &link, path, ""),
current: link == reference,
name: lossy(name).into_owned().into(),
};
let parts: Vec<&[u8]> = if path.is_empty() { Vec::new() } else { path.split(|b| *b == b'/').collect() };
let crumbs = parts
.iter()
.enumerate()
.map(|(i, part)| templates::Crumb {
href: (i + 1 < parts.len()).then(|| self.url_at("tree", reference, &parts[..=i].join(&b'/'), "")),
name: lossy(part),
})
.collect();
let shown = reference
.strip_prefix(b"refs/heads/")
.or_else(|| reference.strip_prefix(b"refs/tags/"))
.unwrap_or(reference);
let pinned = matches!(shown.len(), 40 | 64) && shown.iter().all(u8::is_ascii_hexdigit);
let shown = if pinned { &shown[..12] } else { shown };
templates::Locator {
branch_icon: icon("branch"),
chevron_icon: icon("chevron"),
current: lossy(shown),
branches: self.reader.heads().iter().map(|b| item(self.reader.branch_ref(b), b)).collect(),
tags: self.reader.tags().iter().map(|t| item(self.reader.tag_ref(t), t)).collect(),
root: (!path.is_empty()).then(|| self.url_at("tree", reference, b"", "")),
repo_name: &self.name,
crumbs,
}
.to_string()
}
pub(crate) fn compare_url(&self, from: &[u8], to: &[u8]) -> String {
format!("{}?from={}&to={}", self.url("compare", &[]), encode(from), encode(to))
}
pub(crate) fn sha_link(&self, oid: &str) -> String {
templates::ShaLink { href: self.url("commit", &[("id", oid)]), short: &oid[..oid.len().min(7)] }.to_string()
}
}
pub(crate) struct Entry {
pub(crate) kind: String,
pub(crate) oid: String,
pub(crate) size: usize,
pub(crate) name: Vec<u8>,
}
impl Entry {
pub(crate) fn parse(record: &[u8]) -> Option<Entry> {
let tab = record.iter().position(|b| *b == b'\t')?;
let meta = std::str::from_utf8(&record[..tab]).ok()?;
let mut fields = meta.split_whitespace().skip(1);
let (kind, oid) = (fields.next()?.to_string(), fields.next()?.to_string());
let size = fields.next().and_then(|s| s.parse().ok()).unwrap_or(0);
Some(Entry { kind, oid, size, name: record[tab + 1..].to_vec() })
}
pub(crate) fn list(out: &[u8]) -> Vec<Entry> {
out.split(|b| *b == 0).filter_map(Entry::parse).collect()
}
}
pub(crate) fn entry(repo: &Repo, commit: &str, path: &[u8]) -> Option<Entry> {
let args = [
OsStr::new("ls-tree"),
OsStr::new("-l"),
OsStr::new("-z"),
OsStr::new(commit),
OsStr::new("--"),
OsStr::from_bytes(path),
];
let out = repo.reader.git_bytes(&args)?;
Entry::list(&out).into_iter().find(|e| e.name == path)
}
pub(crate) fn route(owner: &str, name: &str, view: Option<&str>, q: &Q, signed_in: bool) -> View {
let Some(mut repo) = Repo::open(owner, name) else {
return if signed_in { View::Missing(true) } else { View::LoginRequired };
};
if !signed_in && !repo.reader.dir.is_public() {
return View::LoginRequired;
}
repo.signed_in = signed_in;
let result = match view {
None => Some(View::Redirect(repo.url("tree", &[]))),
Some("tree") => view_tree(&repo, q),
Some("blob") => view_blob(&repo, q, false),
Some("raw") => view_blob(&repo, q, true),
Some("archive") => view_archive(&repo, q),
Some("log") => view_log(&repo, q),
Some("commit") => view_commit(&repo, q),
Some("compare") => view_compare(&repo, q),
Some("tags") => view_tags(&repo),
Some(_) => None,
};
result.unwrap_or(View::Missing(signed_in))
}