use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::Duration; use forge_core::Repo as RepoRow; use forge_core::tz::format_in_tz; use forge_git::browse::{self, BlobData, CommitInfo, EntryKind, RefInfo, TreeEntry}; use forge_git::history; use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::error::not_found; use topcoat::router::{page, path_param}; use topcoat::view::{Unescaped, View, component, view}; use crate::i18n::code::{self as g, K}; use crate::i18n::misc::{self as mi, K as MK}; use crate::i18n::s; use crate::i18n::{self, Lang}; use crate::pages::code_live::{follows_branch, live_url}; use crate::pages::finder::file_finder; use crate::pages::refs::{load_refs, ref_links}; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; use crate::pages::repo_side::{code_sub, commit_strip, run_pips, run_rows, tree_facts}; use crate::raw::raw_url; use crate::render::emoji::emojify; use crate::render::markdown::{LinkContext, render_markdown}; use crate::state::AppState; use crate::views::{ display_name, empty_state, iso_time, now_unix, ref_selector, relative_time, repo_href, shell, short_oid, }; pub const README_NAMES: [&str; 5] = [ "README.md", "readme.md", "README.markdown", "README", "README.txt", ]; pub const MAX_BLOB_BYTES: usize = 1 << 20; const LAST_COMMIT_WALK: usize = 10_000; const LAST_COMMIT_TIMEOUT: Duration = Duration::from_secs(3); path_param!(owner); path_param!(repo); path_param!(*rest); pub async fn resolve(path: PathBuf, rest: String) -> Result> { Ok(tokio::task::spawn_blocking(move || browse::split_ref_and_path(&path, &rest)).await??) } pub async fn read_dir( path: PathBuf, commit: String, dir: String, ) -> Result>> { Ok(tokio::task::spawn_blocking(move || browse::read_tree(&path, &commit, &dir)).await??) } pub async fn read_file(path: PathBuf, commit: String, file: String) -> Result> { Ok(tokio::task::spawn_blocking(move || { browse::read_blob(&path, &commit, &file, MAX_BLOB_BYTES) }) .await??) } pub async fn last_commits( path: &Path, commit: &str, dir: &str, names: &[String], ) -> HashMap { let walk = history::last_commits(path, commit, dir, names, LAST_COMMIT_WALK); match tokio::time::timeout(LAST_COMMIT_TIMEOUT, walk).await { Ok(Ok(map)) => map, Ok(Err(e)) => { tracing::warn!(error = %e, "last-commit walk failed"); HashMap::new() } Err(_) => { tracing::warn!("last-commit walk timed out"); HashMap::new() } } } fn child_path(dir: &str, name: &str) -> String { if dir.is_empty() { name.to_owned() } else { format!("{dir}/{name}") } } pub struct LastCommit { pub href: String, pub summary: String, pub iso: String, pub absolute: String, pub age: String, } pub struct LatestBar { pub last: LastCommit, pub short: String, pub author: String, } pub async fn latest_bar( state: &AppState, repo: &RepoRow, path: &Path, commit: &str, lang: Lang, tz: &str, ) -> Option { let log = tokio::time::timeout( LAST_COMMIT_TIMEOUT, history::log(&state.git, path, commit, None, 0, 1), ) .await; let info = match log { Ok(Ok(commits)) => commits.into_iter().next()?, Ok(Err(e)) => { tracing::warn!(error = %e, "latest-commit lookup failed"); return None; } Err(_) => { tracing::warn!("latest-commit lookup timed out"); return None; } }; let user = author_account(state, repo, &info.author_email).await; let author = match user { Some(user) => display_name(lang, &user.username), None => info.author_name.clone(), }; Some(LatestBar { last: last_commit_view(lang, repo, &info, now_unix(), tz), short: short_oid(&info.oid).to_owned(), author, }) } pub struct EntryRow { pub kind: &'static str, pub name: String, pub href: Option, pub short: String, pub last: Option, } #[allow(clippy::too_many_arguments)] pub fn entry_rows( lang: Lang, repo: &RepoRow, ref_name: &str, dir: &str, entries: Vec, last: &HashMap, now: i64, tz: &str, ) -> Vec { entries .into_iter() .map(|entry| { let rel = child_path(dir, &entry.name); let (kind, href, short) = match entry.kind { EntryKind::Tree => ( "dir", Some(repo_href( &repo.owner_name, &repo.name, "tree", &format!("{ref_name}/{rel}"), )), String::new(), ), EntryKind::Blob => ("file", blob_href(repo, ref_name, &rel), String::new()), EntryKind::Executable => ("exec", blob_href(repo, ref_name, &rel), String::new()), EntryKind::Symlink => ("link", blob_href(repo, ref_name, &rel), String::new()), EntryKind::Submodule => ("submodule", None, short_oid(&entry.oid).to_owned()), }; let last = last .get(&entry.name) .map(|c| last_commit_view(lang, repo, c, now, tz)); EntryRow { kind, name: entry.name, href, short, last, } }) .collect() } pub async fn author_account( state: &AppState, repo: &RepoRow, email: &str, ) -> Option { if let Ok(Some(user)) = state.store.verified_user_by_email(email).await { return Some(user); } let owner = state .store .user_by_id(&repo.owner_id) .await .ok() .flatten()?; let same = owner .email .as_deref() .is_some_and(|own| own.eq_ignore_ascii_case(email)); same.then_some(owner) } pub fn last_commit_view( lang: Lang, repo: &RepoRow, commit: &CommitInfo, now: i64, tz: &str, ) -> LastCommit { LastCommit { href: repo_href(&repo.owner_name, &repo.name, "commit", &commit.oid), summary: emojify(&commit.summary).into_owned(), iso: iso_time(commit.author_time), absolute: format_in_tz(commit.author_time, tz), age: relative_time(lang, commit.author_time, now), } } fn blob_href(repo: &RepoRow, ref_name: &str, rel: &str) -> Option { Some(repo_href( &repo.owner_name, &repo.name, "blob", &format!("{ref_name}/{rel}"), )) } pub fn link_context(state: &AppState, repo: &RepoRow, ref_name: &str, dir: &str) -> LinkContext { let at = |section: &str| { repo_href( &repo.owner_name, &repo.name, section, &format!("{ref_name}/{dir}"), ) }; LinkContext { tree_base: at("tree"), blob_base: at("blob"), raw_base: raw_url(state, repo, ref_name, dir) .trim_end_matches('/') .to_owned(), issues_base: Some(repo_href(&repo.owner_name, &repo.name, "issues", "")), } } pub struct Readme { pub name: String, pub markdown: bool, pub body: String, } pub async fn load_readme( state: &AppState, repo: &RepoRow, path: &Path, ref_name: &str, commit: &str, dir: &str, entries: &[TreeEntry], ) -> Result> { let found = README_NAMES.iter().find_map(|wanted| { entries.iter().find(|e| { e.name == *wanted && matches!(e.kind, EntryKind::Blob | EntryKind::Executable) }) }); let Some(found) = found else { return Ok(None); }; let name = found.name.clone(); let file = child_path(dir, &name); let Some(blob) = read_file(path.to_path_buf(), commit.to_owned(), file).await? else { return Ok(None); }; if blob.is_binary { return Ok(None); } let text = String::from_utf8_lossy(&blob.data).into_owned(); if name.ends_with(".md") || name.ends_with(".markdown") { let ctx = link_context(state, repo, ref_name, dir); Ok(Some(Readme { name, markdown: true, body: render_markdown(&text, Some(&ctx)), })) } else { Ok(Some(Readme { name, markdown: false, body: text, })) } } #[component] pub async fn tree_table( cx: &Cx, rows: Vec, lang: Lang, #[default] current: Option, ) -> Result { Ok(view! {
for row in rows.into_iter() { if let Some(href) = row.href { (g::kind_label(lang, row.kind)) (row.name)if row.kind == "dir" { "/" } if let Some(last) = row.last { } } else {
(g::kind_label(lang, row.kind)) (row.name) (row.short)
} }
}) } #[component] pub async fn readme_sheet( cx: &Cx, lang: Lang, owner: String, repo: String, ref_name: String, dir: String, readme: Option, none: &str, ) -> Result { let readme_name = readme.as_ref().map(|readme| readme.name.clone()); let links = readme.as_ref().map(|readme| { let path = if dir.is_empty() { readme.name.clone() } else { format!("{dir}/{}", readme.name) }; let target = format!("{ref_name}/{path}"); ( repo_href(&owner, &repo, "blob", &target), repo_href(&owner, &repo, "commits", &target), repo_href(&owner, &repo, "raw", &target), ) }); let shown = readme_name.unwrap_or_else(|| { if dir.is_empty() { repo.clone() } else { dir.clone() } }); Ok(view! {
(shown) if let Some((source, history, raw)) = links { (s(lang, "Source", "Kaynak")) (s(lang, "History", "Geçmiş")) (s(lang, "Raw", "Ham")) }
if let Some(readme) = readme { readme_card(name: readme.name, markdown: readme.markdown, body: readme.body) } else { empty_state(title: none) }
}) } #[component] pub async fn readme_card(cx: &Cx, name: String, markdown: bool, body: String) -> Result { Ok(view! {

(name)

if markdown {
(Unescaped::new_unchecked(body))
} else {
(body)
}
}) } #[page("/{owner}/{repo}/tree/{*rest}")] async fn tree_page(cx: &Cx) -> Result { let owner = owner(cx); let name = repo(cx); let rest = rest(cx).collect::>().join("/"); let ctx = load_repo(cx, owner, name).await?; let state = context::(cx); let lang = i18n::lang(cx, ctx.viewer_user()); let repo = &ctx.repo; let Some((ref_name, commit, dir)) = resolve(ctx.path.clone(), rest).await? else { return Err(not_found().into()); }; let Some(entries) = read_dir(ctx.path.clone(), commit.clone(), dir.clone()).await? else { return Err(not_found().into()); }; let names: Vec = entries.iter().map(|e| e.name.clone()).collect(); let root_names: Vec = if dir.is_empty() { names.clone() } else { read_dir(ctx.path.clone(), commit.clone(), String::new()) .await? .unwrap_or_default() .into_iter() .map(|e| e.name) .collect() }; let (last, bar, strip, runs) = tokio::join!( last_commits(&ctx.path, &commit, &dir, &names), latest_bar(state, repo, &ctx.path, &commit, lang, ctx.viewer_tz()), commit_strip(state, repo, &ctx.path, &commit), run_rows(state, lang, repo), ); let runs = runs?; let facts = tree_facts(state, repo, &ctx.path, &commit, &root_names).await?; let pips = run_pips(&runs); let sub = code_sub(lang, bar, Some(facts), None, strip.total); let refs: Vec = load_refs(ctx.path.clone()).await?; let readme = load_readme(state, repo, &ctx.path, &ref_name, &commit, &dir, &entries).await?; let rows = entry_rows( lang, repo, &ref_name, &dir, entries, &last, now_unix(), ctx.viewer_tz(), ); let (branches, tags) = ref_links(&refs, &ref_name, &repo.default_branch, repo); let branches_href = repo_href(&repo.owner_name, &repo.name, "branches", ""); let tags_href = repo_href(&repo.owner_name, &repo.name, "tags", ""); let live = follows_branch(&refs, &ref_name) .then(|| live_url(&repo.owner_name, &repo.name, &refs, &ref_name)); let title = ctx.title(); let finder_owner = repo.owner_name.clone(); let finder_repo = repo.name.clone(); let dock_owner = finder_owner.clone(); let dock_repo = finder_repo.clone(); let finder_ref = ref_name.clone(); let code_search_href = repo_href(&repo.owner_name, &repo.name, "search", ""); let readme_file = readme.as_ref().map(|readme| readme.name.clone()); let mut header = ctx.head(state, "code").await?; if let Some(url) = &live { header.live = url.clone(); } Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header, sub: sub, pips: pips)
readme_sheet(lang: lang, owner: dock_owner, repo: dock_repo, ref_name: ref_name.clone(), dir: dir.clone(), readme: readme, none: s(lang, "No README in this folder", "Bu klasörde README yok"))
) }) }