diff --git a/crates/forge-web/src/i18n/browse.rs b/crates/forge-web/src/i18n/browse.rs new file mode 100644 index 0000000..9f7569b --- /dev/null +++ b/crates/forge-web/src/i18n/browse.rs @@ -0,0 +1,137 @@ +//! Strings for the code-browsing upgrades: the diff toolbar, blob line selection, blame, the file +//! finder and the branches page. The `strings!` macro keeps the key list, the lookup and the test +//! list in one place. + +use super::Lang; + +macro_rules! strings { + ($($key:ident => $en:expr, $tr:expr;)*) => { + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum K { + $($key,)* + } + + pub fn t(lang: Lang, key: K) -> &'static str { + match (key, lang) { + $((K::$key, Lang::En) => $en, (K::$key, Lang::Tr) => $tr,)* + } + } + + #[cfg(test)] + const ALL: &[K] = &[$(K::$key,)*]; + }; +} + +strings! { + DiffView => "Diff view", "Fark görünümü"; + Unified => "Unified", "Birleşik"; + Split => "Split", "Bölünmüş"; + IgnoreWhitespace => "Ignore whitespace", "Boşlukları yoksay"; + PatchLink => ".patch", ".patch"; + DiffLink => ".diff", ".diff"; + PatchTitle => "Download as an email-style patch", "E-posta biçiminde yama olarak indir"; + DiffTitle => "Download as a plain diff", "Düz fark olarak indir"; + + BlameLink => "Blame", "Satır geçmişi"; + BlameTitle => "Blame", "Satır geçmişi"; + BlameBackToFile => "Back to file", "Dosyaya dön"; + BlamePrior => "Blame prior to this commit", "Bu işlemeden önceki satır geçmişi"; + BlameTimeout => "Blame took too long and was stopped. Try a smaller file or git on your machine.", "Satır geçmişi çok uzun sürdü ve durduruldu. Daha küçük bir dosya deneyin ya da kendi makinenizde git çalıştırın."; + BlameFailed => "Blame could not be computed for this file.", "Bu dosya için satır geçmişi hesaplanamadı."; + BlameNotText => "Blame is only available for text files.", "Satır geçmişi yalnızca metin dosyaları için kullanılabilir."; + + CopyPermalink => "Copy permalink", "Kalıcı bağlantıyı kopyala"; + PermalinkCopied => "Permalink copied", "Kalıcı bağlantı kopyalandı"; + PermalinkHint => "Link to this exact commit. Press y to switch the address bar.", "Tam bu işlemeye bağlantı. Adres çubuğunu değiştirmek için y'ye basın."; + + GoToFile => "Go to file", "Dosyaya git"; + FinderTitle => "Go to file", "Dosyaya git"; + FinderPlaceholder => "Type to find a file", "Dosya bulmak için yazın"; + FinderHint => "Up and down to move, Enter to open, Esc to close", "Gezinmek için yukarı ve aşağı, açmak için Enter, kapatmak için Esc"; + FinderEmpty => "No matching files", "Eşleşen dosya yok"; + FinderLoading => "Loading files", "Dosyalar yükleniyor"; + FinderFailed => "The file list could not be loaded.", "Dosya listesi yüklenemedi."; + FinderTruncated => "Very large tree: only the first files are searchable.", "Çok büyük ağaç: yalnızca ilk dosyalar aranabilir."; + + BranchAuthorHeader => "Author", "Yazar"; + BranchAheadBehindHeader => "Ahead / behind", "Önde / geride"; + BranchActionsHeader => "Actions", "İşlemler"; + UpToDate => "Even with the default branch", "Varsayılan dalla aynı"; + NewPr => "New PR", "Yeni PR"; + DeleteBranch => "Delete", "Sil"; + DeleteConfirm => "Delete this branch? Its commits stay in the repository until they are cleaned up.", "Bu dal silinsin mi? İşlemeleri temizlenene kadar depoda kalır."; + DeleteConfirmYes => "Yes, delete branch", "Evet, dalı sil"; + DeleteCancel => "Cancel", "Vazgeç"; + NewBranchTitle => "New branch", "Yeni dal"; + BranchNameLabel => "Branch name", "Dal adı"; + BranchFromLabel => "From", "Kaynak"; + BranchFromPlaceholder => "branch, tag or commit", "dal, etiket veya işleme"; + CreateBranch => "Create branch", "Dal oluştur"; + BranchCreated => "Branch created.", "Dal oluşturuldu."; + BranchDeleted => "Branch deleted.", "Dal silindi."; + BranchExists => "A branch with that name already exists.", "Bu adda bir dal zaten var."; + BranchInvalidName => "That is not a valid branch name.", "Bu geçerli bir dal adı değil."; + BranchSourceMissing => "The source branch, tag or commit was not found.", "Kaynak dal, etiket veya işleme bulunamadı."; + BranchIsDefault => "The default branch cannot be deleted. Change the default branch in settings first.", "Varsayılan dal silinemez. Önce ayarlardan varsayılan dalı değiştirin."; + BranchProtectedDelete => "This branch is protected and cannot be deleted.", "Bu dal korumalı ve silinemez."; + BranchPullOnly => "A protection rule on this branch only allows changes through pull requests.", "Bu daldaki bir koruma kuralı yalnızca birleştirme istekleriyle değişikliğe izin verir."; + BranchGone => "That branch no longer exists or has moved.", "Bu dal artık yok ya da taşındı."; + BranchFailed => "The branch change could not be made.", "Dal değişikliği yapılamadı."; + BranchForbidden => "You need write access to change branches.", "Dalları değiştirmek için yazma erişimi gerekir."; +} + +/// "3 ahead, 1 behind", or the up-to-date text when both are zero. +pub fn ahead_behind(lang: Lang, ahead: u32, behind: u32) -> String { + match lang { + Lang::En => format!("{ahead} ahead, {behind} behind"), + Lang::Tr => format!("{ahead} önde, {behind} geride"), + } +} + +/// "Delete branch `name`?" for the accessible name of the delete button. +pub fn delete_aria(lang: Lang, name: &str) -> String { + match lang { + Lang::En => format!("Delete branch {name}"), + Lang::Tr => format!("{name} dalını sil"), + } +} + +/// Shown when blame has a file of `size` bytes over the limit. +pub fn blame_limit(lang: Lang, limit: &str) -> String { + match lang { + Lang::En => format!("Blame is limited to files of {limit} or less."), + Lang::Tr => format!("Satır geçmişi en çok {limit} boyutundaki dosyalarla sınırlıdır."), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_key_has_text_in_both_languages() { + for key in ALL { + assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English text"); + assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish text"); + } + } + + #[test] + fn no_em_dashes() { + for key in ALL { + for lang in [Lang::En, Lang::Tr] { + assert!( + !t(lang, *key).contains('\u{2014}'), + "{key:?} has an em dash" + ); + } + } + } + + #[test] + fn helpers_carry_their_arguments() { + assert_eq!(ahead_behind(Lang::En, 3, 1), "3 ahead, 1 behind"); + assert!(delete_aria(Lang::Tr, "x").contains('x')); + assert!(blame_limit(Lang::En, "1 MiB").contains("1 MiB")); + } +} diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index e1b5faf..ccec8a9 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -19,6 +19,7 @@ use forge_core::User; pub mod accents; pub mod admin; +pub mod browse; pub mod code; pub mod community; pub mod integrations; diff --git a/crates/forge-web/src/pages/commit.rs b/crates/forge-web/src/pages/commit.rs index adc78fa..5dd85e3 100644 --- a/crates/forge-web/src/pages/commit.rs +++ b/crates/forge-web/src/pages/commit.rs @@ -5,7 +5,7 @@ use forge_git::browse; use forge_git::history; use topcoat::Result; use topcoat::context::{Cx, app_context}; -use topcoat::router::error::not_found; +use topcoat::router::error::{content_too_large, not_found}; use topcoat::router::{page, path_param, route}; use topcoat::view::{View, view}; @@ -13,12 +13,12 @@ use crate::i18n::code::{self as g, K}; use crate::i18n::{self}; use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid}; use crate::pages::repo::repo_head; -use crate::pages::repo_ctx::load_repo; +use crate::pages::repo_ctx::{RawDownload, load_repo}; use crate::render::emoji::emojify; use crate::signatures; use crate::state::AppState; use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary}; -use crate::views::diff::{DiffLang, LIMITS, diff_section}; +use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; use crate::views::relative_time; use crate::views::shell; @@ -43,11 +43,47 @@ fn is_hex_prefix(s: &str) -> bool { (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit()) } +/// Which plain download a `.patch` or `.diff` suffix asks for. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Download { + Patch, + Diff, +} + +impl Download { + /// Splits a `.patch` or `.diff` suffix off `spec`. + pub fn split(spec: &str) -> (&str, Option) { + if let Some(rest) = spec.strip_suffix(".patch") { + (rest, Some(Download::Patch)) + } else if let Some(rest) = spec.strip_suffix(".diff") { + (rest, Some(Download::Diff)) + } else { + (spec, None) + } + } + + /// The bytes as a download. Output cut at the cap is refused rather than served broken. + pub fn serve(self, out: history::PatchOut, stem: &str) -> Result { + if !out.complete { + return Err(content_too_large().into()); + } + let ext = match self { + Download::Patch => "patch", + Download::Diff => "diff", + }; + Ok(RawDownload { + content_type: "text/plain; charset=utf-8", + filename: format!("{stem}.{ext}"), + data: out.data, + }) + } +} + #[page("/{owner}/{repo}/commit/{oid}")] async fn commit_page(cx: &Cx) -> Result { let owner = path_param::(cx); let name = path_param::(cx); - let rev = path_param::(cx); + let (rev, download) = Download::split(path_param::(cx)); if !is_hex_prefix(rev) { return Err(not_found().into()); } @@ -66,7 +102,28 @@ async fn commit_page(cx: &Cx) -> Result { let Some(info) = blocking(move || browse::read_commit(&repo_dir, &lookup)).await? else { return Err(not_found().into()); }; - let diff = history::commit_diff(&state.git, &ctx.path, &info.oid, LIMITS).await?; + if let Some(kind) = download { + let out = match kind { + Download::Patch => history::commit_patch(&state.git, &ctx.path, &info.oid).await?, + Download::Diff => history::commit_raw_diff(&state.git, &ctx.path, &info.oid).await?, + }; + return Err(kind.serve(out, &info.oid)?.into()); + } + let opts = DiffOpts::from_cx( + cx, + Some(( + format!( + "/{}/{}/commit/{}.patch", + ctx.repo.owner_name, ctx.repo.name, info.oid + ), + format!( + "/{}/{}/commit/{}.diff", + ctx.repo.owner_name, ctx.repo.name, info.oid + ), + )), + ); + let diff = + history::commit_diff_ws(&state.git, &ctx.path, &info.oid, LIMITS, opts.ignore_ws).await?; let owner_name = ctx.repo.owner_name.clone(); let repo_name = ctx.repo.name.clone(); @@ -145,7 +202,7 @@ async fn commit_page(cx: &Cx) -> Result { if has_body {
(message.as_str())
} - diff_section(diff: &diff, owner: owner_name.as_str(), repo: repo_name.as_str(), oid: info.oid.as_str(), parent: parent.as_deref(), subject: g::t(lang, K::ThisCommit), lang: DiffLang(lang)) + diff_section(diff: &diff, owner: owner_name.as_str(), repo: repo_name.as_str(), oid: info.oid.as_str(), parent: parent.as_deref(), subject: g::t(lang, K::ThisCommit), lang: DiffLang(lang), opts: opts) ) }) } diff --git a/crates/forge-web/src/pages/compare.rs b/crates/forge-web/src/pages/compare.rs index 44e680d..173ebf1 100644 --- a/crates/forge-web/src/pages/compare.rs +++ b/crates/forge-web/src/pages/compare.rs @@ -14,6 +14,7 @@ use std::path::PathBuf; use forge_core::{Action, Repo as RepoRecord, Session, authorize, validate_body, validate_title}; use forge_git::browse::{self, CommitInfo, RefKind}; use forge_git::command::ObjectSource; +use forge_git::history; use forge_git::pulls; use forge_git::repo::repo_path; use serde::Deserialize; @@ -28,12 +29,13 @@ use crate::auth::{check_csrf, require_user}; use crate::i18n; use crate::i18n::pulls::{self as g, K}; use crate::notify::{self, Activity}; -use crate::pages::commits::{CommitRow, blocking, now_secs, url_path}; +use crate::pages::commit::Download; +use crate::pages::commits::{CommitRow, blocking, now_secs, short_oid, url_path}; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::state::AppState; use crate::templates; -use crate::views::diff::{DiffLang, LIMITS, diff_section}; +use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; use crate::views::{alert, repo_href, shell, user_facing_message}; use crate::webhooks::emit::{Sender, emit_pull}; @@ -256,15 +258,29 @@ async fn compare_view( let show_diff = related && has_commits; let parent = cmp.merge_base.clone(); + let compare_path = format!( + "/{owner}/{name}/compare/{}", + url_path(&format!("{base}...{head}")) + ); + let mut opts = DiffOpts::from_cx( + cx, + Some(( + format!("{compare_path}.patch"), + format!("{compare_path}.diff"), + )), + ); + // The page may be a failed POST re-shown; the toolbar still links to the comparison itself. + opts.path = compare_path; let diff = if show_diff { Some( - pulls::range_diff_files_with( + pulls::range_diff_files_ws( &state.git, &ctx.path, cmp.objects(), &cmp.base_oid, &cmp.head_oid, LIMITS, + opts.ignore_ws, ) .await?, ) @@ -374,7 +390,7 @@ async fn compare_view( } if show_diff { for d in diff.iter() { - diff_section(diff: d, owner: owner.as_str(), repo: name.as_str(), oid: cmp.head_oid.as_str(), parent: parent.as_deref(), subject: g::t(lang, K::ThisComparison), lang: DiffLang(lang)) + diff_section(diff: d, owner: owner.as_str(), repo: name.as_str(), oid: cmp.head_oid.as_str(), parent: parent.as_deref(), subject: g::t(lang, K::ThisComparison), lang: DiffLang(lang), opts: opts.clone()) } } ) @@ -450,7 +466,8 @@ async fn compare_picker(cx: &Cx) -> Result { async fn compare_page(cx: &Cx) -> Result { let owner = path_param::(cx); let name = path_param::(cx); - let spec = path_param::(cx).collect::>().join("/"); + let full_spec = path_param::(cx).collect::>().join("/"); + let (spec, download) = Download::split(&full_spec); let ctx = load_repo(cx, owner, name).await?; let state = app_context::(cx); let Some((base, head)) = spec.split_once("...") else { @@ -462,6 +479,34 @@ async fn compare_page(cx: &Cx) -> Result { let Some(cmp) = resolve_comparison(state, &ctx, base, head).await? else { return Err(not_found().into()); }; + if let Some(kind) = download { + let out = match kind { + Download::Patch => { + history::range_patch( + &state.git, + &ctx.path, + cmp.objects(), + &cmp.base_oid, + &cmp.head_oid, + ) + .await? + } + Download::Diff => { + let from = match &cmp.merge_base { + Some(mb) => mb.clone(), + None => history::empty_tree_for(&cmp.head_oid).to_owned(), + }; + history::raw_diff(&state.git, &ctx.path, cmp.objects(), &from, &cmp.head_oid) + .await? + } + }; + let stem = format!( + "{}...{}", + short_oid(&cmp.base_oid), + short_oid(&cmp.head_oid) + ); + return Err(kind.serve(out, &stem)?.into()); + } compare_view(cx, ctx, cmp, None, None).await } diff --git a/crates/forge-web/src/pages/pull_files.rs b/crates/forge-web/src/pages/pull_files.rs index 2e0525f..aee0482 100644 --- a/crates/forge-web/src/pages/pull_files.rs +++ b/crates/forge-web/src/pages/pull_files.rs @@ -7,7 +7,9 @@ use std::collections::HashMap; use forge_core::{Action, IssueState, Side, Thread, authorize}; +use forge_git::command::ObjectSource; use forge_git::history::CommitDiff; +use forge_git::pulls::range_diff_files_ws; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::error::not_found; @@ -25,7 +27,7 @@ use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; use crate::pages::tree::link_context; use crate::state::AppState; -use crate::views::diff::{DiffLang, LineComments, diff_section}; +use crate::views::diff::{DiffLang, DiffOpts, LIMITS, LineComments, diff_section}; use crate::views::review_thread::ThreadCtx; use crate::views::{alert, shell}; @@ -125,8 +127,25 @@ async fn pull_files(cx: &Cx) -> Result { let lang = i18n::lang(cx, viewer(&ctx)); let commit_count = commits_of(state, &ctx, &pr).await?.len(); - let diff = pull_diff(state, &ctx, &pr).await?; - let frame = frame_in(lang, state, &ctx, &pr, commit_count, diff.files.len()).await?; + let full_diff = pull_diff(state, &ctx, &pr).await?; + let frame = frame_in(lang, state, &ctx, &pr, commit_count, full_diff.files.len()).await?; + let opts = DiffOpts::from_cx(cx, None); + // With whitespace ignored the file list can shrink, so file indexes differ from the comment + // routes' view. Existing threads still show; new inline comments wait for the full diff. + let diff = if opts.ignore_ws { + range_diff_files_ws( + &state.git, + &ctx.path, + ObjectSource::default(), + &pr.base_oid, + &pr.head_oid, + LIMITS, + true, + ) + .await? + } else { + full_diff + }; let viewer_id = viewer(&ctx).map(|user| user.id.clone()); let signed_in = viewer_id.is_some(); @@ -180,9 +199,9 @@ async fn pull_files(cx: &Cx) -> Result { edits, }; let comments = LineComments { - anchors: can_comment, + anchors: can_comment && !opts.ignore_ws, threads: by_line, - open_form: comment_target(cx).filter(|_| can_comment), + open_form: comment_target(cx).filter(|_| can_comment && !opts.ignore_ws), files_href: format!("{href}/files"), has_pending: pending > 0, ctx: thread_ctx, @@ -208,7 +227,7 @@ async fn pull_files(cx: &Cx) -> Result { } diff_section(diff: &diff, owner: owner.as_str(), repo: name.as_str(), oid: pr.head_oid.as_str(), parent: parent.as_deref(), - subject: g::t(lang, K::ThisPullRequest), lang: DiffLang(lang), comments: comments) + subject: g::t(lang, K::ThisPullRequest), lang: DiffLang(lang), comments: comments, opts: opts) ) }) } diff --git a/crates/forge-web/src/pages/repo_ctx.rs b/crates/forge-web/src/pages/repo_ctx.rs index 1c60273..67b54ff 100644 --- a/crates/forge-web/src/pages/repo_ctx.rs +++ b/crates/forge-web/src/pages/repo_ctx.rs @@ -119,6 +119,24 @@ impl std::fmt::Display for RepoMoved { impl std::error::Error for RepoMoved {} +/// A plain-text download (a `.patch` or `.diff`) raised by a page handler that cannot return a +/// response of its own. The `repo_moved` layer turns it into a 200 with these bytes. +#[derive(Debug, Clone)] +pub struct RawDownload { + pub content_type: &'static str, + /// File name offered to the browser. + pub filename: String, + pub data: Vec, +} + +impl std::fmt::Display for RawDownload { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("raw download") + } +} + +impl std::error::Error for RawDownload {} + impl RepoCtx { /// Whether the viewer may delete this repo: its owner or an instance admin only. pub fn can_delete(&self) -> bool { @@ -343,24 +361,54 @@ impl Layer for RepoMovedLayer { } } -/// Turns a `RepoMoved` error from a handler into a 301 with the new location. Other errors pass -/// through unchanged. +/// Turns a `RepoMoved` error from a handler into a 301 with the new location, and a `RawDownload` +/// into its plain-text response. Other errors pass through unchanged. async fn repo_moved(cx: &Cx, body: Body, next: Next<'_>) -> Result { - match next.run(cx, body).await { - Ok(response) => Ok(response), - Err(error) => match error.downcast_ref::() { - Some(moved) => { - let mut response = Response::new(Body::empty()); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; - // Owner and repo names are plain ASCII and the query came from a valid URI, so this - // only fails on a corrupt location; a 404 is the safe answer then. - let Ok(location) = HeaderValue::from_str(&moved.location) else { - return Err(not_found().into()); - }; - response.headers_mut().insert(LOCATION, location); - Ok(response) - } - None => Err(error), - }, + let error = match next.run(cx, body).await { + Ok(response) => return Ok(response), + Err(error) => error, + }; + let error = match error.downcast_cloned::() { + Ok(download) => { + return raw_download_response(download).ok_or_else(|| not_found().into()); + } + Err(error) => error, + }; + match error.downcast_ref::() { + Some(moved) => { + let mut response = Response::new(Body::empty()); + *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + // Owner and repo names are plain ASCII and the query came from a valid URI, so this + // only fails on a corrupt location; a 404 is the safe answer then. + let Ok(location) = HeaderValue::from_str(&moved.location) else { + return Err(not_found().into()); + }; + response.headers_mut().insert(LOCATION, location); + Ok(response) + } + None => Err(error), } } + +/// The 200 response for a [`RawDownload`]. `None` when the file name is not a valid header value. +fn raw_download_response(download: RawDownload) -> Option { + let mut response = Response::new(Body::from(download.data)); + let headers = response.headers_mut(); + headers.insert( + http::header::CONTENT_TYPE, + HeaderValue::from_static(download.content_type), + ); + headers.insert( + http::header::CONTENT_DISPOSITION, + HeaderValue::from_str(&format!("inline; filename=\"{}\"", download.filename)).ok()?, + ); + headers.insert( + http::header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + headers.insert( + http::header::CACHE_CONTROL, + HeaderValue::from_static("private, no-cache"), + ); + Some(response) +} diff --git a/crates/forge-web/src/views/diff.rs b/crates/forge-web/src/views/diff.rs index 6fcf51c..531e693 100644 --- a/crates/forge-web/src/views/diff.rs +++ b/crates/forge-web/src/views/diff.rs @@ -13,9 +13,13 @@ use std::collections::HashMap; use forge_core::{Side, Thread}; use forge_git::history::{CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind}; use topcoat::Result; +use topcoat::context::Cx; +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; +use topcoat::router::request::uri; use topcoat::view::{View, component, view}; use crate::i18n::Lang; +use crate::i18n::browse as b; use crate::i18n::code::{self as g, K}; use crate::pages::commits::url_path; use crate::views::review_thread::{ThreadCtx, review_thread_in}; @@ -60,6 +64,94 @@ pub struct LineComments { pub ctx: ThreadCtx, } +/// Name of the cookie that remembers the viewer's unified or split choice. +pub const DIFF_VIEW_COOKIE: &str = "forge_diff"; + +/// How a diff page shows its diff: unified or split, whitespace ignored or not, plus what the +/// toolbar needs to build its links. The default has no toolbar and shows a plain unified diff. +#[derive(Clone, Default)] +pub struct DiffOpts { + /// Draw the toolbar. + pub enabled: bool, + pub split: bool, + pub ignore_ws: bool, + /// Path of the page the toolbar links back to. + pub path: String, + /// The request's query pairs except the ones the toolbar owns. + pub query: Vec<(String, String)>, + /// `.patch` and `.diff` download links, when the page has them. + pub downloads: Option<(String, String)>, +} + +impl DiffOpts { + /// Reads the request: `?view=split|unified` wins and is remembered in a cookie, else the + /// cookie decides; `?w=1` ignores whitespace. `downloads` are the patch and diff links. + pub fn from_cx(cx: &Cx, downloads: Option<(String, String)>) -> Self { + let request = uri(cx); + let mut view_param = None; + let mut ignore_ws = false; + let mut query = Vec::new(); + if let Some(raw) = request.query() { + for (key, value) in form_urlencoded::parse(raw.as_bytes()) { + match key.as_ref() { + "view" => view_param = Some(value.into_owned()), + "w" => ignore_ws = value == "1", + "comment" | "review_error" => {} + _ => query.push((key.into_owned(), value.into_owned())), + } + } + } + let split = match view_param.as_deref() { + Some(v @ ("split" | "unified")) => { + let max_age = time::Duration::seconds(365 * 24 * 60 * 60); + cookies(cx).add( + Cookie::build((DIFF_VIEW_COOKIE, v.to_owned())) + .path("/") + .secure(true) + .same_site(SameSite::Lax) + .max_age(max_age) + .build(), + ); + v == "split" + } + _ => cookies(cx) + .get(DIFF_VIEW_COOKIE) + .is_some_and(|c| c.value() == "split"), + }; + Self { + enabled: true, + split, + ignore_ws, + path: request.path().to_owned(), + query, + downloads, + } + } + + /// The page URL for the given view and whitespace setting. + pub fn href(&self, split: bool, ignore_ws: bool) -> String { + let mut ser = form_urlencoded::Serializer::new(String::new()); + for (k, v) in &self.query { + ser.append_pair(k, v); + } + ser.append_pair("view", if split { "split" } else { "unified" }); + if ignore_ws { + ser.append_pair("w", "1"); + } + format!("{}?{}", self.path, ser.finish()) + } +} + +/// The toolbar above the diff, flattened for the view. +struct Toolbar { + unified_href: String, + split_href: String, + ws_href: String, + split: bool, + ignore_ws: bool, + downloads: Option<(String, String)>, +} + /// The inline comment form under an open line. struct InlineForm { action: String, @@ -106,6 +198,143 @@ struct FileView { has_blob: bool, blob_href: String, rows: Vec, + /// Rows for the split view; filled in place of `rows` when the diff is split. + split_rows: Vec, +} + +/// One side of a split row. +struct SplitSide { + /// `add`, `del`, `ctx`, `ctx dup` (the repeated side of a context line) or `empty`. + class: &'static str, + num: String, + code: String, + anchor: Option, + plus_href: Option, +} + +impl SplitSide { + fn empty() -> Self { + Self { + class: "empty", + num: String::new(), + code: String::new(), + anchor: None, + plus_href: None, + } + } + + fn from_row(row: DiffRow, class: &'static str, num: String) -> (Self, Option) { + ( + Self { + class, + num, + code: row.code, + anchor: row.anchor, + plus_href: row.plus_href, + }, + row.below, + ) + } +} + +/// A row of the split table: a hunk header, or a left and a right side with what sits below. +struct SplitRow { + hunk: Option, + left: SplitSide, + right: SplitSide, + below: Option, +} + +fn merge_below(a: Option, b: Option) -> Option { + match (a, b) { + (Some(mut a), Some(b)) => { + a.threads.extend(b.threads); + if a.form.is_none() { + a.form = b.form; + } + Some(a) + } + (a, None) => a, + (None, b) => b, + } +} + +/// Pairs each run of deleted lines with the added lines that follow it, side by side. +fn flush_pairs(out: &mut Vec, dels: &mut Vec, adds: &mut Vec) { + let mut dels = std::mem::take(dels).into_iter(); + let mut adds = std::mem::take(adds).into_iter(); + loop { + let (d, a) = (dels.next(), adds.next()); + if d.is_none() && a.is_none() { + break; + } + let (left, left_below) = match d { + Some(row) => { + let num = row.old.clone(); + SplitSide::from_row(row, "del", num) + } + None => (SplitSide::empty(), None), + }; + let (right, right_below) = match a { + Some(row) => { + let num = row.new.clone(); + SplitSide::from_row(row, "add", num) + } + None => (SplitSide::empty(), None), + }; + out.push(SplitRow { + hunk: None, + left, + right, + below: merge_below(left_below, right_below), + }); + } +} + +fn split_rows(rows: Vec) -> Vec { + let mut out = Vec::new(); + let mut dels: Vec = Vec::new(); + let mut adds: Vec = Vec::new(); + for row in rows { + match row.class { + "diff-line del" => { + if !adds.is_empty() { + flush_pairs(&mut out, &mut dels, &mut adds); + } + dels.push(row); + } + "diff-line add" => adds.push(row), + "diff-line hunk" => { + flush_pairs(&mut out, &mut dels, &mut adds); + out.push(SplitRow { + hunk: Some(row.code), + left: SplitSide::empty(), + right: SplitSide::empty(), + below: None, + }); + } + _ => { + flush_pairs(&mut out, &mut dels, &mut adds); + let left = SplitSide { + class: "ctx", + num: row.old.clone(), + code: row.code.clone(), + anchor: None, + plus_href: None, + }; + let new = row.new.clone(); + let (right, below) = SplitSide::from_row(row, "ctx dup", new); + out.push(SplitRow { + hunk: None, + left, + right, + below, + }); + } + } + } + flush_pairs(&mut out, &mut dels, &mut adds); + out } impl FileView { @@ -234,6 +463,7 @@ impl FileView { has_blob: !blob_href.is_empty(), blob_href, rows, + split_rows: Vec::new(), } } } @@ -262,15 +492,31 @@ pub async fn diff_section( subject: &str, #[default] lang: DiffLang, #[default] comments: LineComments, + #[default] opts: DiffOpts, ) -> Result { let lang = lang.0; let mut comments = comments; - let files: Vec = diff + let anchored = comments.anchors; + let split = opts.split; + let mut files: Vec = diff .files .iter() .enumerate() .map(|(i, file)| FileView::new(i, file, oid, parent, owner, repo, lang, &mut comments)) .collect(); + if split { + for file in &mut files { + file.split_rows = split_rows(std::mem::take(&mut file.rows)); + } + } + let toolbar = opts.enabled.then(|| Toolbar { + unified_href: opts.href(false, opts.ignore_ws), + split_href: opts.href(true, opts.ignore_ws), + ws_href: opts.href(opts.split, !opts.ignore_ws), + split: opts.split, + ignore_ws: opts.ignore_ws, + downloads: opts.downloads.clone(), + }); let nav: Vec = files .iter() .map(|f| NavItem { @@ -293,6 +539,9 @@ pub async fn diff_section( Ok(view! {

(files_label.as_str()) " " (add_label.as_str()) " " (del_label.as_str())

+ if let Some(bar) = toolbar { + diff_toolbar(bar: bar, lang: lang) + } if truncated_files {

(truncated_note.as_str())

} @@ -309,18 +558,48 @@ pub async fn diff_section( } for file in files.into_iter() { - diff_file(file: file, lang: lang) + diff_file(file: file, lang: lang, split: split, anchored: anchored) } }
}) } +/// Unified or split, ignore whitespace, and the patch and diff downloads. #[component] -async fn diff_file(file: FileView, lang: Lang) -> Result { +async fn diff_toolbar(bar: Toolbar, lang: Lang) -> Result { + let unified_on = if bar.split { "false" } else { "true" }; + let split_on = if bar.split { "true" } else { "false" }; + let ws_on = if bar.ignore_ws { "true" } else { "false" }; + Ok(view! { + + }) +} + +#[component] +async fn diff_file(file: FileView, lang: Lang, split: bool, anchored: bool) -> Result { let add_label = format!("+{}", file.additions); let del_label = format!("-{}", file.deletions); let rows = file.rows; + let pairs = file.split_rows; + let has_rows = !rows.is_empty() || !pairs.is_empty(); + let table_class = match (split, anchored) { + (true, true) => "diff-table diff-split anchored", + (true, false) => "diff-table diff-split", + _ => "diff-table", + }; Ok(view! {
@@ -340,12 +619,15 @@ async fn diff_file(file: FileView, lang: Lang) -> Result {

(g::t(lang, K::DiffTooLarge))

} } - if !rows.is_empty() { + if has_rows {
- +
for row in rows.into_iter() { diff_line(row: row, lang: lang) } + for row in pairs.into_iter() { + diff_split_line(row: row, lang: lang, anchored: anchored) + }
} @@ -354,6 +636,75 @@ async fn diff_file(file: FileView, lang: Lang) -> Result { }) } +/// One split row as a ``: the two sides, then, when either has threads or an open form, a +/// full-width row holding them. A hunk header spans the table. +#[component] +async fn diff_split_line(row: SplitRow, lang: Lang, anchored: bool) -> Result { + let SplitRow { + hunk, + left, + right, + below, + } = row; + let (threads, form, ctx) = match below { + Some(below) => (below.threads, below.form, Some(below.ctx)), + None => (Vec::new(), None, None), + }; + let span = if anchored { "6" } else { "4" }; + let is_hunk = hunk.is_some(); + let hunk_text = hunk.unwrap_or_default(); + let left_plus = format!("diff-plus side-{}", left.class); + let left_ln = format!("diff-ln side-{}", left.class); + let left_code = format!("diff-code side-{}", left.class); + let right_plus = format!("diff-plus side-{}", right.class); + let right_ln = format!("diff-ln side-{}", right.class); + let right_code = format!("diff-code side-{}", right.class); + Ok(view! { + + if is_hunk { + + (hunk_text.as_str()) + + } else { + + if anchored { + + if let Some(href) = left.plus_href { + "+" + } + + } + (left.num.as_str()) + (left.code.as_str()) + if anchored { + + if let Some(href) = right.plus_href { + "+" + } + + } + (right.num.as_str()) + (right.code.as_str()) + + } + if let Some(ctx) = ctx { + + +
+ for thread in threads.into_iter() { + review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files") + } + if let Some(form) = form { + inline_comment_form(form: form, lang: lang) + } +
+ + + } + + }) +} + /// One diff line as a ``: the line itself, then, when it has threads or an open form, a /// full-width row holding them. #[component]