forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB7aca449Tahinli9 minutes ago336 commits

tree.rs496 lines, 15.7 KiBHistoryRawDownload
1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::time::Duration;
4
5use forge_core::Repo as RepoRow;
6use forge_core::tz::format_in_tz;
7use forge_git::browse::{self, BlobData, CommitInfo, EntryKind, RefInfo, TreeEntry};
8use forge_git::history;
9use topcoat::Result;
10use topcoat::context::{Cx, context};
11use topcoat::router::error::not_found;
12use topcoat::router::{page, path_param};
13use topcoat::view::{Unescaped, View, component, view};
14
15use crate::i18n::code::{self as g, K};
16use crate::i18n::misc::{self as mi, K as MK};
17use crate::i18n::s;
18use crate::i18n::{self, Lang};
19use crate::pages::code_live::{follows_branch, live_url};
20use crate::pages::finder::file_finder;
21use crate::pages::refs::{load_refs, ref_links};
22use crate::pages::repo::repo_head;
23use crate::pages::repo_ctx::load_repo;
24use crate::pages::repo_side::{code_sub, commit_strip, run_pips, run_rows, tree_facts};
25use crate::raw::raw_url;
26use crate::render::emoji::emojify;
27use crate::render::markdown::{LinkContext, render_markdown};
28use crate::state::AppState;
29use crate::views::{
30 display_name, empty_state, iso_time, now_unix, ref_selector, relative_time, repo_href, shell,
31 short_oid,
32};
33
34pub const README_NAMES: [&str; 5] = [
35 "README.md",
36 "readme.md",
37 "README.markdown",
38 "README",
39 "README.txt",
40];
41
42pub const MAX_BLOB_BYTES: usize = 1 << 20;
43const LAST_COMMIT_WALK: usize = 2000;
44const LAST_COMMIT_TIMEOUT: Duration = Duration::from_secs(3);
45
46path_param!(owner);
47path_param!(repo);
48path_param!(*rest);
49
50pub async fn resolve(path: PathBuf, rest: String) -> Result<Option<(String, String, String)>> {
51 Ok(tokio::task::spawn_blocking(move || browse::split_ref_and_path(&path, &rest)).await??)
52}
53
54pub async fn read_dir(
55 path: PathBuf,
56 commit: String,
57 dir: String,
58) -> Result<Option<Vec<TreeEntry>>> {
59 Ok(tokio::task::spawn_blocking(move || browse::read_tree(&path, &commit, &dir)).await??)
60}
61
62pub async fn read_file(path: PathBuf, commit: String, file: String) -> Result<Option<BlobData>> {
63 Ok(tokio::task::spawn_blocking(move || {
64 browse::read_blob(&path, &commit, &file, MAX_BLOB_BYTES)
65 })
66 .await??)
67}
68
69pub async fn last_commits(
70 state: &AppState,
71 path: &Path,
72 commit: &str,
73 dir: &str,
74 names: &[String],
75) -> HashMap<String, CommitInfo> {
76 let walk = history::last_commits(&state.git, path, commit, dir, names, LAST_COMMIT_WALK);
77 match tokio::time::timeout(LAST_COMMIT_TIMEOUT, walk).await {
78 Ok(Ok(map)) => map,
79 Ok(Err(e)) => {
80 tracing::warn!(error = %e, "last-commit walk failed");
81 HashMap::new()
82 }
83 Err(_) => {
84 tracing::warn!("last-commit walk timed out");
85 HashMap::new()
86 }
87 }
88}
89
90fn child_path(dir: &str, name: &str) -> String {
91 if dir.is_empty() {
92 name.to_owned()
93 } else {
94 format!("{dir}/{name}")
95 }
96}
97
98pub struct LastCommit {
99 pub href: String,
100 pub summary: String,
101 pub iso: String,
102 pub absolute: String,
103 pub age: String,
104}
105
106pub struct LatestBar {
107 pub last: LastCommit,
108 pub short: String,
109 pub author: String,
110}
111
112pub async fn latest_bar(
113 state: &AppState,
114 repo: &RepoRow,
115 path: &Path,
116 commit: &str,
117 lang: Lang,
118 tz: &str,
119) -> Option<LatestBar> {
120 let log = tokio::time::timeout(
121 LAST_COMMIT_TIMEOUT,
122 history::log(&state.git, path, commit, None, 0, 1),
123 )
124 .await;
125 let info = match log {
126 Ok(Ok(commits)) => commits.into_iter().next()?,
127 Ok(Err(e)) => {
128 tracing::warn!(error = %e, "latest-commit lookup failed");
129 return None;
130 }
131 Err(_) => {
132 tracing::warn!("latest-commit lookup timed out");
133 return None;
134 }
135 };
136
137 let user = author_account(state, repo, &info.author_email).await;
138 let author = match user {
139 Some(user) => display_name(lang, &user.username),
140 None => info.author_name.clone(),
141 };
142 Some(LatestBar {
143 last: last_commit_view(lang, repo, &info, now_unix(), tz),
144 short: short_oid(&info.oid).to_owned(),
145 author,
146 })
147}
148
149pub struct EntryRow {
150 pub kind: &'static str,
151 pub name: String,
152 pub href: Option<String>,
153 pub short: String,
154 pub last: Option<LastCommit>,
155}
156
157#[allow(clippy::too_many_arguments)]
158pub fn entry_rows(
159 lang: Lang,
160 repo: &RepoRow,
161 ref_name: &str,
162 dir: &str,
163 entries: Vec<TreeEntry>,
164 last: &HashMap<String, CommitInfo>,
165 now: i64,
166 tz: &str,
167) -> Vec<EntryRow> {
168 entries
169 .into_iter()
170 .map(|entry| {
171 let rel = child_path(dir, &entry.name);
172 let (kind, href, short) = match entry.kind {
173 EntryKind::Tree => (
174 "dir",
175 Some(repo_href(
176 &repo.owner_name,
177 &repo.name,
178 "tree",
179 &format!("{ref_name}/{rel}"),
180 )),
181 String::new(),
182 ),
183 EntryKind::Blob => ("file", blob_href(repo, ref_name, &rel), String::new()),
184 EntryKind::Executable => ("exec", blob_href(repo, ref_name, &rel), String::new()),
185 EntryKind::Symlink => ("link", blob_href(repo, ref_name, &rel), String::new()),
186 EntryKind::Submodule => ("submodule", None, short_oid(&entry.oid).to_owned()),
187 };
188 let last = last
189 .get(&entry.name)
190 .map(|c| last_commit_view(lang, repo, c, now, tz));
191 EntryRow {
192 kind,
193 name: entry.name,
194 href,
195 short,
196 last,
197 }
198 })
199 .collect()
200}
201
202pub async fn author_account(
203 state: &AppState,
204 repo: &RepoRow,
205 email: &str,
206) -> Option<forge_core::User> {
207 if let Ok(Some(user)) = state.store.verified_user_by_email(email).await {
208 return Some(user);
209 }
210 let owner = state
211 .store
212 .user_by_id(&repo.owner_id)
213 .await
214 .ok()
215 .flatten()?;
216 let same = owner
217 .email
218 .as_deref()
219 .is_some_and(|own| own.eq_ignore_ascii_case(email));
220 same.then_some(owner)
221}
222
223pub fn last_commit_view(
224 lang: Lang,
225 repo: &RepoRow,
226 commit: &CommitInfo,
227 now: i64,
228 tz: &str,
229) -> LastCommit {
230 LastCommit {
231 href: repo_href(&repo.owner_name, &repo.name, "commit", &commit.oid),
232 summary: emojify(&commit.summary).into_owned(),
233 iso: iso_time(commit.author_time),
234 absolute: format_in_tz(commit.author_time, tz),
235 age: relative_time(lang, commit.author_time, now),
236 }
237}
238
239fn blob_href(repo: &RepoRow, ref_name: &str, rel: &str) -> Option<String> {
240 Some(repo_href(
241 &repo.owner_name,
242 &repo.name,
243 "blob",
244 &format!("{ref_name}/{rel}"),
245 ))
246}
247
248pub fn link_context(state: &AppState, repo: &RepoRow, ref_name: &str, dir: &str) -> LinkContext {
249 let at = |section: &str| {
250 repo_href(
251 &repo.owner_name,
252 &repo.name,
253 section,
254 &format!("{ref_name}/{dir}"),
255 )
256 };
257 LinkContext {
258 tree_base: at("tree"),
259 blob_base: at("blob"),
260 raw_base: raw_url(state, repo, ref_name, dir)
261 .trim_end_matches('/')
262 .to_owned(),
263 issues_base: Some(repo_href(&repo.owner_name, &repo.name, "issues", "")),
264 }
265}
266
267pub struct Readme {
268 pub name: String,
269 pub markdown: bool,
270 pub body: String,
271}
272
273pub async fn load_readme(
274 state: &AppState,
275 repo: &RepoRow,
276 path: &Path,
277 ref_name: &str,
278 commit: &str,
279 dir: &str,
280 entries: &[TreeEntry],
281) -> Result<Option<Readme>> {
282 let found = README_NAMES.iter().find_map(|wanted| {
283 entries.iter().find(|e| {
284 e.name == *wanted && matches!(e.kind, EntryKind::Blob | EntryKind::Executable)
285 })
286 });
287 let Some(found) = found else {
288 return Ok(None);
289 };
290 let name = found.name.clone();
291 let file = child_path(dir, &name);
292 let Some(blob) = read_file(path.to_path_buf(), commit.to_owned(), file).await? else {
293 return Ok(None);
294 };
295 if blob.is_binary {
296 return Ok(None);
297 }
298 let text = String::from_utf8_lossy(&blob.data).into_owned();
299 if name.ends_with(".md") || name.ends_with(".markdown") {
300 let ctx = link_context(state, repo, ref_name, dir);
301 Ok(Some(Readme {
302 name,
303 markdown: true,
304 body: render_markdown(&text, Some(&ctx)),
305 }))
306 } else {
307 Ok(Some(Readme {
308 name,
309 markdown: false,
310 body: text,
311 }))
312 }
313}
314
315#[component]
316pub async fn tree_table(
317 cx: &Cx,
318 rows: Vec<EntryRow>,
319 lang: Lang,
320 #[default] current: Option<String>,
321) -> Result<impl View> {
322 Ok(view! {
323 <div class="rail-list tree-list">
324 for row in rows.into_iter() {
325 if let Some(href) = row.href {
326 <a class="rail-item tree-entry" href=(href) data-kb-row="" aria-current=((current.as_deref() == Some(row.name.as_str())).then_some("page"))>
327 <span class="sr-only">(g::kind_label(lang, row.kind))</span>
328 <span class="nm dir">(row.name)if row.kind == "dir" { "/" }</span>
329 if let Some(last) = row.last {
330 <time class="val" data-rel="true" datetime=(last.iso) title=(last.absolute)>(last.age)</time>
331 }
332 </a>
333 } else {
334 <div class="rail-item tree-entry" data-kb-row="">
335 <span class="sr-only">(g::kind_label(lang, row.kind))</span>
336 <span class="nm dir">(row.name)</span>
337 <span class="val">(row.short)</span>
338 </div>
339 }
340 }
341 </div>
342 })
343}
344
345#[component]
346pub async fn readme_sheet(
347 cx: &Cx,
348 lang: Lang,
349 owner: String,
350 repo: String,
351 ref_name: String,
352 dir: String,
353 readme: Option<Readme>,
354 none: &str,
355) -> Result<impl View> {
356 let readme_name = readme.as_ref().map(|readme| readme.name.clone());
357 let links = readme.as_ref().map(|readme| {
358 let path = if dir.is_empty() {
359 readme.name.clone()
360 } else {
361 format!("{dir}/{}", readme.name)
362 };
363 let target = format!("{ref_name}/{path}");
364 (
365 repo_href(&owner, &repo, "blob", &target),
366 repo_href(&owner, &repo, "commits", &target),
367 repo_href(&owner, &repo, "raw", &target),
368 )
369 });
370 let shown = readme_name.unwrap_or_else(|| {
371 if dir.is_empty() {
372 repo.clone()
373 } else {
374 dir.clone()
375 }
376 });
377 Ok(view! {
378 <div class="sheet">
379 <div class="sheet-tools">
380 <strong>(shown)</strong>
381 if let Some((source, history, raw)) = links {
382 <a class="act" href=(source)>(s(lang, "Source", "Kaynak"))</a>
383 <a class="act" href=(history)>(s(lang, "History", "Geçmiş"))</a>
384 <a class="act" href=(raw)>(s(lang, "Raw", "Ham"))</a>
385 }
386 </div>
387 if let Some(readme) = readme {
388 readme_card(name: readme.name, markdown: readme.markdown, body: readme.body)
389 } else {
390 empty_state(title: none)
391 }
392 </div>
393 })
394}
395
396#[component]
397pub async fn readme_card(cx: &Cx, name: String, markdown: bool, body: String) -> Result<impl View> {
398 Ok(view! {
399 <section class="readme">
400 <p class="sr-only">(name)</p>
401 if markdown {
402 <div class="markdown-body">(Unescaped::new_unchecked(body))</div>
403 } else {
404 <pre class="readme-text">(body)</pre>
405 }
406 </section>
407 })
408}
409
410#[page("/{owner}/{repo}/tree/{*rest}")]
411async fn tree_page(cx: &Cx) -> Result<impl View> {
412 let owner = owner(cx);
413 let name = repo(cx);
414 let rest = rest(cx).collect::<Vec<_>>().join("/");
415 let ctx = load_repo(cx, owner, name).await?;
416 let state = context::<AppState>(cx);
417 let lang = i18n::lang(cx, ctx.viewer_user());
418 let repo = &ctx.repo;
419
420 let Some((ref_name, commit, dir)) = resolve(ctx.path.clone(), rest).await? else {
421 return Err(not_found().into());
422 };
423 let Some(entries) = read_dir(ctx.path.clone(), commit.clone(), dir.clone()).await? else {
424 return Err(not_found().into());
425 };
426 let names: Vec<String> = entries.iter().map(|e| e.name.clone()).collect();
427 let root_names: Vec<String> = if dir.is_empty() {
428 names.clone()
429 } else {
430 read_dir(ctx.path.clone(), commit.clone(), String::new())
431 .await?
432 .unwrap_or_default()
433 .into_iter()
434 .map(|e| e.name)
435 .collect()
436 };
437 let (last, bar, strip, runs) = tokio::join!(
438 last_commits(state, &ctx.path, &commit, &dir, &names),
439 latest_bar(state, repo, &ctx.path, &commit, lang, ctx.viewer_tz()),
440 commit_strip(state, repo, &ctx.path, &commit),
441 run_rows(state, lang, repo),
442 );
443 let runs = runs?;
444 let facts = tree_facts(state, repo, &ctx.path, &commit, &root_names).await?;
445 let pips = run_pips(&runs);
446 let sub = code_sub(lang, bar, Some(facts), None, Vec::new(), strip.total);
447 let refs: Vec<RefInfo> = load_refs(ctx.path.clone()).await?;
448 let readme = load_readme(state, repo, &ctx.path, &ref_name, &commit, &dir, &entries).await?;
449 let rows = entry_rows(
450 lang,
451 repo,
452 &ref_name,
453 &dir,
454 entries,
455 &last,
456 now_unix(),
457 ctx.viewer_tz(),
458 );
459 let (branches, tags) = ref_links(&refs, &ref_name, &repo.default_branch, repo);
460 let branches_href = repo_href(&repo.owner_name, &repo.name, "branches", "");
461 let tags_href = repo_href(&repo.owner_name, &repo.name, "tags", "");
462 let live = follows_branch(&refs, &ref_name)
463 .then(|| live_url(&repo.owner_name, &repo.name, &refs, &ref_name));
464
465 let title = ctx.title();
466 let finder_owner = repo.owner_name.clone();
467 let finder_repo = repo.name.clone();
468 let dock_owner = finder_owner.clone();
469 let dock_repo = finder_repo.clone();
470 let finder_ref = ref_name.clone();
471 let code_search_href = repo_href(&repo.owner_name, &repo.name, "search", "");
472 let readme_file = readme.as_ref().map(|readme| readme.name.clone());
473 let mut header = ctx.head(state, "code").await?;
474 if let Some(url) = &live {
475 header.live = url.clone();
476 }
477 Ok(view! {
478 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
479 repo_head(head: header, sub: sub, pips: pips)
480 <div class="work">
481 <nav class="rail" aria-label=(s(lang, "Files", "Dosyalar"))>
482 <div class="rail-head browse-bar" data-live=(live.as_deref()) data-live-code=(live.is_some().then_some("true")) data-live-gone=(g::t(lang, K::LivePathGone))>
483 <h2>(s(lang, "Files", "Dosyalar"))</h2>
484 ref_selector(lang: lang, label: mi::t(lang, MK::RefLabel), current: ref_name.clone(), branches: branches, tags: tags,
485 branches_href: branches_href, tags_href: tags_href)
486 <a class="act code-search-act" href=(code_search_href)>(g::t(lang, K::SearchCodePlaceholder))</a>
487 file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref)
488 </div>
489 tree_table(rows: rows, lang: lang, current: readme_file)
490 </nav>
491 readme_sheet(lang: lang, owner: dock_owner, repo: dock_repo, ref_name: ref_name.clone(), dir: dir.clone(), readme: readme,
492 none: s(lang, "No README in this folder", "Bu klasörde README yok"))
493 </div>
494 )
495 })
496}