diff --git a/crates/forge-git/src/history.rs b/crates/forge-git/src/history.rs index 489fb2c..02fb6a5 100644 --- a/crates/forge-git/src/history.rs +++ b/crates/forge-git/src/history.rs @@ -263,6 +263,26 @@ pub async fn log( .collect()) } +/// Number of commits reachable from `commit`, limited to `path` when given (`git rev-list +/// --count`). Counts every commit, not just the ones a history page shows. +pub async fn count(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>) -> Result { + validate_oid(commit)?; + let mut cmd = git(env, "rev-list") + .git_dir(repo) + .arg("--count") + .user_revs(&[commit])?; + if let Some(p) = path { + browse::validate_repo_path(p)?; + let spec = literal_spec(p); + cmd = cmd.paths(&[spec.as_str()]); + } + let out = cmd.output().await?; + let text = String::from_utf8_lossy(&out); + text.trim() + .parse::() + .map_err(|_| Error::Failed(format!("unexpected rev-list count: {:?}", text.trim()))) +} + /// Commits reachable from `new` but not from `old` (when `old` is given), oldest first. At most /// `max` of the newest commits are returned. Both ids must be full object ids; they are passed /// after `--end-of-options`, so no value can be read as an option. diff --git a/crates/forge-git/tests/history.rs b/crates/forge-git/tests/history.rs index a80d4de..01b7983 100644 --- a/crates/forge-git/tests/history.rs +++ b/crates/forge-git/tests/history.rs @@ -4,7 +4,7 @@ use std::process::{Command, Stdio}; use forge_git::history::{ ArchiveFormat, CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind, archive_command, - commit_diff, last_commits, log, + commit_diff, count, last_commits, log, }; use forge_git::{Error, GitEnv}; @@ -322,6 +322,43 @@ async fn last_commits_finds_newest_touch_per_child() { assert_eq!(short["sub"].oid, c5); } +#[tokio::test] +async fn count_counts_all_commits_or_those_touching_a_path() { + let f = fixture(); + f.write("d/x.txt", "1\n"); + f.commit("c1 add x"); + f.write("d/y.txt", "1\n"); + let c2 = f.commit("c2 add y"); + f.write("d/x.txt", "2\n"); + f.commit("c3 change x"); + f.write("other.txt", "1\n"); + let c4 = f.commit("c4 other"); + + let all = count(&f.env, &f.git_dir, &c4, None).await.unwrap(); + assert_eq!(all, 4); + let dir = count(&f.env, &f.git_dir, &c4, Some("d")).await.unwrap(); + assert_eq!(dir, 3); + let file = count(&f.env, &f.git_dir, &c4, Some("other.txt")) + .await + .unwrap(); + assert_eq!(file, 1); + let at_c2 = count(&f.env, &f.git_dir, &c2, Some("d/x.txt")) + .await + .unwrap(); + assert_eq!(at_c2, 1); + let untouched = count(&f.env, &f.git_dir, &c4, Some("missing")) + .await + .unwrap(); + assert_eq!(untouched, 0); + + assert!(count(&f.env, &f.git_dir, "not-an-oid", None).await.is_err()); + assert!( + count(&f.env, &f.git_dir, &c4, Some("../escape")) + .await + .is_err() + ); +} + #[tokio::test] async fn archive_command_produces_listable_tar_gz() { let f = fixture(); diff --git a/crates/forge-web/src/i18n/code.rs b/crates/forge-web/src/i18n/code.rs index 827413c..9b744f4 100644 --- a/crates/forge-web/src/i18n/code.rs +++ b/crates/forge-web/src/i18n/code.rs @@ -36,6 +36,7 @@ pub enum K { NameHeader, LastCommitHeader, AgeHeader, + LatestCommitLabel, KindDir, KindFile, KindExec, @@ -181,6 +182,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (LastCommitHeader, Tr) => "Son commit", (AgeHeader, En) => "Age", (AgeHeader, Tr) => "Zaman", + (LatestCommitLabel, En) => "Latest commit", + (LatestCommitLabel, Tr) => "Son commit", (KindDir, En) => "dir", (KindDir, Tr) => "dizin", (KindFile, En) => "file", @@ -417,6 +420,14 @@ pub fn changed_files(lang: Lang, count: usize) -> String { } } +/// `N commits` in English (`1 commit` for one), `N commit` in Turkish. +pub fn commit_count(lang: Lang, count: u64) -> String { + match lang { + Lang::En => format!("{count} commit{}", if count == 1 { "" } else { "s" }), + Lang::Tr => format!("{count} commit"), + } +} + /// The note that a diff stops at `max` files. `subject` names what the diff shows. pub fn diff_truncated(lang: Lang, max: usize, subject: &str) -> String { match lang { @@ -521,6 +532,7 @@ mod tests { K::NameHeader, K::LastCommitHeader, K::AgeHeader, + K::LatestCommitLabel, K::KindDir, K::KindFile, K::KindExec, diff --git a/crates/forge-web/src/pages/repo.rs b/crates/forge-web/src/pages/repo.rs index 10a8add..7c02bac 100644 --- a/crates/forge-web/src/pages/repo.rs +++ b/crates/forge-web/src/pages/repo.rs @@ -28,7 +28,7 @@ use crate::pages::refs::load_refs; use crate::pages::releases::latest_card; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; use crate::pages::tree::{ - entry_rows, last_commits, load_readme, read_dir, readme_card, tree_table, + entry_rows, last_commits, latest_bar, load_readme, read_dir, readme_card, tree_table, }; use crate::state::AppState; use crate::views::{now_unix, relative_time, repo_href, repo_tabs, shell, user_link}; @@ -417,11 +417,25 @@ async fn repo_page(cx: &Cx) -> Result { // The tree and README exist only when the default branch has a commit. let mut tree = None; let mut readme = None; + let mut bar = None; if let Some(commit) = &head && let Some(entries) = read_dir(ctx.path.clone(), commit.clone(), String::new()).await? { let names: Vec = entries.iter().map(|e| e.name.clone()).collect(); - let last = last_commits(state, &ctx.path, commit, "", &names).await; + let (last, latest) = tokio::join!( + last_commits(state, &ctx.path, commit, "", &names), + latest_bar( + state, + repo, + &ctx.path, + &branch, + commit, + "", + lang, + ctx.viewer_tz() + ), + ); + bar = latest; readme = load_readme(state, repo, &ctx.path, &branch, commit, "", &entries).await?; tree = Some(entry_rows( lang, @@ -467,7 +481,7 @@ async fn repo_page(cx: &Cx) -> Result {
- tree_table(rows: rows, lang: lang) + tree_table(rows: rows, latest: bar, lang: lang) if let Some(readme) = readme { readme_card(name: readme.name, markdown: readme.markdown, body: readme.body) } diff --git a/crates/forge-web/src/pages/tree.rs b/crates/forge-web/src/pages/tree.rs index ed1cfee..c75d1b1 100644 --- a/crates/forge-web/src/pages/tree.rs +++ b/crates/forge-web/src/pages/tree.rs @@ -26,7 +26,8 @@ use crate::render::emoji::emojify; use crate::render::markdown::{LinkContext, render_markdown}; use crate::state::AppState; use crate::views::{ - Crumb, breadcrumb, iso_time, now_unix, ref_selector, relative_time, repo_href, shell, short_oid, + Crumb, avatar_url, breadcrumb, display_name, iso_time, now_unix, ref_selector, relative_time, + repo_href, shell, short_oid, user_href, }; /// Files at the root of a directory that count as its README, in priority order. @@ -112,6 +113,102 @@ pub struct LastCommit { pub age: String, } +/// The bar above a directory listing: the newest commit that touched the directory (or the +/// whole ref at the root), with its author, short sha, age and the number of commits. +pub struct LatestBar { + pub last: LastCommit, + pub short: String, + pub author: String, + /// Profile link, only when the author maps to a forge user. + pub author_href: Option, + /// Avatar of that user. None for plain-text authors. + pub avatar: Option, + pub commits_href: String, + pub commits_label: String, +} + +/// Latest commit bar for the listing of `dir` at `commit` (`""` is the root). The commit lookup +/// and the commit count run side by side. Errors and timeouts leave the bar out, or the count +/// out of its label. +#[allow(clippy::too_many_arguments)] +pub async fn latest_bar( + state: &AppState, + repo: &RepoRow, + path: &Path, + ref_name: &str, + commit: &str, + dir: &str, + lang: Lang, + tz: &str, +) -> Option { + let filter = (!dir.is_empty()).then_some(dir); + let (log, count) = tokio::join!( + tokio::time::timeout( + LAST_COMMIT_TIMEOUT, + history::log(&state.git, path, commit, filter, 0, 1), + ), + tokio::time::timeout( + LAST_COMMIT_TIMEOUT, + history::count(&state.git, path, commit, filter), + ), + ); + 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 count = match count { + Ok(Ok(n)) => Some(n), + Ok(Err(e)) => { + tracing::warn!(error = %e, "commit count failed"); + None + } + Err(_) => { + tracing::warn!("commit count timed out"); + None + } + }; + + let user = state + .store + .verified_user_by_email(&info.author_email) + .await + .ok() + .flatten(); + let (author, author_href, avatar) = match user { + Some(user) => ( + display_name(lang, &user.username), + Some(user_href(&user.username)), + Some(avatar_url(&user.username, user.avatar_hash.as_deref())), + ), + None => (info.author_name.clone(), None, None), + }; + let rest = if dir.is_empty() { + ref_name.to_owned() + } else { + format!("{ref_name}/{dir}") + }; + let commits_label = match count { + Some(n) => g::commit_count(lang, n), + None => g::t(lang, K::TabCommits).to_owned(), + }; + Some(LatestBar { + last: last_commit_view(lang, repo, &info, now_unix(), tz), + short: short_oid(&info.oid).to_owned(), + author, + author_href, + avatar, + commits_href: repo_href(&repo.owner_name, &repo.name, "commits", &rest), + commits_label, + }) +} + /// One row of a directory listing. pub struct EntryRow { /// "dir", "file", "exec", "link" or "submodule". @@ -289,11 +386,63 @@ pub async fn load_readme( } } -/// Directory listing table: kind, name, last commit and its age. +/// The latest commit bar above a listing. It is the first row of the listing box, and its +/// padding and columns match the table rows below it. +#[component] +pub async fn latest_commit_bar(bar: LatestBar, lang: Lang) -> Result { + let LatestBar { + last, + short, + author, + author_href, + avatar, + commits_href, + commits_label, + } = bar; + let initial = author + .chars() + .next() + .map(|c| c.to_uppercase().collect::()) + .unwrap_or_default(); + Ok(view! { +
+ + if let Some(src) = avatar { + + } else { + + } + if let Some(href) = author_href { + (author) + } else { + (author) + } + + (last.summary) + + (short) + + + + (commits_label) + + +
+ }) +} + +/// Directory listing table: kind, name, last commit and its age. `latest` is the bar above it. #[component] -pub async fn tree_table(rows: Vec, lang: Lang) -> Result { +pub async fn tree_table( + rows: Vec, + latest: Option, + lang: Lang, +) -> Result { Ok(view! {
+ if let Some(bar) = latest { + latest_commit_bar(bar: bar, lang: lang) + } @@ -372,7 +521,19 @@ async fn tree_page(cx: &Cx) -> Result { return Err(not_found().into()); }; let names: Vec = entries.iter().map(|e| e.name.clone()).collect(); - let last = last_commits(state, &ctx.path, &commit, &dir, &names).await; + let (last, bar) = tokio::join!( + last_commits(state, &ctx.path, &commit, &dir, &names), + latest_bar( + state, + repo, + &ctx.path, + &ref_name, + &commit, + &dir, + lang, + ctx.viewer_tz() + ), + ); 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( @@ -401,7 +562,7 @@ async fn tree_page(cx: &Cx) -> Result { breadcrumb(lang: lang, crumbs: crumbs) file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref) - tree_table(rows: rows, lang: lang) + tree_table(rows: rows, latest: bar, lang: lang) if let Some(readme) = readme { readme_card(name: readme.name, markdown: readme.markdown, body: readme.body) } diff --git a/crates/forge-web/tests/browse_e2e.rs b/crates/forge-web/tests/browse_e2e.rs index 434026b..9727948 100644 --- a/crates/forge-web/tests/browse_e2e.rs +++ b/crates/forge-web/tests/browse_e2e.rs @@ -136,6 +136,28 @@ fn element_texts(body: &str, selector: &str) -> Vec { .collect() } +/// Checks the latest commit bar of a listing: one bar, with the subject, the short sha of `oid` +/// and the commit count label. +fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &str) { + let bars = element_texts(body, ".latest-commit"); + assert_eq!(bars.len(), 1, "{what}: exactly one latest commit bar"); + let subjects = element_texts(body, ".latest-commit .latest-subject"); + assert_eq!(subjects.len(), 1, "{what}: bar must show the subject"); + assert_eq!(subjects[0].trim(), subject, "{what}: bar subject"); + let shas = element_texts(body, ".latest-commit .latest-sha"); + assert_eq!(shas.len(), 1, "{what}: bar must show the sha"); + assert_eq!(shas[0].trim(), &oid[..7], "{what}: bar short sha"); + let counts = element_texts(body, ".latest-commit .latest-count"); + assert!( + counts.iter().any(|c| c.trim() == count), + "{what}: bar must show {count:?}, got {counts:?}" + ); + assert!( + !attr_values(body, ".latest-commit .latest-age", "title").is_empty(), + "{what}: bar age needs an absolute time in its title" + ); +} + fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { let out = Command::new(BIN) .arg("--config") @@ -409,9 +431,25 @@ async fn browse_end_to_end() { "README image must point at the raw origin: {image_srcs:?}" ); + // Latest commit bar: the root has one commit on main, so its subject, short sha and count. + assert_latest_bar( + &home_body, + "repo home", + "browse fixtures", + &pub_main, + "1 commit", + ); + let tree = http.get("/tahinli/pub/tree/main/src", None).await; assert_eq!(tree.status, 200, "tree of src"); assert!(tree.body().contains("main.rs"), "tree must list main.rs"); + assert_latest_bar( + &tree.body(), + "tree of src", + "browse fixtures", + &pub_main, + "1 commit", + ); let blob = http.get("/tahinli/pub/blob/main/src/main.rs", None).await; assert_eq!(blob.status, 200, "blob of main.rs"); @@ -458,12 +496,23 @@ async fn browse_end_to_end() { "branches must list feature/x" ); + let feature_head = String::from_utf8_lossy(&git(&pub_work, &["rev-parse", "feature/x"]).stdout) + .trim() + .to_owned(); let feature_tree = http.get("/tahinli/pub/tree/feature/x", None).await; assert_eq!(feature_tree.status, 200, "tree of feature/x"); assert!( feature_tree.body().contains("feature.txt"), "feature/x tree must list feature.txt" ); + // The feature commit is the newest on feature/x, on top of the two-commit history. + assert_latest_bar( + &feature_tree.body(), + "tree of feature/x", + "feature commit", + &feature_head, + "2 commits", + ); let archive = http.get("/tahinli/pub/archive/main.tar.gz", None).await; assert_eq!(archive.status, 200, "tar.gz archive"); diff --git a/style/_repo.scss b/style/_repo.scss index bc9130c..97db07b 100644 --- a/style/_repo.scss +++ b/style/_repo.scss @@ -912,3 +912,129 @@ flex-basis: 100%; } } + +// Latest commit bar: the first row of the listing box (repo home and tree views). Its padding +// matches the table cells, so the author sits over the Name column and the age over the Age +// column. The subject takes the slack and ellipsizes; on phones it drops to its own line. +.latest-commit { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; + min-width: 0; + padding: 10px 0; + font-size: 13.5px; + color: var(--text); + border-bottom: 1px solid var(--border); + + .latest-author { + display: inline-flex; + flex: 0 1 auto; + align-items: center; + gap: 8px; + min-width: 0; + max-width: 14rem; + white-space: nowrap; + + .avatar { + flex: none; + width: 20px; + height: 20px; + margin-right: 0; + } + + // Plain-text authors have no avatar: a neutral disc with the author's initial. + .avatar-blank { + display: inline-flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + border: 1px solid var(--border); + font-size: 11px; + font-weight: 600; + line-height: 1; + color: var(--muted); + } + + a, + span:not(.avatar) { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + font-weight: 600; + color: var(--text); + } + + a:hover { + color: var(--accent-ink); + text-decoration: none; + } + } + + .latest-subject { + flex: 1 1 0; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--text); + + &:hover { + color: var(--accent-ink); + text-decoration: none; + } + } + + .latest-meta { + display: inline-flex; + flex: none; + align-items: center; + gap: 14px; + white-space: nowrap; + font-size: 13px; + color: var(--muted); + } + + .latest-sha { + font-size: 12.5px; + color: var(--muted); + + &:hover { + color: var(--accent-ink); + text-decoration: none; + } + } + + .latest-count { + display: inline-flex; + align-items: center; + gap: 5px; + color: var(--muted); + + &:hover { + color: var(--text); + text-decoration: none; + } + + .ico { + width: 15px; + height: 15px; + } + } +} + +@media (max-width: 600px) { + .latest-commit { + row-gap: 6px; + + .latest-subject { + order: 3; + flex: 1 1 100%; + } + + .latest-meta { + gap: 10px; + margin-left: auto; + } + } +}