improve pull request flow

This commit is contained in:
2026-09-02 09:53:50 +07:00
parent c054f61593
commit db3eaff4b9
6 changed files with 1210 additions and 279 deletions
@@ -1,12 +1,14 @@
use std::path::{Path, PathBuf};
use std::rc::Rc;
use assets::CustomIconName;
use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
SharedString, Size, WeakEntity, Window, div, px, size,
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, PathPromptOptions,
Pixels, Render, SharedString, Size, WeakEntity, Window, div, px, size,
};
use gpui_component::alert::Alert;
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::checkbox::Checkbox;
use gpui_component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
@@ -14,11 +16,13 @@ use gpui_component::form::{field, v_form};
use gpui_component::input::{Input, InputState, Textarea, TextareaState};
use gpui_component::scroll::Scrollbar;
use gpui_component::{
ActiveTheme, Icon, VirtualListScrollHandle, WindowExt, h_flex, v_flex, v_virtual_list,
ActiveTheme, Disableable, Icon, IconName, VirtualListScrollHandle, WindowExt, h_flex, v_flex,
v_virtual_list,
};
use nostr::prelude::{EventId, Kind};
use signed_core::{RepoStatus, activity_subject};
use signed_state::{ProfileStore, RepoStore};
use signed_git::{format_patch_between, merge_base, patch_applies};
use signed_state::{GitStore, ProfileStore, RepoStore};
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
use signed_ui::{SegmentButton, UserAvatar, placeholder, status_badge};
use utils::relative_time;
@@ -283,15 +287,55 @@ impl PullRequestsView {
}
}
/// State of the new pull request dialog, so the draft checkbox re-renders.
/// A patch series generated from a local repository, with the metadata
/// derived from it.
struct GeneratedPatch {
/// The `git format-patch` series (fills the patch textarea).
patch: String,
/// The merge base with the target branch, as hex.
merge_base: Option<String>,
}
/// State of the new pull request dialog, so the async generation, the
/// apply check and the draft checkbox re-render.
#[derive(Default)]
struct NewPullRequestDialogState {
draft: bool,
/// The last generated patch series; its merge base is reused at submit
/// only while the patch textarea is unchanged.
generated: Option<GeneratedPatch>,
/// Result of the pre-publish applicability check against the app's
/// mirror clone of the target repository.
apply_check: Option<Result<(), String>>,
/// A patch generation is in flight.
generating: bool,
/// Error of the last generation attempt.
error: Option<SharedString>,
}
impl NewPullRequestDialogState {
/// Text and whether it is good news, for the line under the patch field.
fn apply_check_message(&self) -> Option<(SharedString, bool)> {
match &self.apply_check {
Some(Ok(())) => Some((
"Applies cleanly to the repository's default branch".into(),
true,
)),
Some(Err(error)) => Some((
format!("May not apply cleanly to the repository's default branch: {error}").into(),
false,
)),
None => None,
}
}
}
/// Open the "new pull request" dialog: a title, an optional description,
/// an optional branch name and a patch input that submit through
/// [`RepoStore::open_pull_request`] when confirmed.
/// [`RepoStore::open_pull_request`] when confirmed. The patch can either be
/// pasted, or generated from a local checkout: pick a repository, a source
/// and a target branch, and the app runs `git format-patch` itself and
/// checks the series against the app's mirror clone of the target.
pub(super) fn open_new_pull_request_dialog(
store: Entity<RepoStore>,
window: &mut Window,
@@ -301,6 +345,9 @@ pub(super) fn open_new_pull_request_dialog(
let description =
cx.new(|cx| TextareaState::new(window, cx).placeholder("Describe the change..."));
let branch = cx.new(|cx| InputState::new(window, cx).placeholder("Branch name (optional)"));
let repo_path = cx.new(|cx| InputState::new(window, cx).placeholder("Pick a local checkout…"));
let source = cx.new(|cx| InputState::new(window, cx).placeholder("Source branch"));
let target = cx.new(|cx| InputState::new(window, cx).placeholder("Target branch"));
let patch = cx
.new(|cx| TextareaState::new(window, cx).placeholder("Paste `git format-patch` output..."));
let state = cx.new(|_| NewPullRequestDialogState::default());
@@ -309,21 +356,28 @@ pub(super) fn open_new_pull_request_dialog(
let subject = subject.clone();
let description = description.clone();
let branch = branch.clone();
let repo_path = repo_path.clone();
let source = source.clone();
let target = target.clone();
let patch = patch.clone();
let store = store.clone();
let state = state.clone();
dialog
.width(px(520.))
.width(px(560.))
.margin_top(px(50.))
.content(move |body, _window, cx| {
let generating = state.read(cx).generating;
let draft = state.read(cx).draft;
let error = state.read(cx).error.clone();
let apply_check = state.read(cx).apply_check_message();
body.child(
DialogHeader::new()
.child(DialogTitle::new().child("New pull request"))
.child(
DialogDescription::new()
.child("Propose a change with the output of `git format-patch`."),
DialogDescription::new().child(
"Propose a change with the output of `git format-patch`.",
),
),
)
.child(
@@ -339,6 +393,104 @@ pub(super) fn open_new_pull_request_dialog(
.label("Description")
.child(Textarea::new(&description).h(px(96.))),
)
.child(
field()
.label("Local repository")
.description(
"Generate the patch from a local checkout; leave empty to paste it",
)
.child(
h_flex()
.gap_1()
.items_center()
.child(
div()
.flex_1()
.child(Input::new(&repo_path).disabled(true)),
)
.child(
Button::new("choose-checkout")
.icon(IconName::FolderOpen)
.ghost()
.tooltip("Choose local checkout")
.on_click({
let repo_path = repo_path.clone();
let source = source.clone();
let target = target.clone();
let patch = patch.clone();
let branch = branch.clone();
let state = state.clone();
let store = store.clone();
move |_ev, window, cx| {
choose_local_repo(
&repo_path,
&source,
&target,
&patch,
&branch,
&state,
&store,
window,
cx,
);
}
}),
)
.child(
Button::new("generate-patch")
.ghost()
.label("Generate")
.tooltip(
"Generate the patch from the local checkout",
)
.loading(generating)
.disabled(generating)
.on_click({
let repo_path = repo_path.clone();
let source = source.clone();
let target = target.clone();
let patch = patch.clone();
let branch = branch.clone();
let state = state.clone();
let store = store.clone();
move |_ev, window, cx| {
let path =
repo_path.read(cx).value().to_string();
let source =
source.read(cx).value().to_string();
let target =
target.read(cx).value().to_string();
if !path.is_empty()
&& !source.is_empty()
&& !target.is_empty()
{
generate_patch(
&state,
&patch,
&branch,
path,
source,
target,
&store,
window,
cx,
);
}
}
}),
),
),
)
.child(
field()
.label("Source branch")
.child(Input::new(&source)),
)
.child(
field()
.label("Target branch")
.child(Input::new(&target)),
)
.child(
field()
.label("Branch")
@@ -346,9 +498,31 @@ pub(super) fn open_new_pull_request_dialog(
.child(Input::new(&branch)),
)
.child(
field()
.label("Patch")
.child(Textarea::new(&patch).h(px(160.))),
field().label("Patch").child(
v_flex()
.gap_1()
.child(Textarea::new(&patch).h(px(140.)))
.when_some(apply_check, |this, (message, ok)| {
this.child(
div()
.text_xs()
.text_color(if ok {
cx.theme().success
} else {
cx.theme().warning
})
.child(message),
)
})
.when_some(error, |this, message| {
this.child(
div()
.text_xs()
.text_color(cx.theme().danger)
.child(message),
)
}),
),
)
.child(
field().child(
@@ -370,15 +544,21 @@ pub(super) fn open_new_pull_request_dialog(
.primary()
.label("Create pull request")
.tooltip("Create pull request")
.loading(generating)
.disabled(generating)
.on_click({
let subject = subject.clone();
let description = description.clone();
let branch = branch.clone();
let patch = patch.clone();
let repo_path = repo_path.clone();
let store = store.clone();
let state = state.clone();
move |_event, window, cx| {
if state.read(cx).generating {
return;
}
let subject = subject.read(cx).value().to_string();
let description = description.read(cx).value().to_string();
let branch = branch.read(cx).value().to_string();
@@ -386,6 +566,21 @@ pub(super) fn open_new_pull_request_dialog(
let subject = (!subject.is_empty()).then_some(subject);
let branch = (!branch.is_empty()).then_some(branch);
let draft = state.read(cx).draft;
// The generated merge base stays valid
// only while the patch is unchanged; an
// edited patch falls back to none.
let merge_base = state
.read(cx)
.generated
.as_ref()
.filter(|generated| generated.patch == patch)
.and_then(|generated| generated.merge_base.clone());
// The checkout (when set) is where the
// tip commit is pushed from, so other
// clients can fetch it.
let repo_path = repo_path.read(cx).value().to_string();
let push_from = (!repo_path.is_empty())
.then(|| PathBuf::from(repo_path));
store.update(cx, |store, cx| {
store.open_pull_request(
@@ -394,6 +589,8 @@ pub(super) fn open_new_pull_request_dialog(
branch,
patch,
draft,
merge_base,
push_from,
cx,
);
});
@@ -407,6 +604,188 @@ pub(super) fn open_new_pull_request_dialog(
});
}
/// Prompt for a local checkout, fill the source/target defaults (the
/// checkout's current branch and the repository's announced HEAD) and
/// generate the patch series right away.
#[allow(clippy::too_many_arguments)]
fn choose_local_repo(
repo_path: &Entity<InputState>,
source: &Entity<InputState>,
target: &Entity<InputState>,
patch: &Entity<TextareaState>,
branch: &Entity<InputState>,
state: &Entity<NewPullRequestDialogState>,
store: &Entity<RepoStore>,
window: &mut Window,
cx: &mut App,
) {
let handle = window.window_handle();
let repo_path = repo_path.clone();
let source = source.clone();
let target = target.clone();
let patch = patch.clone();
let branch = branch.clone();
let state = state.clone();
let store = store.clone();
// The announced HEAD branch is the natural target default.
let target_default = store.read(cx).head.clone().unwrap_or_default();
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose local checkout".into()),
});
cx.spawn(async move |cx| {
if let Ok(Ok(Some(mut paths))) = prompt.await
&& let Some(path) = paths.pop()
{
let path = path.to_string_lossy().to_string();
// The checkout's current branch is the source default; resolve
// it off the UI thread.
let current = cx
.background_executor()
.spawn({
let path = path.clone();
async move {
gix::open(Path::new(&path))
.ok()
.and_then(|repo| signed_git::current_branch(&repo).ok().flatten())
}
})
.await;
let _ = handle.update(cx, |_, window, cx| {
repo_path.update(cx, |input, cx| {
input.set_value(path.clone(), window, cx);
});
source.update(cx, |input, cx| {
input.set_value(current.clone().unwrap_or_default(), window, cx);
});
target.update(cx, |input, cx| {
input.set_value(target_default.clone(), window, cx);
});
if let Some(current) = current
&& !current.is_empty()
&& !target_default.is_empty()
{
generate_patch(
&state,
&patch,
&branch,
path,
current,
target_default,
&store,
window,
cx,
);
}
});
}
})
.detach();
}
/// Generate the patch series `source..target` of the local checkout at
/// `repo_path`, fill the patch textarea and record the merge base and the
/// pre-publish applicability check in `state`.
#[allow(clippy::too_many_arguments)]
fn generate_patch(
state: &Entity<NewPullRequestDialogState>,
patch_input: &Entity<TextareaState>,
branch_input: &Entity<InputState>,
repo_path: String,
source: String,
target: String,
store: &Entity<RepoStore>,
window: &mut Window,
cx: &mut App,
) {
state.update(cx, |state, cx| {
state.generating = true;
state.error = None;
state.apply_check = None;
cx.notify();
});
let cache = GitStore::global(cx).cache().clone();
let (addr, clone_urls) = {
let store = store.read(cx);
(
store.addr().clone(),
store
.announcement
.as_ref()
.map(|a| {
a.clone
.iter()
.map(ToString::to_string)
.collect::<Vec<String>>()
})
.unwrap_or_default(),
)
};
let handle = window.window_handle();
let state = state.clone();
let patch_input = patch_input.clone();
let branch_input = branch_input.clone();
let task = cx.spawn(async move |cx| {
// The branch-name tag defaults to the source branch; keep a copy
// for the UI update after the background generation moves it.
let source_label = source.clone();
let generated = cx
.background_executor()
.spawn(async move {
let base =
merge_base(Path::new(&repo_path), &source, &target)?.ok_or_else(|| {
anyhow::anyhow!("{source} and {target} share no common ancestor")
})?;
let patch = format_patch_between(Path::new(&repo_path), &base, &source)?;
// Best-effort: does the series apply to the current default
// branch of the app's mirror clone of the target repository?
let check = cache
.ensure_clone(&addr, &clone_urls)
.ok()
.and_then(|repo| repo.workdir().map(|workdir| workdir.to_path_buf()))
.map(|workdir| patch_applies(&workdir, &patch).map_err(|e| e.to_string()));
Ok::<_, anyhow::Error>((patch, Some(base), check))
})
.await;
let _ = handle.update(cx, |_, window, cx| match generated {
Ok((patch, merge_base, check)) => {
patch_input.update(cx, |input, cx| {
input.set_value(patch.clone(), window, cx);
});
// The branch-name tag defaults to the source branch.
if branch_input.read(cx).value().is_empty() {
branch_input.update(cx, |input, cx| {
input.set_value(source_label.clone(), window, cx);
});
}
state.update(cx, |state, cx| {
state.generating = false;
state.generated = Some(GeneratedPatch { patch, merge_base });
state.apply_check = check;
cx.notify();
});
}
Err(error) => state.update(cx, |state, cx| {
state.generating = false;
state.error = Some(error.to_string().into());
cx.notify();
}),
});
});
task.detach();
}
impl BasePanel for PullRequestsView {
fn panel_name(&self) -> &'static str {
"pull-requests"
@@ -480,10 +859,33 @@ impl Render for PullRequestsView {
let scroll_handle = self.scroll_handle.clone();
let view = cx.entity().clone();
// Non-fatal warnings and errors of the last action (e.g. creating
// or updating a PR), shown as dismissible banners above the list.
let (last_error, last_warning) = {
let store = self.store.read(cx);
(store.last_error.clone(), store.last_warning.clone())
};
v_flex()
.size_full()
.image_cache(image_cache("pull-requests", MAX_IMAGES))
.child(self.render_header(cx))
.when_some(last_warning, |this, warning| {
this.child(Alert::warning("pr-warning", warning).banner().on_close({
let store = self.store.clone();
move |_event, _window, cx| {
store.update(cx, |store, _| store.last_warning = None);
}
}))
})
.when_some(last_error, |this, error| {
this.child(Alert::error("pr-error", error).banner().on_close({
let store = self.store.clone();
move |_event, _window, cx| {
store.update(cx, |store, _| store.last_error = None);
}
}))
})
.child(
v_flex()
.relative()