diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index 83e173d..ac9b1bf 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -28,6 +28,7 @@ pub mod secret; pub mod server_settings; pub mod session; pub mod store; +pub mod suggestions; pub mod time; pub mod token; pub mod totp; diff --git a/crates/forge-core/src/suggestions.rs b/crates/forge-core/src/suggestions.rs new file mode 100644 index 0000000..ac1b555 --- /dev/null +++ b/crates/forge-core/src/suggestions.rs @@ -0,0 +1,209 @@ +//! Suggested changes in review comments. A comment whose body holds a fenced block opened with +//! ```suggestion proposes replacing the commented line with the lines of that block. This module +//! splits a body into text and suggestion parts, and computes the replacement of one line of a +//! file. The web layer checks the replacement against the head and the git layer commits it. + +/// One part of a comment body: markdown text, or the lines of a suggestion block. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Part { + Text(String), + Suggestion(Vec), +} + +/// Why a suggestion cannot replace a line. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ApplyError { + /// The file has no such line. + OutOfRange, + /// The line no longer reads what the comment was written against. + Changed, +} + +/// Splits a comment body into text and suggestion parts, in order. A suggestion opens with three +/// or more backticks and the word `suggestion`, and closes with a line of at least as many +/// backticks. A fence that never closes is text, as is any other code fence. +pub fn split_body(body: &str) -> Vec { + let lines: Vec<&str> = body.split('\n').collect(); + let mut parts = Vec::new(); + let mut text: Vec<&str> = Vec::new(); + let mut i = 0; + while i < lines.len() { + if let Some(ticks) = open_fence(lines[i]) { + let close = (i + 1..lines.len()).find(|&j| closes_fence(lines[j], ticks)); + if let Some(close) = close { + if !text.is_empty() { + parts.push(Part::Text(text.join("\n"))); + text.clear(); + } + let block = lines[i + 1..close] + .iter() + .map(|line| line.trim_end_matches('\r').to_owned()) + .collect(); + parts.push(Part::Suggestion(block)); + i = close + 1; + continue; + } + } + text.push(lines[i]); + i += 1; + } + if !text.is_empty() { + parts.push(Part::Text(text.join("\n"))); + } + parts +} + +/// The number of backticks of a line that opens a suggestion block, if it does. +fn open_fence(line: &str) -> Option { + let ticks = line.bytes().take_while(|&b| b == b'`').count(); + (ticks >= 3 && line[ticks..].trim() == "suggestion").then_some(ticks) +} + +/// Whether `line` closes a fence opened with `ticks` backticks. +fn closes_fence(line: &str, ticks: usize) -> bool { + let trimmed = line.trim(); + trimmed.len() >= ticks && trimmed.bytes().all(|b| b == b'`') +} + +/// The text of the commented line, read from the last line of a stored diff hunk. The hunk ends +/// at the commented line, and that line is an added or a context line. `None` for a deleted line. +pub fn hunk_line(diff_hunk: &str) -> Option<&str> { + let last = diff_hunk.lines().last()?; + match last.as_bytes().first()? { + b'+' | b' ' => Some(&last[1..]), + _ => None, + } +} + +/// `text` with line `line` (1-based) replaced by `replacement`, when that line still reads +/// `expected`. An empty replacement deletes the line. The trailing newline of `text` is kept. +pub fn replace_line( + text: &str, + line: u32, + expected: &str, + replacement: &[String], +) -> Result { + if text.is_empty() { + return Err(ApplyError::OutOfRange); + } + let index = (line as usize) + .checked_sub(1) + .ok_or(ApplyError::OutOfRange)?; + let ends_with_newline = text.ends_with('\n'); + let body = text.strip_suffix('\n').unwrap_or(text); + let mut lines: Vec<&str> = body.split('\n').collect(); + let current = lines.get(index).ok_or(ApplyError::OutOfRange)?; + if current.trim_end_matches('\r') != expected.trim_end_matches('\r') { + return Err(ApplyError::Changed); + } + let replacement: Vec<&str> = replacement.iter().map(String::as_str).collect(); + lines.splice(index..=index, replacement); + let mut out = lines.join("\n"); + if ends_with_newline { + out.push('\n'); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lines(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn body_without_a_suggestion_is_one_text_part() { + assert_eq!( + split_body("looks fine\n\n```rust\nlet x = 1;\n```"), + vec![Part::Text("looks fine\n\n```rust\nlet x = 1;\n```".into())] + ); + } + + #[test] + fn suggestion_block_is_split_out_with_its_surrounding_text() { + let body = "Try this:\n```suggestion\nlet y = 2;\n```\nThanks"; + assert_eq!( + split_body(body), + vec![ + Part::Text("Try this:".into()), + Part::Suggestion(lines(&["let y = 2;"])), + Part::Text("Thanks".into()), + ] + ); + } + + #[test] + fn empty_suggestion_and_several_blocks_are_parsed_in_order() { + let body = "```suggestion\n```\n\n````suggestion\na\n```\nb\n````"; + assert_eq!( + split_body(body), + vec![ + Part::Suggestion(vec![]), + Part::Text("".into()), + Part::Suggestion(lines(&["a", "```", "b"])), + ] + ); + } + + #[test] + fn unclosed_suggestion_fence_stays_text() { + let body = "```suggestion\nlet y = 2;"; + assert_eq!(split_body(body), vec![Part::Text(body.into())]); + } + + #[test] + fn hunk_last_line_gives_the_commented_text() { + assert_eq!(hunk_line("-old\n+let x = 1;"), Some("let x = 1;")); + assert_eq!(hunk_line(" ctx\n more"), Some("more")); + assert_eq!(hunk_line("+a\n-gone"), None); + assert_eq!(hunk_line(""), None); + } + + #[test] + fn replace_line_swaps_one_line_and_keeps_the_rest() { + let text = "a\nb\nc\n"; + assert_eq!( + replace_line(text, 2, "b", &lines(&["B"])), + Ok("a\nB\nc\n".into()) + ); + } + + #[test] + fn replace_line_can_expand_delete_and_keep_a_missing_newline() { + assert_eq!( + replace_line("a\nb", 2, "b", &lines(&["b1", "b2"])), + Ok("a\nb1\nb2".into()) + ); + assert_eq!(replace_line("a\nb\nc\n", 2, "b", &[]), Ok("a\nc\n".into())); + } + + #[test] + fn replace_line_refuses_a_changed_or_missing_line() { + assert_eq!( + replace_line("a\nb\n", 2, "old", &lines(&["x"])), + Err(ApplyError::Changed) + ); + assert_eq!( + replace_line("a\nb\n", 3, "b", &lines(&["x"])), + Err(ApplyError::OutOfRange) + ); + assert_eq!( + replace_line("a\n", 0, "a", &lines(&["x"])), + Err(ApplyError::OutOfRange) + ); + assert_eq!( + replace_line("", 1, "", &lines(&["x"])), + Err(ApplyError::OutOfRange) + ); + } + + #[test] + fn replace_line_ignores_carriage_returns_on_the_expected_line() { + assert_eq!( + replace_line("a\r\nb\r\n", 1, "a", &lines(&["A"])), + Ok("A\nb\r\n".into()) + ); + } +} diff --git a/crates/forge-git/src/pulls.rs b/crates/forge-git/src/pulls.rs index 79fd01d..926ac39 100644 --- a/crates/forge-git/src/pulls.rs +++ b/crates/forge-git/src/pulls.rs @@ -632,6 +632,122 @@ pub async fn rebase_commits( Ok(RebaseResult::Clean { tip, count }) } +/// One file of a commit made by [`commit_file_edit`]. +#[derive(Debug, Clone, Copy)] +pub struct FileEdit<'a> { + /// Repo path of the file. It must be a regular file in the base commit. + pub path: &'a str, + /// The new content of the file. + pub content: &'a [u8], +} + +static EDIT_INDEX_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Commits `edit` on top of `base` and moves `refname` from `base` to the new commit, only if the +/// ref still holds `base`. A moved ref gives `Error::RefMoved` and nothing changes. The new tree is +/// `base`'s tree with the one file replaced and its mode kept. It is built in a temporary index in +/// the repo, so no working tree is needed. The commit's only parent is `base`. Returns its id. +#[allow(clippy::too_many_arguments)] +pub async fn commit_file_edit( + env: &GitEnv, + repo: &Path, + refname: &str, + base: &str, + edit: &FileEdit<'_>, + message: &str, + author: &Signature, + committer: &Signature, +) -> Result { + validate_ref(refname)?; + validate_oid(base)?; + validate_blob_path(edit.path)?; + let seq = EDIT_INDEX_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let index = repo.join(format!("forge-edit-index-{}-{seq}", std::process::id())); + let result = edit_and_commit( + env, repo, &index, refname, base, edit, message, author, committer, + ) + .await; + // The index is scratch space. A leftover file is harmless, but do not keep it. + let _ = tokio::fs::remove_file(&index).await; + result +} + +#[allow(clippy::too_many_arguments)] +async fn edit_and_commit( + env: &GitEnv, + repo: &Path, + index: &Path, + refname: &str, + base: &str, + edit: &FileEdit<'_>, + message: &str, + author: &Signature, + committer: &Signature, +) -> Result { + let blob = GitCommand::new(env, "hash-object") + .git_dir(repo) + .arg("-w") + .arg("--stdin") + .output_stdin(edit.content) + .await?; + let blob = String::from_utf8_lossy(&blob).trim().to_owned(); + validate_oid(&blob)?; + + GitCommand::new(env, "read-tree") + .git_dir(repo) + .env("GIT_INDEX_FILE", index) + .user_arg(base)? + .status() + .await?; + + // `ls-files -s` gives ` \t`. The path must be the file itself, and a + // regular file: a symlink or a submodule is not something a suggestion can rewrite. + let listing = GitCommand::new(env, "ls-files") + .git_dir(repo) + .env("GIT_INDEX_FILE", index) + .arg("-s") + .arg("-z") + .arg("--") + .user_arg(edit.path)? + .output() + .await?; + let entry = + String::from_utf8_lossy(listing.split(|b| *b == 0).next().unwrap_or_default()).into_owned(); + let mode = match entry.split_once('\t') { + Some((meta, path)) if path == edit.path => meta.split_whitespace().next().unwrap_or(""), + _ => "", + }; + if mode != "100644" && mode != "100755" { + return Err(Error::InvalidInput(format!( + "{} is not a regular file at this commit", + edit.path + ))); + } + let mode = mode.to_owned(); + + GitCommand::new(env, "update-index") + .git_dir(repo) + .env("GIT_INDEX_FILE", index) + .arg("--add") + .arg("--cacheinfo") + .user_arg(&mode)? + .user_arg(&blob)? + .user_arg(edit.path)? + .status() + .await?; + + let tree = GitCommand::new(env, "write-tree") + .git_dir(repo) + .env("GIT_INDEX_FILE", index) + .output() + .await?; + let tree = String::from_utf8_lossy(&tree).trim().to_owned(); + + let commit = commit_tree(env, repo, &tree, &[base], message, author, committer).await?; + update_ref_cas(env, repo, refname, &commit, base).await?; + Ok(commit) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index bc0427e..77f2cca 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -996,6 +996,23 @@ if (/^#L\d+$/.test(location.hash)) { logSelect(location.hash.slice(1), true); } }); + // "Suggest change" (a button with data-suggest in a comment form) puts a ```suggestion block that + // holds the commented line into the form's comment box, at the caret. No request is made. + document.addEventListener('click', function (e) { + var btn = e.target && e.target.closest ? e.target.closest('[data-suggest]') : null; + if (!btn) { return; } + e.preventDefault(); + var form = btn.closest('form'); + var area = form ? form.querySelector('textarea[name="body"]') : null; + if (!area) { return; } + var block = '```suggestion\n' + btn.getAttribute('data-suggest') + '\n```\n'; + var start = area.selectionStart != null ? area.selectionStart : area.value.length; + var end = area.selectionEnd != null ? area.selectionEnd : start; + area.value = area.value.slice(0, start) + block + area.value.slice(end); + area.focus(); + area.setSelectionRange(start + block.length, start + block.length); + }); + // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose diff --git a/crates/forge-web/src/ci/live.rs b/crates/forge-web/src/ci/live.rs index 3cea8c2..5e7268d 100644 --- a/crates/forge-web/src/ci/live.rs +++ b/crates/forge-web/src/ci/live.rs @@ -80,7 +80,7 @@ impl CiLive { /// One keyed set of counters. A key has an entry only while it has a receiver or a bump is due. #[derive(Default)] -struct Signals { +pub(crate) struct Signals { counters: Mutex>>, } @@ -89,7 +89,7 @@ impl Signals { self.counters.lock().unwrap_or_else(PoisonError::into_inner) } - fn subscribe(&self, key: &str) -> watch::Receiver { + pub(crate) fn subscribe(&self, key: &str) -> watch::Receiver { self.counters() .entry(key.to_owned()) .or_insert_with(|| watch::channel(0).0) @@ -98,7 +98,7 @@ impl Signals { /// Counts one change. Without a subscriber there is no entry, so the bump is a no-op. An entry /// whose last receiver is gone is removed here. - fn bump(&self, key: &str) { + pub(crate) fn bump(&self, key: &str) { let mut counters = self.counters(); let Some(tx) = counters.get(key) else { return; diff --git a/crates/forge-web/src/i18n/pulls_review.rs b/crates/forge-web/src/i18n/pulls_review.rs index 25b0528..e4ea19d 100644 --- a/crates/forge-web/src/i18n/pulls_review.rs +++ b/crates/forge-web/src/i18n/pulls_review.rs @@ -75,6 +75,12 @@ pub enum K { ReviewErrInvalid, ReviewErrBadLine, ReviewErrClosed, + ReviewErrOutdated, + ReviewErrNoPush, + SuggestedChange, + SuggestChange, + ApplySuggestion, + SuggestionOutdated, EditReviewComment, CommentLabel, SaveComment, @@ -290,6 +296,24 @@ pub fn t(lang: Lang, key: K) -> &'static str { (ReviewErrClosed, Tr) => { "Bu çekme isteği kapalı olduğu için yeni incelemeler gönderilemez." } + (ReviewErrOutdated, En) => { + "This suggestion no longer applies to the current head. Reload the page to see the latest code." + } + (ReviewErrOutdated, Tr) => { + "Bu öneri artık güncel başın üzerinde uygulanamıyor. En son kodu görmek için sayfayı yenileyin." + } + (ReviewErrNoPush, En) => { + "You cannot push to this branch, so the suggestion cannot be applied." + } + (ReviewErrNoPush, Tr) => "Bu dala push yapamadığınız için öneri uygulanamaz.", + (SuggestChange, En) => "Suggest change", + (SuggestChange, Tr) => "Değişiklik öner", + (SuggestedChange, En) => "Suggested change", + (SuggestedChange, Tr) => "Önerilen değişiklik", + (ApplySuggestion, En) => "Apply suggestion", + (ApplySuggestion, Tr) => "Öneriyi uygula", + (SuggestionOutdated, En) => "This suggestion is outdated", + (SuggestionOutdated, Tr) => "Bu öneri güncel değil", (EditReviewComment, En) => "Edit review comment", (EditReviewComment, Tr) => "İnceleme yorumunu düzenle", (CommentLabel, En) => "Comment", @@ -479,6 +503,12 @@ pub const ALL: &[K] = &[ K::ReviewErrInvalid, K::ReviewErrBadLine, K::ReviewErrClosed, + K::ReviewErrOutdated, + K::ReviewErrNoPush, + K::SuggestedChange, + K::SuggestChange, + K::ApplySuggestion, + K::SuggestionOutdated, K::EditReviewComment, K::CommentLabel, K::SaveComment, diff --git a/crates/forge-web/src/pages/issue_parts.rs b/crates/forge-web/src/pages/issue_parts.rs index ae4da8d..ef4cfbd 100644 --- a/crates/forge-web/src/pages/issue_parts.rs +++ b/crates/forge-web/src/pages/issue_parts.rs @@ -20,6 +20,7 @@ use crate::i18n::issues::{self as g, K}; use crate::notify::{self, Activity}; use crate::pages::edit_history::{edit_counts, history_href, thread_edit_counts}; use crate::pages::notifications::{NotifyBox, notify_box}; +use crate::pages::pull_reviews::suggest_states; use crate::pages::repo_ctx::RepoCtx; use crate::pages::tree::link_context; use crate::render::markdown::{LinkContext, render_markdown}; @@ -899,6 +900,10 @@ async fn review_entries( ) .is_ok(); let edits = thread_edit_counts(state, &threads).await?; + let suggest = match store.pull_by_number(&ctx.repo.id, item.number).await? { + Some(pr) => suggest_states(state, ctx, &pr, viewer(ctx), &threads).await?, + None => Default::default(), + }; let thread_ctx = ThreadCtx { pr_href: repo_href( &ctx.repo.owner_name, @@ -915,6 +920,7 @@ async fn review_entries( tz: tz.to_owned(), link: Some(link.clone()), edits, + suggest: std::sync::Arc::new(suggest), }; let mut keyed = Vec::new(); diff --git a/crates/forge-web/src/pages/pull_files.rs b/crates/forge-web/src/pages/pull_files.rs index aee0482..08190ef 100644 --- a/crates/forge-web/src/pages/pull_files.rs +++ b/crates/forge-web/src/pages/pull_files.rs @@ -5,6 +5,7 @@ //! are in `pull_reviews`. use std::collections::HashMap; +use std::sync::Arc; use forge_core::{Action, IssueState, Side, Thread, authorize}; use forge_git::command::ObjectSource; @@ -21,7 +22,7 @@ use crate::i18n::pulls::{self as g, K}; use crate::i18n::{self, Lang}; use crate::pages::edit_history::thread_edit_counts; use crate::pages::issue_parts::{csrf_of, may_converse, parse_number, triage, viewer}; -use crate::pages::pull_reviews::{error_text_in, pull_diff}; +use crate::pages::pull_reviews::{error_text_in, pull_diff, suggest_states}; use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header, pull_subnav_in}; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; @@ -175,6 +176,7 @@ async fn pull_files(cx: &Cx) -> Result { .await?; let pending = threads.iter().filter(|t| t.root.pending).count(); let edits = thread_edit_counts(state, &threads).await?; + let suggest = suggest_states(state, &ctx, &pr, viewer(&ctx), &threads).await?; let mut by_line: HashMap<(usize, Side, u32), Vec> = HashMap::new(); for thread in threads.into_iter().filter(|t| !t.root.outdated) { if let Some(index) = file_index(&diff, &thread.root.path) { @@ -197,6 +199,7 @@ async fn pull_files(cx: &Cx) -> Result { tz: ctx.viewer_tz().to_owned(), link: Some(link), edits, + suggest: Arc::new(suggest), }; let comments = LineComments { anchors: can_comment && !opts.ignore_ws, @@ -208,6 +211,8 @@ async fn pull_files(cx: &Cx) -> Result { }; let error = review_error_from(lang, cx); + // The page follows the pull request's event stream: a change re-renders it. + let live = format!("{href}/events"); let owner = ctx.repo.owner_name.clone(); let name = ctx.repo.name.clone(); let parent = pr.merge_base.clone(); @@ -222,12 +227,14 @@ async fn pull_files(cx: &Cx) -> Result { if let Some(message) = error { alert(message: message.as_str()) } - if can_review { - review_bar(lang: lang, pr_href: href.clone(), csrf: csrf.clone(), pending: pending, is_author: is_author) - } - 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, opts: opts) +
+ if can_review { + review_bar(lang: lang, pr_href: href.clone(), csrf: csrf.clone(), pending: pending, is_author: is_author) + } + 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, opts: opts) +
) }) } diff --git a/crates/forge-web/src/pages/pull_reviews.rs b/crates/forge-web/src/pages/pull_reviews.rs index 672d162..9cfc548 100644 --- a/crates/forge-web/src/pages/pull_reviews.rs +++ b/crates/forge-web/src/pages/pull_reviews.rs @@ -9,10 +9,15 @@ //! dismisses. Archived repos refuse every write. Closed or merged pull requests accept comments //! and replies but no new reviews. +use std::collections::HashMap; + +use forge_core::protection::effective; use forge_core::reviews::{ReviewComment, ReviewState, Side}; -use forge_core::{Action, IssueState, PullRequest, User, authorize}; +use forge_core::suggestions::{Part, hunk_line, replace_line, split_body}; +use forge_core::{Action, IssueState, PullRequest, Thread, User, authorize}; +use forge_git::browse::read_text_blob; use forge_git::history::{CommitDiff, DiffStatus, FileDiff, LineKind}; -use forge_git::pulls::range_diff_files; +use forge_git::pulls::{FileEdit, Signature, commit_file_edit, range_diff_files}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -25,15 +30,22 @@ use topcoat::view::{View, view}; use crate::auth::require_user; use crate::i18n::pulls_review::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::internal::{may_push_directly, trigger_maintenance}; use crate::notify::{self, Activity}; use crate::pages::issue_parts::{check_write, csrf_of, may_change, may_converse, parse_number}; +use crate::pages::pulls_merge::contact_email; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, load_repo}; +use crate::post_update::after_ref_update; use crate::state::AppState; use crate::views::diff::LIMITS; -use crate::views::{alert, repo_href, shell}; +use crate::views::review_thread::SuggestState; +use crate::views::{alert, now_unix, repo_href, shell}; use crate::webhooks::emit::{Sender, emit_review}; +/// The largest file a suggestion is applied to, in bytes. +const MAX_SUGGESTED_FILE: usize = 4 << 20; + path_param!(owner); path_param!(repo); path_param!(number); @@ -47,6 +59,10 @@ pub(crate) const ERR_EMPTY: &str = "empty"; pub(crate) const ERR_INVALID: &str = "invalid"; pub(crate) const ERR_BAD_LINE: &str = "bad_line"; pub(crate) const ERR_CLOSED: &str = "closed"; +/// A suggestion no longer applies to the head, so it is not applied. +pub(crate) const ERR_OUTDATED: &str = "outdated"; +/// The viewer may not push to the pull request's head branch, so cannot apply a suggestion. +pub(crate) const ERR_NO_PUSH: &str = "no_push"; /// The message for a `review_error` code in `lang`, or `None` for an unknown code. pub(crate) fn error_text_in(lang: Lang, code: &str) -> Option<&'static str> { @@ -57,6 +73,8 @@ pub(crate) fn error_text_in(lang: Lang, code: &str) -> Option<&'static str> { ERR_INVALID => Some(g::t(lang, K::ReviewErrInvalid)), ERR_BAD_LINE => Some(g::t(lang, K::ReviewErrBadLine)), ERR_CLOSED => Some(g::t(lang, K::ReviewErrClosed)), + ERR_OUTDATED => Some(g::t(lang, K::ReviewErrOutdated)), + ERR_NO_PUSH => Some(g::t(lang, K::ReviewErrNoPush)), _ => None, } } @@ -88,6 +106,8 @@ struct ReviewForm { reason: String, /// `1` to resolve a thread, `0` to unresolve it. resolved: String, + /// The index of the suggestion block to apply, among the comment's suggestion blocks. + block: String, /// The tab the form was posted from: `files` or anything else for the conversation. #[serde(rename = "return")] ret: String, @@ -222,6 +242,99 @@ fn refusal(tab: &str, code: &str, anchor: &str) -> SeeOther { see_other(format!("{tab}?review_error={code}{anchor}")) } +// Suggested changes + +/// Whether the viewer may apply a suggestion to the head of `pr`: signed in with Write, the head +/// branch lives in this repo, the repo is not archived, and a restricted branch rule does not +/// bar them from pushing. +async fn may_apply( + state: &AppState, + ctx: &RepoCtx, + pr: &PullRequest, + viewer: Option<&User>, +) -> Result { + let Some(user) = viewer else { + return Ok(false); + }; + if pr.head_repo_id.as_ref() != Some(&ctx.repo.id) || ctx.repo.archived { + return Ok(false); + } + if authorize(Some(user), &ctx.repo, ctx.role, ctx.org_role, Action::Write).is_err() { + return Ok(false); + } + let rules = state.store.list_branch_rules(&ctx.repo.id).await?; + let rule = effective(&rules, &ctx.repo.default_branch, &pr.head_branch); + if rule.restrict_push { + return Ok(may_push_directly(&state.store, &ctx.repo, &user.id).await?); + } + Ok(true) +} + +/// The lines of suggestion block `index` (counted from 0) of `body`, if it has one. +fn suggestion_at(body: &str, index: usize) -> Option> { + split_body(body) + .into_iter() + .filter_map(|part| match part { + Part::Suggestion(lines) => Some(lines), + Part::Text(_) => None, + }) + .nth(index) +} + +/// Whether the first suggestion of `root` still applies to `current`, the head's text of its file. +fn suggestion_applies(current: &str, root: &ReviewComment) -> bool { + let (Some(expected), Some(lines)) = (hunk_line(&root.diff_hunk), suggestion_at(&root.body, 0)) + else { + return false; + }; + replace_line(current, root.line, expected, &lines).is_ok() +} + +/// The suggestion state of each thread of the pull request whose root proposes a change, keyed by +/// root id. A suggestion is `Ready` when it applies to the head and the viewer may apply it, and +/// `Outdated` when it no longer applies. A closed pull request shows none. +pub(crate) async fn suggest_states( + state: &AppState, + ctx: &RepoCtx, + pr: &PullRequest, + viewer: Option<&User>, + threads: &[Thread], +) -> Result> { + let mut states = HashMap::new(); + if is_closed(pr) { + return Ok(states); + } + let pushable = may_apply(state, ctx, pr, viewer).await?; + for thread in threads { + let root = &thread.root; + if root.pending || root.side != Side::New || suggestion_at(&root.body, 0).is_none() { + continue; + } + let current = read_text_blob(&ctx.path, &pr.head_oid, &root.path, MAX_SUGGESTED_FILE) + .ok() + .flatten(); + let applies = !root.outdated + && current + .as_deref() + .is_some_and(|text| suggestion_applies(text, root)); + if !applies { + states.insert(root.id.clone(), SuggestState::Outdated); + } else if pushable { + states.insert(root.id.clone(), SuggestState::Ready); + } + } + Ok(states) +} + +/// The signature of `user` as an author or committer of a suggestion commit. +fn signature_of(state: &AppState, user: &User) -> Signature { + Signature { + name: user.username.clone(), + email: contact_email(&state.config.base_url, user), + time_unix: now_unix(), + } +} + // Line comments /// Adds a line comment (single, or into the author's pending review) on the Files tab. The @@ -284,10 +397,12 @@ async fn review_comment_post(cx: &Cx, Form(form): Form) -> Result Ok(see_other(format!( - "{files}#L-{file_index}-{}-{line}", - side.as_str() - ))), + Ok(_) => { + Ok(see_other(format!( + "{files}#L-{file_index}-{}-{line}", + side.as_str() + ))) + } Err(forge_core::Error::Invalid(_)) => { Ok(see_other(format!("{back}&review_error={ERR_INVALID}"))) } @@ -319,7 +434,9 @@ async fn review_comment_reply(cx: &Cx, Form(form): Form) -> Result Ok(see_other(format!("{tab}{anchor}"))), + Ok(_) => { + Ok(see_other(format!("{tab}{anchor}"))) + } Err(forge_core::Error::Invalid(_)) => Ok(refusal(&tab, ERR_INVALID, &anchor)), Err(e) => Err(e.into()), } @@ -418,11 +535,13 @@ async fn review_comment_edit_save(cx: &Cx, Form(form): Form) -> Resu .edit_review_comment(&comment.id, &form.body) .await { - Ok(()) => Ok(see_other(format!( - "{}#rc-{}", - tab_url(&ctx, number, &form.ret), - root_of(&comment) - ))), + Ok(()) => { + Ok(see_other(format!( + "{}#rc-{}", + tab_url(&ctx, number, &form.ret), + root_of(&comment) + ))) + } Err(forge_core::Error::Invalid(_)) => Ok(refusal(&edit_url, ERR_INVALID, "")), Err(e) => Err(e.into()), } @@ -488,6 +607,97 @@ async fn review_comment_resolve(cx: &Cx, Form(form): Form) -> Result Ok(see_other(format!("{tab}{anchor}"))) } +/// Applies suggestion block `block` of a root comment to the pull request's head. The commit is +/// made by the viewer, with the commenter as co-author, and replaces the commented line. The +/// thread is then resolved and the push flow runs, as for any ref update. Refused when the pull +/// request is closed, the viewer may not push to the head, or the line no longer reads what the +/// suggestion was written against. +#[route(POST "/{owner}/{repo}/pulls/{number}/review_comments/{comment_id}/apply")] +async fn review_comment_apply(cx: &Cx, Form(form): Form) -> Result { + let number = parse_number(path_param::(cx))?; + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let (user, session) = require_user(cx).await?; + check_write(&ctx, &session, &form.csrf)?; + let state = app_context::(cx); + let pr = pull_for(state, &ctx, number).await?; + let comment = comment_on_pull(state, &pr, &user, path_param::(cx)).await?; + let files = tab_url(&ctx, number, &form.ret); + let anchor = format!("#rc-{}", comment.id); + if comment.reply_to.is_some() || comment.pending || comment.side != Side::New { + return Ok(refusal(&files, ERR_INVALID, &anchor)); + } + if is_closed(&pr) { + return Ok(refusal(&files, ERR_CLOSED, &anchor)); + } + if !may_apply(state, &ctx, &pr, Some(&user)).await? { + return Ok(refusal(&files, ERR_NO_PUSH, &anchor)); + } + let block = form.block.parse::().unwrap_or(0); + let Some(lines) = suggestion_at(&comment.body, block) else { + return Ok(refusal(&files, ERR_INVALID, &anchor)); + }; + let Some(expected) = hunk_line(&comment.diff_hunk) else { + return Ok(refusal(&files, ERR_INVALID, &anchor)); + }; + let head = pr.head_oid.clone(); + let current = if comment.outdated { + None + } else { + read_text_blob(&ctx.path, &head, &comment.path, MAX_SUGGESTED_FILE) + .ok() + .flatten() + }; + let Some(edited) = + current.and_then(|text| replace_line(&text, comment.line, expected, &lines).ok()) + else { + return Ok(refusal(&files, ERR_OUTDATED, &anchor)); + }; + + let author = signature_of(state, &user); + let (trailer_name, trailer_email) = match state.store.user_by_id(&comment.author_id).await? { + Some(commenter) => { + let email = contact_email(&state.config.base_url, &commenter); + (commenter.username, email) + } + None => (comment.author_name.clone(), author.email.clone()), + }; + let message = + format!("Apply suggestion from review\n\nCo-authored-by: {trailer_name} <{trailer_email}>"); + let refname = format!("refs/heads/{}", pr.head_branch); + let file = FileEdit { + path: &comment.path, + content: edited.as_bytes(), + }; + let commit = match commit_file_edit( + &state.git, &ctx.path, &refname, &head, &file, &message, &author, &author, + ) + .await + { + Ok(commit) => commit, + Err(forge_git::error::Error::RefMoved(_)) => { + return Ok(refusal(&files, ERR_STALE, &anchor)); + } + Err(forge_git::error::Error::InvalidInput(_)) => { + return Ok(refusal(&files, ERR_OUTDATED, &anchor)); + } + Err(e) => return Err(e.into()), + }; + + // The commit has landed, so the steps after it log their failures and do not refuse. + if let Err(e) = state + .store + .set_thread_resolved(&comment.id, &user.id, true) + .await + { + tracing::error!(error = %e, repo_id = %ctx.repo.id, "suggestion: resolving the thread failed"); + } + trigger_maintenance(&state.git, &ctx.repo.id); + if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &head, &commit).await { + tracing::error!(error = %e, repo_id = %ctx.repo.id, ref_name = %refname, "suggestion: post-update failed"); + } + Ok(see_other(format!("{files}{anchor}"))) +} + // Reviews /// Submits the author's pending review as a comment, approval or change request. The PR author @@ -619,7 +829,9 @@ async fn review_dismiss(cx: &Cx, Form(form): Form) -> Result Ok(see_other(format!("{tab}#review-{}", review.id))), + Ok(()) => { + Ok(see_other(format!("{tab}#review-{}", review.id))) + } Err(forge_core::Error::Invalid(_)) => Ok(refusal(&tab, ERR_INVALID, "")), Err(e) => Err(e.into()), } @@ -1180,4 +1392,146 @@ mod tests { let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await; assert_eq!(status, 403); } + + /// The comment body that proposes replacing line 2 of `a.txt` with `text`. + fn suggestion(text: &str) -> String { + format!("Try this:\n```suggestion\n{text}\n```") + } + + /// Posts the apply form for suggestion block 0 of comment `comment_id`. + async fn apply_as( + fx: &Fixture, + number: i64, + token: &str, + comment_id: &str, + ) -> (u16, Option) { + let form = csrf_form(token, &[("block", "0"), ("return", "files")]); + let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{comment_id}/apply"); + let (status, location, _) = send(&fx.router, "POST", &uri, Some(token), Some(form)).await; + (status, location) + } + + #[tokio::test] + async fn applying_a_suggestion_commits_it_to_the_head_and_resolves_the_thread() { + let fx = Fixture::new(Visibility::Public).await; + owner_session(&fx).await; + let number = open_pull(&fx).await; + let before = pull(&fx, number).await.head_oid; + + let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await; + assert_eq!(status, 303); + let root = root_id(&fx, number).await; + let (status, location) = apply_as(&fx, number, "tahinli", &root).await; + assert_eq!(status, 303); + assert!(!location.unwrap().contains("review_error")); + + let pr = pull(&fx, number).await; + assert_ne!( + pr.head_oid, before, + "the head moved to the suggestion commit" + ); + assert_eq!( + git(&fx.bare, &["show", &format!("{}:a.txt", pr.head_oid)]), + "one\ntwo!\nthree" + ); + assert_eq!( + git(&fx.bare, &["log", "-1", "--format=%an", &pr.head_oid]), + "tahinli" + ); + let message = git(&fx.bare, &["log", "-1", "--format=%B", &pr.head_oid]); + assert!( + message.starts_with("Apply suggestion from review"), + "{message}" + ); + assert!( + message.contains("Co-authored-by: tahinli <"), + "commenter trailer: {message}" + ); + assert_eq!(git(&fx.bare, &["rev-parse", "feature"]), pr.head_oid); + let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); + assert!(threads[0].root.resolved, "applying resolves the thread"); + } + + #[tokio::test] + async fn outdated_suggestion_is_shown_without_apply_and_refused() { + let fx = Fixture::new(Visibility::Public).await; + owner_session(&fx).await; + let number = open_pull(&fx).await; + let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await; + assert_eq!(status, 303); + let root = root_id(&fx, number).await; + + // The head moves on: its line 2 no longer reads what the suggestion was written against. + let pr = pull(&fx, number).await; + git(&fx.work, &["checkout", "-q", "feature"]); + std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap(); + git(&fx.work, &["commit", "-q", "-am", "Move line 2"]); + let moved = git(&fx.work, &["rev-parse", "HEAD"]); + git( + &fx.work, + &[ + "push", + "-q", + &fx.bare.to_string_lossy(), + "HEAD:refs/heads/feature", + ], + ); + fx.store + .update_pull_head(&pr.issue.id, &moved) + .await + .unwrap(); + + let page = get(&fx, number, "tahinli").await; + assert!( + page.contains("This suggestion is outdated"), + "outdated note shown" + ); + assert!( + !page.contains("Apply suggestion"), + "no apply button when outdated" + ); + + let (status, location) = apply_as(&fx, number, "tahinli", &root).await; + assert_eq!(status, 303); + assert!(location.unwrap().contains("review_error=outdated")); + assert_eq!( + git(&fx.bare, &["rev-parse", "feature"]), + moved, + "nothing was committed" + ); + let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); + assert!( + !threads[0].root.resolved, + "a refused apply leaves the thread open" + ); + } + + #[tokio::test] + async fn a_reader_without_push_access_cannot_apply_and_sees_no_button() { + let fx = Fixture::new(Visibility::Public).await; + owner_session(&fx).await; + let number = open_pull(&fx).await; + let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await; + assert_eq!(status, 303); + let root = root_id(&fx, number).await; + sign_in(&fx, "rita", "rita").await; + + let page = get(&fx, number, "rita").await; + assert!(page.contains("Suggested change"), "the diff still shows"); + assert!( + !page.contains("Apply suggestion"), + "no apply button without push access" + ); + + let (status, location) = apply_as(&fx, number, "rita", &root).await; + assert_eq!(status, 303); + assert!(location.unwrap().contains("review_error=no_push")); + } + + /// The Files tab of the pull request as `token` sees it. + async fn get(fx: &Fixture, number: i64, token: &str) -> String { + let uri = format!("/tahinli/demo/pulls/{number}/files"); + let (_, _, body) = send(&fx.router, "GET", &uri, Some(token), None).await; + body + } } diff --git a/crates/forge-web/src/pages/pull_view.rs b/crates/forge-web/src/pages/pull_view.rs index d21dae8..231a762 100644 --- a/crates/forge-web/src/pages/pull_view.rs +++ b/crates/forge-web/src/pages/pull_view.rs @@ -789,6 +789,8 @@ async fn pull_conversation( let page_title = frame.page_title.clone(); let header = ctx.head(state, "pulls").await?; let labels_href = repo_href(&owner, &name, "labels.css", ""); + // The conversation follows the pull request's event stream: a change re-renders it. + let live = format!("{href}/events"); Ok(view! { cx => shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()), repo_head(head: header) @@ -798,7 +800,7 @@ async fn pull_conversation( if let Some(message) = review_error { alert(message: message) } -
+
discussion_timeline(lang: lang, discussion: discussion) if review_box_shown { diff --git a/crates/forge-web/src/pages/pulls_merge.rs b/crates/forge-web/src/pages/pulls_merge.rs index f828ada..ddf572e 100644 --- a/crates/forge-web/src/pages/pulls_merge.rs +++ b/crates/forge-web/src/pages/pulls_merge.rs @@ -498,7 +498,7 @@ pub async fn perform_merge( /// The address written into a commit for `user`: their email, or a noreply address on this /// instance's host when they have none. -fn contact_email(base_url: &str, user: &User) -> String { +pub(crate) fn contact_email(base_url: &str, user: &User) -> String { match user .email .as_deref() diff --git a/crates/forge-web/src/pulls_sync.rs b/crates/forge-web/src/pulls_sync.rs index 2a6c122..cb70255 100644 --- a/crates/forge-web/src/pulls_sync.rs +++ b/crates/forge-web/src/pulls_sync.rs @@ -57,12 +57,15 @@ pub async fn sync_pulls_for_ref( { tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: head update failed"); } + // Open pull request pages show the new head, commits and mergeability. + crate::pages::pull_live::bump_pull(state, &repo.id, &issue_id); } let bases = state.store.open_pulls_for_base(&repo.id, branch).await?; for (number, issue_id) in bases { if let Err(e) = sync_base(state, repo, actor_id, number, &issue_id, old, new).await { tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: base update failed"); } + crate::pages::pull_live::bump_pull(state, &repo.id, &issue_id); } Ok(()) } diff --git a/crates/forge-web/src/views/diff.rs b/crates/forge-web/src/views/diff.rs index e80e4b0..a2db4cb 100644 --- a/crates/forge-web/src/views/diff.rs +++ b/crates/forge-web/src/views/diff.rs @@ -21,6 +21,7 @@ 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::i18n::pulls_review::{self as pr_g, K as PrK}; use crate::pages::commits::url_path; use crate::views::review_thread::{ThreadCtx, review_thread_in}; @@ -163,6 +164,8 @@ struct InlineForm { head_oid: String, has_pending: bool, can_review: bool, + /// The text of the commented line, when a suggestion can replace it (a line on the new side). + suggest_line: Option, } /// What renders under a line: its threads and, if open, the form. @@ -429,6 +432,7 @@ impl FileView { head_oid: oid.to_owned(), has_pending: comments.has_pending, can_review: comments.ctx.can_review, + suggest_line: (side == Side::New).then(|| line.text.clone()), }); let below = (!threads.is_empty() || form.is_some()).then(|| RowBelow { threads, @@ -770,12 +774,14 @@ async fn inline_comment_form(form: InlineForm, lang: Lang) -> Result head_oid, has_pending, can_review, + suggest_line, } = form; let review_label = if has_pending { g::t(lang, K::AddReviewComment) } else { g::t(lang, K::StartReview) }; + let suggest_label = pr_g::t(lang, PrK::SuggestChange); Ok(view! {
@@ -792,6 +798,9 @@ async fn inline_comment_form(form: InlineForm, lang: Lang) -> Result if can_review { } + if let Some(text) = suggest_line { + + } (g::t(lang, K::CancelLink))
diff --git a/crates/forge-web/src/views/review_thread.rs b/crates/forge-web/src/views/review_thread.rs index c0255cd..ff48379 100644 --- a/crates/forge-web/src/views/review_thread.rs +++ b/crates/forge-web/src/views/review_thread.rs @@ -6,6 +6,7 @@ use std::collections::HashMap; use std::sync::Arc; +use forge_core::suggestions::{Part, hunk_line, split_body}; use forge_core::{ReviewComment, Thread}; use topcoat::Result; use topcoat::view::{Unescaped, View, component, view}; @@ -16,6 +17,15 @@ use crate::pages::issue_parts::When; use crate::render::markdown::{LinkContext, render_markdown}; use crate::views::{avatar_url, display_name, now_unix, user_href, user_link}; +/// What the Apply control of a suggestion shows. A root without a state shows the diff only. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SuggestState { + /// It applies to the head and the viewer may apply it. + Ready, + /// It no longer applies to the head, so it cannot be applied. + Outdated, +} + /// What a thread needs from its page: where the review POSTs go, the CSRF token, who is viewing /// and what they may do. Built once per page and cloned into each thread. #[derive(Clone, Default)] @@ -39,6 +49,24 @@ pub struct ThreadCtx { pub link: Option, /// Earlier versions per review comment id. A comment in here with a count shows "edited". pub edits: Arc>, + /// The suggestion state of each root comment that proposes a change, keyed by root id. + pub suggest: Arc>, +} + +/// One part of a comment body: rendered markdown, or a suggested change. +#[derive(Clone)] +struct PartRow { + /// The rendered markdown of a text part. Empty for a suggestion. + html: String, + suggestion: bool, + /// The commented line as it reads now, shown as the removed line. Empty when unknown. + old: String, + /// The lines the suggestion puts in place of the commented line. + new_lines: Vec, + /// The index of the suggestion among the comment's blocks, for the apply form. + block: String, + apply_action: Option, + outdated: bool, } /// One comment of a thread, flattened for the view. @@ -48,12 +76,52 @@ struct CommentRow { login: String, avatar: String, when: When, - html: String, + parts: Vec, history_href: Option, edit_href: Option, delete_href: Option, } +/// The parts of a comment body. Each suggestion block becomes a suggestion part: its removed line +/// comes from the stored hunk, and `state` (set only for a root) sets the apply control. +fn body_parts( + comment: &ReviewComment, + ctx: &ThreadCtx, + state: Option, +) -> Vec { + let old = hunk_line(&comment.diff_hunk).unwrap_or_default().to_owned(); + let mut block = 0usize; + split_body(&comment.body) + .into_iter() + .map(|part| match part { + Part::Text(text) => PartRow { + html: render_markdown(&text, ctx.link.as_ref()), + suggestion: false, + old: String::new(), + new_lines: Vec::new(), + block: String::new(), + apply_action: None, + outdated: false, + }, + Part::Suggestion(lines) => { + let index = block; + block += 1; + let apply_action = (state == Some(SuggestState::Ready)) + .then(|| format!("{}/review_comments/{}/apply", ctx.pr_href, comment.id)); + PartRow { + html: String::new(), + suggestion: true, + old: old.clone(), + new_lines: lines, + block: index.to_string(), + apply_action, + outdated: state == Some(SuggestState::Outdated), + } + } + }) + .collect() +} + /// The controls and content of a thread, shared by the open and the collapsed (resolved) forms. struct ThreadParts { location: String, @@ -70,16 +138,23 @@ struct ThreadParts { lang: Lang, } -fn comment_row(comment: ReviewComment, ctx: &ThreadCtx, now: i64, lang: Lang) -> CommentRow { +fn comment_row( + comment: ReviewComment, + ctx: &ThreadCtx, + now: i64, + lang: Lang, + state: Option, +) -> CommentRow { let mine = ctx.viewer_id.as_deref() == Some(comment.author_id.as_str()); let base = format!("{}/review_comments/{}", ctx.pr_href, comment.id); let edited = ctx.edits.get(&comment.id).is_some_and(|count| *count > 0); + let parts = body_parts(&comment, ctx, state); CommentRow { avatar: avatar_url(&comment.author_name, None), author: display_name(lang, &comment.author_name), login: comment.author_name.clone(), when: When::new(lang, &comment.created_at, &ctx.tz, now), - html: render_markdown(&comment.body, ctx.link.as_ref()), + parts, history_href: edited .then(|| format!("{}/history/review_comment/{}", ctx.pr_href, comment.id)), edit_href: (mine && ctx.can_comment).then(|| format!("{base}/edit")), @@ -116,6 +191,7 @@ pub async fn review_thread_in( let now = now_unix(); let return_to = return_to.to_owned(); let Thread { root, replies } = thread; + let suggest = ctx.suggest.get(&root.id).copied(); let anchor = format!("rc-{}", root.id); let location = format!("{}:{}", root.path, root.line); let hunk = (show_hunk && !root.diff_hunk.is_empty()).then(|| root.diff_hunk.clone()); @@ -130,9 +206,14 @@ pub async fn review_thread_in( } else { ("1", g::t(lang, K::Resolve)) }; + // Only the root's suggestions are applied: the commented line is the root's. let comments: Vec = std::iter::once(root) .chain(replies) - .map(|comment| comment_row(comment, &ctx, now, lang)) + .enumerate() + .map(|(index, comment)| { + let state = if index == 0 { suggest } else { None }; + comment_row(comment, &ctx, now, lang, state) + }) .collect(); let parts = ThreadParts { @@ -318,7 +399,7 @@ async fn thread_comment( login, avatar, when, - html, + parts, history_href, edit_href, delete_href, @@ -349,7 +430,62 @@ async fn thread_comment( } -
(Unescaped::new_unchecked(html))
+ for part in parts.into_iter() { + comment_part(part: part, csrf: csrf.clone(), return_to: return_to.clone(), + lang: lang) + } }) } + +/// One part of a comment body: its markdown, or a suggested change with its removed and added +/// lines, the Apply control when it applies, and a note when it is outdated. +#[component] +async fn comment_part( + part: PartRow, + csrf: String, + return_to: String, + lang: Lang, +) -> Result { + let PartRow { + html, + suggestion, + old, + new_lines, + block, + apply_action, + outdated, + } = part; + let caption = g::t(lang, K::SuggestedChange); + let apply_label = g::t(lang, K::ApplySuggestion); + let outdated_text = g::t(lang, K::SuggestionOutdated); + let removed_sign = "-"; + let added_sign = "+"; + Ok(view! { + if !suggestion { +
(Unescaped::new_unchecked(html))
+ } + if suggestion { +
+
(caption)
+ if !old.is_empty() { +
(removed_sign)(old.as_str())
+ } + for line in new_lines.into_iter() { +
(added_sign)(line.as_str())
+ } + if let Some(action) = apply_action { +
+ + + + +
+ } + if outdated { +

(outdated_text)

+ } +
+ } + }) +} diff --git a/docs/architecture.md b/docs/architecture.md index 3a1b65d..4dc3cf4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -501,6 +501,8 @@ Known gaps: - Mergeability checked with `git merge-tree --write-tree`, recomputed when base or head moves. Optional `refs/pull/N/merge`. - Three-dot diffs from the merge base, rename detection (`-M`), binary detection, lazy-loaded large files. - Reviews (approve, request changes, comment) and review comments anchored to commit, path, line, side, and hunk. Comments are marked outdated, not deleted. +- Suggested changes: a comment body with a ```` ```suggestion ```` block proposes replacing the commented line. It renders as a removed and an added line. Anyone with push access to a same-repo head branch can apply it while the PR is open and the line still reads what the suggestion was written against. The apply writes one commit on the head (tree built with `hash-object`, `read-tree`, `update-index`, `write-tree`, `commit-tree`, and a compare-and-swap `update-ref`), authored by the viewer with `Co-authored-by:` the commenter, resolves the thread, and runs the normal push flow. Single line only; multi-line ranges and batched suggestions are not supported. +- Live updates: the Files and Conversation tabs follow `/{owner}/{repo}/pulls/{n}/events` (SSE), and re-render on any review write or head update. - Merge strategies: merge commit (`commit-tree` from merge-tree output), squash, rebase, fast-forward only. - `range-diff` for "what changed since the last review." AGit (`refs/for/`) is considered later. - Live pages: the pull list and every pull tab (conversation, commits, files) update while open. Each has an event stream (`/{o}/{r}/pulls/events`, `/{o}/{r}/pulls/{n}/events`) that sends `changed` when a write changes what the page shows. A POST under the pulls paths, a push, a commit status for the head, and a mergeability or auto-merge run each wake it. The page re-reads in place and keeps typed text, focus and open inline forms; the Files tab keeps the file in view at the same offset. Streams are in-process, event driven, and never poll. Topics live in `live.rs`; the bump helpers are in `pages/pull_live.rs`. diff --git a/style/main.scss b/style/main.scss index c452dfe..64a8ddd 100644 --- a/style/main.scss +++ b/style/main.scss @@ -3102,6 +3102,65 @@ span.reaction { margin-top: 6px; } +// A suggested change: the commented line (removed) and the lines that replace it (added), in the +// same colours as the diff's del and add rows. +.review-suggestion { + margin-top: 8px; + border: 1px solid var(--border); + border-radius: var(--radius-lg); + background: var(--surface); + overflow: hidden; + font-size: 0.875rem; +} + +.review-suggestion-caption { + padding: 6px 10px; + border-bottom: 1px solid var(--border); + color: var(--muted); +} + +.review-suggestion-line { + display: flex; + gap: 8px; + padding: 2px 10px; + font-family: var(--mono); + font-size: 0.8125rem; + white-space: pre; + overflow-x: auto; + + code { + font-family: inherit; + white-space: pre; + } + + &.add { + background: var(--add-bg); + color: var(--add-text); + } + + &.del { + background: var(--del-bg); + color: var(--del-text); + } +} + +.review-suggestion-sign { + flex: 0 0 auto; + width: 1ch; +} + +.review-suggestion-apply { + padding: 8px 10px; + border-top: 1px solid var(--border); +} + +.review-suggestion-outdated { + margin: 0; + padding: 8px 10px; + border-top: 1px solid var(--border); + color: var(--muted); +} + .review-thread-actions { display: flex; gap: 12px;