add per-commit publishing from sync status
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run
Rust / build (macos-latest, stable) (pull_request) Waiting to run
Rust / build (ubuntu-latest, stable) (pull_request) Waiting to run
Rust / build (windows-latest, stable) (pull_request) Waiting to run

This commit is contained in:
2026-11-19 05:14:52 +07:00
parent 41f34d0192
commit c7c1d0c741
13 changed files with 518 additions and 244 deletions
@@ -462,6 +462,7 @@ impl PullRequestDetailView {
commit_row(
ix,
&commit,
None,
move |window, cx| {
if let Some(worktree) = worktree.clone() {
crate::shared::log_dropped(view.update(cx, |this, cx| {
@@ -411,6 +411,7 @@ impl NewPullRequestView {
commit_row(
ix,
&commit,
None,
move |window, cx| {
crate::shared::log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx);
+3 -162
View File
@@ -2,11 +2,10 @@ use std::collections::HashSet;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, InteractiveElement as _, IntoElement,
ParentElement as _, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div,
px,
AnyElement, Context, InteractiveElement as _, IntoElement, ParentElement as _, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use signed_state::{Backend, CheckoutStatus, CheckoutSyncStatus, CheckoutsStore, Nip34Kind};
use signed_state::{Backend, Nip34Kind};
use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::clipboard::ClipboardButton;
@@ -21,38 +20,6 @@ use utils::relative_time_secs;
use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name};
use super::{RepoDetailView, actions, dialogs};
use crate::pull_requests::NewPullRequestView;
/// Push and sync bookkeeping for the repository header.
#[derive(Default)]
pub(super) struct Banners {
ready_requested: bool,
ready_head: Option<String>,
ready_statuses: Vec<CheckoutStatus>,
push_statuses: Vec<CheckoutStatus>,
}
impl Banners {
pub(super) fn ready_requested_at(&self) -> (bool, &Option<String>) {
(self.ready_requested, &self.ready_head)
}
pub(super) fn mark_ready_requested(&mut self, head: Option<String>) {
self.ready_requested = true;
self.ready_head = head;
}
pub(super) fn set_statuses(
&mut self,
ready: Vec<CheckoutStatus>,
push: Vec<CheckoutStatus>,
) -> bool {
let changed = ready != self.ready_statuses || push != self.push_statuses;
self.ready_statuses = ready;
self.push_statuses = push;
changed
}
}
impl RepoDetailView {
pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -75,35 +42,6 @@ impl RepoDetailView {
dialogs::init::open(local_path, cx.entity().downgrade(), window, cx);
}
pub(super) fn open_new_pull_request(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return;
};
let id = SharedString::from(format!("new-pr:{addr}"));
let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
let store = self.store.clone();
crate::shared::panels::open_detail(
&workspace,
id.clone(),
move |window, cx| {
cx.new(|cx| {
NewPullRequestView::new(
workspace_for_build.clone(),
id.clone(),
store.clone(),
window,
cx,
)
})
},
window,
cx,
);
}
pub(super) fn render_about(&mut self, cx: &mut Context<Self>) -> AnyElement {
if self.store.read(cx).addr().is_none() {
return self.render_init_banner(cx);
@@ -178,9 +116,6 @@ impl RepoDetailView {
.flex_none()
.gap_2()
.justify_end()
.when_some(self.render_sync_button(cx), |this, button| {
this.child(button)
})
.child(
Popover::new("code-popover")
.open(self.clone_open)
@@ -390,100 +325,6 @@ impl RepoDetailView {
.into_any_element()
}
/// A checkout with commits the repository owner has not pushed yet.
pub(super) fn push_suggestion(&self, cx: &App) -> Option<CheckoutStatus> {
let store = self.store.read(cx);
let addr = store.addr()?;
let user = Backend::global(cx).read(cx).current_user()?;
if !store.is_author(&user) {
return None;
}
CheckoutsStore::global(cx)
.read(cx)
.push_statuses_of(addr)
.into_iter()
.next()
}
/// A checkout whose branches are ahead of their nostr state.
pub(super) fn sync_suggestion(&self, cx: &App) -> Option<CheckoutSyncStatus> {
let store = self.store.read(cx);
let addr = store.addr()?;
let user = Backend::global(cx).read(cx).current_user()?;
if !store.is_author(&user) {
return None;
}
self.sync_directory
.read(cx)
.statuses_of(addr, cx)
.into_iter()
.find(|checkout| checkout.status.ahead_total > 0)
}
/// Pushes the sync/push suggestion.
fn render_sync_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let pushing = self.store.read(cx).pushing;
let (icon, label, tooltip, path) = if let Some(status) = self.push_suggestion(cx) {
let commits = if status.ahead == 1 {
"1 commit".to_owned()
} else {
format!("{} commits", status.ahead)
};
let path = status.path.clone();
(
Icon::named(IconRole::ArrowUp),
SharedString::from(format!("{commits} ready to push")),
format!("Push {}", status.branch),
path,
)
} else {
let checkout = self.sync_suggestion(cx)?;
let (branch, ahead) = checkout
.status
.refs
.iter()
.filter_map(|(name, sync)| match sync {
signed_git::RefSync::LocalAhead { ahead } => Some((name, *ahead)),
signed_git::RefSync::Diverged { ahead, .. } => Some((name, *ahead)),
_ => None,
})
.max_by_key(|(_, ahead)| *ahead)?;
let commits = if ahead == 1 {
"1 commit".to_owned()
} else {
format!("{ahead} commits")
};
let path = checkout.path.clone();
(
Icon::named(IconRole::Refresh),
SharedString::from(format!("{commits} ahead of Nostr")),
format!("Sync {branch}"),
path,
)
};
Some(
Button::new("sync-button")
.icon(icon)
.label(label)
.tooltip(Tooltip::text(tooltip))
.variant(ButtonVariant::Secondary)
.loading(pushing)
.disabled(pushing)
.on_click(cx.listener(move |this, _, window, cx| {
this.push_unpushed_checkout(path.clone(), window, cx);
}))
.into_any_element(),
)
}
pub(super) fn render_metadata(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.px_6()
+2
View File
@@ -353,6 +353,7 @@ fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement {
pub(crate) fn commit_row(
ix: usize,
commit: &FileCommit,
action: Option<AnyElement>,
on_click: impl Fn(&mut Window, &mut gpui::App) + 'static,
cx: &gpui::App,
) -> gpui::AnyElement {
@@ -401,6 +402,7 @@ pub(crate) fn commit_row(
.child(relative_time_secs(commit.time)),
),
)
.when_some(action, |row, action| row.child(action))
.on_click(move |_, window, cx| on_click(window, cx))
.into_any_element()
}
+74 -4
View File
@@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
@@ -7,12 +7,16 @@ use gpui::{
Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div, uniform_list,
};
use signed_git::{CommitList, Repo};
use signed_state::RepoStore;
use ui::common::v_flex;
use signed_state::{Backend, RepoStore, SyncStatusDirectory};
use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable as _, v_flex};
use ui::icons::{Icon, IconRole};
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
use super::RepoDetailView;
use super::commit_diff::CommitDiffView;
use super::helpers::commit_row;
use crate::shared::panels;
@@ -21,6 +25,8 @@ use crate::workspace::Workspace;
pub struct RepoHistoryView {
store: Entity<RepoStore>,
workspace: WeakEntity<Workspace>,
detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>,
worktree: Option<PathBuf>,
all_commits: Option<CommitList>,
loading_all_commits: bool,
@@ -29,10 +35,17 @@ pub struct RepoHistoryView {
}
impl RepoHistoryView {
pub fn new(store: Entity<RepoStore>, workspace: WeakEntity<Workspace>) -> Self {
pub fn new(
store: Entity<RepoStore>,
workspace: WeakEntity<Workspace>,
detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>,
) -> Self {
Self {
store,
workspace,
detail,
sync_directory,
worktree: None,
all_commits: None,
loading_all_commits: false,
@@ -45,6 +58,10 @@ impl RepoHistoryView {
self.worktree = path;
}
pub fn worktree(&self) -> Option<&Path> {
self.worktree.as_deref()
}
/// Number of commits reachable from HEAD, for the Commits tab label.
pub fn commit_count(&self) -> Option<usize> {
self.all_commits.as_ref().map(|list| list.total)
@@ -142,6 +159,26 @@ impl Render for RepoHistoryView {
let shown = commits.len();
let total = list.total;
let view = cx.entity().downgrade();
let detail = self.detail.clone();
let user = Backend::global(cx).read(cx).current_user();
let author = user.is_some_and(|user| self.store.read(cx).is_author(&user));
let checkout = self.worktree.clone();
let ahead = self
.store
.read(cx)
.addr()
.cloned()
.filter(|_| author)
.map(|addr| {
self.sync_directory.read_with(cx, |directory, cx| {
directory.ahead_commits_of(&addr, checkout.as_deref(), cx)
})
})
.unwrap_or_default();
let pushing = self.store.read(cx).pushing;
v_flex()
.relative()
@@ -156,9 +193,42 @@ impl Render for RepoHistoryView {
let id = commit.id.clone();
let view = view.clone();
let action = ahead
.iter()
.find(|(id, _)| id.starts_with(commit.id.as_str()))
.map(|(ahead, path)| {
let detail = detail.clone();
let path = path.clone();
let target = ahead.clone();
let short = commit.id.clone();
Button::new(("sync-commit", ix))
.label("Sync")
.icon(Icon::named(IconRole::ArrowUp))
.variant(ButtonVariant::Secondary)
.small()
.disabled(pushing)
.tooltip(Tooltip::text(format!("Sync up to {short}")))
.on_click(move |_, window, cx| {
cx.stop_propagation();
if let Some(detail) = detail.upgrade() {
detail.update(cx, |this, cx| {
this.sync_checkout_commit(
path.clone(),
target.clone(),
window,
cx,
);
});
}
})
.into_any_element()
});
commit_row(
ix,
&commit,
action,
move |window, cx| {
if let Err(error) = view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx);
+56 -54
View File
@@ -1,5 +1,5 @@
use std::collections::HashSet;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
@@ -13,7 +13,7 @@ use nostr::prelude::{PublicKey, Url};
use signed_core::{Announcement, RepoAddr};
use signed_git::{FileCommit, GitCache, Repo};
use signed_state::{
Backend, CheckoutsStore, LocalReposStore, Mirrors, Nip34Binding, RepoStore, SyncStatusDirectory,
Backend, LocalReposStore, Mirrors, Nip34Binding, RepoStore, SyncStatusDirectory,
};
use ui::alert::{Alert, AlertSeverity};
use ui::avatar::Avatar;
@@ -35,7 +35,6 @@ pub mod history;
pub mod refs;
use files::RepoFilesView;
use header::Banners;
use helpers::{RepoData, load_repo_data};
use history::RepoHistoryView;
use refs::RefSwitcher;
@@ -82,11 +81,10 @@ pub struct RepoDetailView {
error: Option<SharedString>,
head_commit: Option<FileCommit>,
refs: RefSwitcher,
banners: Banners,
tasks: Vec<Task<Result<(), Error>>>,
/// Profiles rendered by the header and maintainers.
pub(super) directory: Entity<ProfileDirectory>,
/// Sync status feeding the sync-to-Nostr banner.
/// Sync status feeding the per-commit sync buttons.
sync_directory: Entity<SyncStatusDirectory>,
pub(super) repo_menu_open: bool,
pub(super) clone_open: bool,
@@ -135,19 +133,24 @@ impl RepoDetailView {
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let checkouts = CheckoutsStore::global(cx);
let weak = cx.entity().downgrade();
let sync_directory = SyncStatusDirectory::new(cx);
let files = cx.new(RepoFilesView::new);
let history = cx.new(|_| RepoHistoryView::new(store.clone(), workspace.clone()));
let history = cx.new(|_| {
RepoHistoryView::new(
store.clone(),
workspace.clone(),
weak.clone(),
sync_directory.clone(),
)
});
let issues = cx.new(|cx| IssuesView::new(workspace.clone(), store.clone(), cx));
let pulls = cx.new(|cx| PullRequestsView::new(workspace.clone(), store.clone(), cx));
let weak = cx.entity().downgrade();
let refs = RefSwitcher::new(weak.clone(), window, cx);
let subscriptions = vec![
cx.observe(&checkouts, |this, _checkouts, cx| {
if this.refresh_statuses(cx) {
cx.notify();
}
cx.observe(&sync_directory, |this, _directory, cx| {
this.sync_history_source(cx);
}),
cx.subscribe(&files, |this, _files, _event, cx| {
if this.active_section != RepoSection::Files {
@@ -179,10 +182,9 @@ impl RepoDetailView {
error: None,
head_commit: None,
refs,
banners: Banners::default(),
tasks: Vec::new(),
directory: ProfileDirectory::new(cx),
sync_directory: SyncStatusDirectory::new(cx),
sync_directory,
repo_menu_open: false,
clone_open: false,
_subscriptions: subscriptions,
@@ -203,7 +205,6 @@ impl RepoDetailView {
self.store
.update(cx, |store, cx| store.announce(announcement, cx));
self.refresh_ready_statuses(cx);
cx.notify();
}
@@ -215,7 +216,6 @@ impl RepoDetailView {
) {
self._subscriptions
.push(cx.observe_in(store, window, |this, store, window, cx| {
this.refresh_ready_statuses(cx);
this.track_profiles(cx);
this.track_sync_status(cx);
if !this.repo_started && store.read(cx).announcement.is_some() {
@@ -223,7 +223,6 @@ impl RepoDetailView {
}
cx.notify();
}));
self.refresh_ready_statuses(cx);
}
fn track_profiles(&mut self, cx: &mut Context<Self>) {
@@ -264,45 +263,47 @@ impl RepoDetailView {
});
}
fn refresh_ready_statuses(&mut self, cx: &mut Context<Self>) {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return;
};
/// Commits list a local checkout with unpushed commits, so they can be synced one by one.
fn history_source(&self, displayed: &Path, cx: &App) -> PathBuf {
let store = self.store.read(cx);
let head = self.store.read(cx).head.clone();
let (requested, requested_head) = self.banners.ready_requested_at();
if requested && requested_head == &head {
return;
if store.path.is_some() {
return displayed.to_path_buf();
}
self.banners.mark_ready_requested(head.clone());
let backend = Backend::global(cx);
let checkout = CheckoutsStore::global(cx);
let owned = backend
let Some(addr) = store.addr() else {
return displayed.to_path_buf();
};
let owned = Backend::global(cx)
.read(cx)
.current_user()
.is_some_and(|user| self.store.read(cx).is_author(&user));
.is_some_and(|user| store.is_author(&user));
checkout.update(cx, |store, cx| {
store.request_statuses(&addr, head, cx);
if owned {
store.request_push_statuses(&addr, cx);
}
});
if !owned {
return displayed.to_path_buf();
}
fn refresh_statuses(&mut self, cx: &mut Context<Self>) -> bool {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return false;
self.sync_directory
.read_with(cx, |directory, cx| directory.statuses_of(addr, cx))
.into_iter()
.find(|checkout| checkout.status.head.is_some() && checkout.status.ahead_total > 0)
.map(|checkout| checkout.path)
.unwrap_or_else(|| displayed.to_path_buf())
}
fn sync_history_source(&mut self, cx: &mut Context<Self>) {
let Some(displayed) = self.worktree.clone() else {
return;
};
let checkouts = CheckoutsStore::global(cx).read(cx);
let ready_statuses = checkouts.ready_statuses_of(&addr);
let push_statuses = checkouts.push_statuses_of(&addr);
self.banners.set_statuses(ready_statuses, push_statuses)
let source = self.history_source(&displayed, cx);
self.history.update(cx, |history, cx| {
if history.worktree() == Some(source.as_path()) {
return;
}
history.set_worktree(Some(source));
history.reload(cx);
});
}
fn announcement<'a>(&'a self, cx: &'a App) -> Option<&'a Announcement> {
@@ -493,8 +494,10 @@ impl RepoDetailView {
files.set_readme(readme_path, readme, cx);
});
let history_source = self.history_source(&worktree, cx);
self.history.update(cx, |history, cx| {
history.set_worktree(Some(worktree.clone()));
history.set_worktree(Some(history_source));
history.reload(cx);
});
@@ -731,9 +734,10 @@ impl RepoDetailView {
self.tasks.push(task);
}
fn push_unpushed_checkout(
fn sync_checkout_commit(
&mut self,
path: PathBuf,
commit: String,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -748,14 +752,12 @@ impl RepoDetailView {
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
let push = this.update_in(cx, |_this, _window, cx| {
store.update(cx, |store, cx| store.push_checkout(path.clone(), cx))
store.update(cx, |store, cx| {
store.push_checkout_commit(path.clone(), commit.clone(), cx)
})
})?;
if let Ok(()) = push.await {
this.update_in(cx, |this, window, cx| {
this.load_repo(window, cx);
})?;
}
push.await?;
Ok(())
});
+65
View File
@@ -829,13 +829,78 @@ impl Repo {
refs.push((name.to_owned(), sync));
}
let ahead_commits = self.head_ahead_commits(remote_refs);
Ok(RepoSyncStatus {
refs,
ahead_total,
behind_total,
head: local_refs.head.clone(),
ahead_commits,
})
}
/// Commit ids reachable from HEAD but not from any remote ref, newest first.
fn head_ahead_commits(&self, remote_refs: &[(String, String)]) -> Vec<String> {
let Ok(head) = self.inner.head_id() else {
return Vec::new();
};
let mut hidden = Vec::with_capacity(remote_refs.len());
for (_, commit) in remote_refs {
let Some(id) = self.inner.rev_parse_single(commit.as_bytes()).ok() else {
return Vec::new();
};
let Ok(object) = id.object() else {
return Vec::new();
};
let Ok(commit) = object.peel_to_commit() else {
return Vec::new();
};
hidden.push(commit.id().detach());
}
let Ok(walk) = self.inner.rev_walk([head]).with_hidden(hidden).all() else {
return Vec::new();
};
let ahead: Vec<String> = walk
.filter_map(Result::ok)
.take(MAX_LISTED_COMMITS)
.map(|info| info.id().to_string())
.collect();
let Some(branch) = self.current_branch() else {
return Vec::new();
};
let name = format!("refs/heads/{branch}");
let Some((_, published)) = remote_refs.iter().find(|(refname, _)| refname == &name) else {
// A branch missing on Nostr creates nothing, so every commit is safe.
return ahead;
};
// None of the ahead commits can extend a tip HEAD no longer descends from.
let fast_forward = self
.merge_base(&head.to_string(), published)
.ok()
.flatten()
.is_some_and(|base| base == *published);
if !fast_forward {
return Vec::new();
}
ahead
.into_iter()
.filter(|commit| {
self.merge_base(published, commit)
.is_ok_and(|base| base.as_deref() == Some(published.as_str()))
})
.collect()
}
/// Classifies a branch present on both sides.
fn branch_sync(&self, local_commit: &str, remote_commit: &str) -> RefSync {
if local_commit == remote_commit {
+4
View File
@@ -18,6 +18,10 @@ pub struct RepoSyncStatus {
pub refs: Vec<(String, RefSync)>,
pub ahead_total: usize,
pub behind_total: usize,
/// Current branch short name of the checkout, `None` when detached.
pub head: Option<String>,
/// Ids of commits reachable from HEAD that publish the current branch as a fast-forward.
pub ahead_commits: Vec<String>,
}
impl RepoSyncStatus {
+140
View File
@@ -429,6 +429,146 @@ fn merge_base_finds_the_fork_point_and_reports_unrelated_history() {
assert!(repo.merge_base("orphan", "no-such-ref").is_err());
}
#[test]
fn sync_status_lists_commits_missing_from_nostr() {
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root");
std::fs::write(dir.path().join("b.txt"), b"two").expect("write");
commit_all(&repo, "second");
let second = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("second");
std::fs::write(dir.path().join("c.txt"), b"three").expect("write");
commit_all(&repo, "third");
let third = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("third");
let branch = repo.current_branch().expect("branch");
let ahead = repo
.sync_status(&[(format!("refs/heads/{branch}"), root.clone())])
.expect("status");
assert_eq!(ahead.head.as_deref(), Some(branch.as_str()));
assert_eq!(ahead.ahead_total, 2);
assert_eq!(ahead.ahead_commits.len(), 2);
assert!(ahead.ahead_commits.contains(&second));
assert!(ahead.ahead_commits.contains(&third));
assert!(!ahead.ahead_commits.contains(&root));
let in_sync = repo
.sync_status(&[(format!("refs/heads/{branch}"), third)])
.expect("status");
assert!(in_sync.ahead_commits.is_empty());
let missing = repo
.sync_status(&[(format!("refs/heads/{branch}"), "0".repeat(40))])
.expect("status");
assert!(missing.ahead_commits.is_empty());
}
#[test]
fn publishing_a_commit_advances_the_remote_tip() {
let server = tempfile::tempdir().expect("tempdir");
let server_repo = bare_server(server.path(), "npub1test", "my-repo");
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root");
std::fs::write(dir.path().join("b.txt"), b"two").expect("write");
commit_all(&repo, "second");
let second = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("second");
std::fs::write(dir.path().join("c.txt"), b"three").expect("write");
commit_all(&repo, "third");
let third = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("third");
let branch = repo.current_branch().expect("branch");
let refname = format!("refs/heads/{branch}");
let base_url = format!("file://{}", server.path().display());
let root_refspec = format!("+{root}:{refname}");
repo.push_refspecs(&base_url, "npub1test", "my-repo", &[root_refspec.as_str()])
.expect("publish root");
assert_eq!(
git_in(&server_repo, &["rev-parse", refname.as_str()]).expect("server tip"),
root
);
let status = repo
.sync_status(&[(refname.clone(), root.clone())])
.expect("status");
assert_eq!(status.ahead_commits.len(), 2);
assert!(status.ahead_commits.contains(&second));
assert!(status.ahead_commits.contains(&third));
let second_refspec = format!("+{second}:{refname}");
repo.push_refspecs(&base_url, "npub1test", "my-repo", &[second_refspec.as_str()])
.expect("publish second");
assert_eq!(
git_in(&server_repo, &["rev-parse", refname.as_str()]).expect("server tip"),
second
);
let status = repo
.sync_status(&[(refname, second.clone())])
.expect("status");
assert_eq!(status.ahead_commits, vec![third]);
}
#[test]
fn sync_status_skips_a_merged_commit_that_would_rewind_the_branch() {
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root");
let branch = repo.current_branch().expect("branch");
let refname = format!("refs/heads/{branch}");
git_run(dir.path(), &["checkout", "-q", "-b", "side"]);
std::fs::write(dir.path().join("side.txt"), b"side").expect("write");
commit_all(&repo, "side work");
let side = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("side");
git_run(dir.path(), &["checkout", "-q", branch.as_str()]);
std::fs::write(dir.path().join("main.txt"), b"main").expect("write");
commit_all(&repo, "main work");
let mainline = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("mainline");
assert_ne!(root, mainline);
git_run(
dir.path(),
&["merge", "-q", "--no-ff", "-m", "merge side", "side"],
);
let merge = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("merge");
let status = repo.sync_status(&[(refname, mainline)]).expect("status");
assert!(status.ahead_commits.contains(&merge));
assert!(!status.ahead_commits.contains(&root));
// Publishing the side commit would drop the merge and everything after it.
assert!(!status.ahead_commits.contains(&side));
}
#[test]
fn sync_status_skips_a_diverged_history() {
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root");
let branch = repo.current_branch().expect("branch");
let refname = format!("refs/heads/{branch}");
std::fs::write(dir.path().join("published.txt"), b"published").expect("write");
commit_all(&repo, "published");
let published = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("published");
git_run(dir.path(), &["reset", "-q", "--hard", root.as_str()]);
std::fs::write(dir.path().join("local.txt"), b"local").expect("write");
commit_all(&repo, "local");
let local = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("local");
let status = repo.sync_status(&[(refname, published)]).expect("status");
assert!(status.ahead_commits.is_empty());
assert!(!status.ahead_commits.contains(&local));
}
#[test]
fn split_patch_series_splits_real_multi_commit_mboxes() {
let dir = tempfile::tempdir().expect("tempdir");
+102 -6
View File
@@ -727,7 +727,7 @@ impl Backend {
cx: &mut Context<Self>,
) -> Task<Result<PushOutcome, Error>> {
let path = Mirrors::path(&announcement.addr());
self.push_repo_from(announcement, path, None, GitPushPolicy::Reconcile, cx)
self.push_repo_from(announcement, path, None, GitPushPolicy::Reconcile, None, cx)
}
/// Republishes the mirror and deletes grasp refs the mirror does not have.
@@ -737,14 +737,22 @@ impl Backend {
cx: &mut Context<Self>,
) -> Task<Result<PushOutcome, Error>> {
let path = Mirrors::path(&announcement.addr());
self.push_repo_from(announcement, path, None, GitPushPolicy::ResetRemote, cx)
self.push_repo_from(
announcement,
path,
None,
GitPushPolicy::ResetRemote,
None,
cx,
)
}
pub fn push_checkout(
pub fn push_checkout_commit(
&mut self,
announcement: Announcement,
checkout: PathBuf,
announced_head: Option<String>,
commit: String,
cx: &mut Context<Self>,
) -> Task<Result<PushOutcome, Error>> {
self.push_repo_from(
@@ -752,6 +760,7 @@ impl Backend {
checkout,
announced_head,
GitPushPolicy::Reconcile,
Some(commit),
cx,
)
}
@@ -762,6 +771,7 @@ impl Backend {
path: PathBuf,
announced_head: Option<String>,
policy: GitPushPolicy,
tip: Option<String>,
cx: &mut Context<Self>,
) -> Task<Result<PushOutcome, Error>> {
let addr = announcement.addr();
@@ -791,6 +801,92 @@ impl Backend {
}
});
let mut state = match tip {
Some(commit) => {
let owner = announcement.owner.to_bech32().map_err(|error| {
anyhow!("could not encode the repository owner: {error}")
})?;
let urls: Vec<String> = announcement
.relays
.iter()
.filter_map(grasp_base_url)
.map(|base| format!("{base}/{owner}/{}.git", announcement.id))
.collect();
let ls_path = path.clone();
let target = commit.clone();
let (branch, published) = cx
.background_spawn(async move {
let repo = Repo::open(&ls_path)?;
let Some(branch) = repo.current_branch() else {
bail!("the checkout has a detached HEAD");
};
let Some(tip) = repo.head() else {
bail!("the checkout has no commits");
};
if repo.merge_base(&tip, &target)? != Some(target.clone()) {
bail!("commit {target} is not on {branch}");
}
for url in &urls {
if let Ok(refs) = repo.ls_remote(url) {
let name = format!("refs/heads/{branch}");
if let Some((_, published)) =
refs.iter().find(|(refname, _)| refname == &name)
{
let base = repo.merge_base(published, &target).map_err(
|error| {
anyhow!(
"could not compare {target} with the \
published {branch}: {error}"
)
},
)?;
if base.as_deref() != Some(published.as_str()) {
bail!(
"commit {target} would rewind {branch} on the \
grasp servers"
);
}
}
return Ok::<_, Error>((branch, refs));
}
}
bail!("could not read the published refs from any grasp server")
})
.await?;
let name = format!("refs/heads/{branch}");
let commit = Sha1Hash::from_str(&commit)
.map_err(|_| anyhow!("invalid commit: {commit}"))?;
let mut refs = published
.into_iter()
.map(|(name, commit)| GitRef::new(name, &commit))
.collect::<Result<Vec<_>, Error>>()?;
match refs.iter_mut().find(|git_ref| git_ref.name == name) {
Some(git_ref) => git_ref.commit = commit,
None => refs.push(GitRef {
name: name.clone(),
commit,
}),
}
SyncState {
refs,
head: Some(branch),
path: Some(path.clone()),
mode: GitPushMode::Ref(name),
policy: GitPushPolicy::Reconcile,
}
}
None => {
let mut state = {
let work = cx.background_spawn({
let path = path.clone();
@@ -799,10 +895,10 @@ impl Backend {
work.await?
};
state.policy = policy;
// Fetch grasp refs the local repository lacks before the state event is signed,
// so the servers' full ref map is declared.
state.reconcile(&announcement, cx).await?;
state
}
};
// Keep the announced default branch in `HEAD` when it is among the pushed refs.
if let Some(head) = announced_head
+4 -4
View File
@@ -1190,9 +1190,10 @@ impl RepoStore {
self.run_push(push, None, cx)
}
pub fn push_checkout(
pub fn push_checkout_commit(
&mut self,
path: PathBuf,
commit: String,
cx: &mut Context<Self>,
) -> Task<Result<(), Error>> {
if self.pushing {
@@ -1210,12 +1211,11 @@ impl RepoStore {
};
// The state event's `HEAD` stays the announced default branch.
// The checkout may be on a side branch.
let head = self.head.clone();
let backend = Backend::global(cx);
let push = backend.update(cx, |backend, cx| {
backend.push_checkout(announcement, path.clone(), head, cx)
backend.push_checkout_commit(announcement, path.clone(), head, commit, cx)
});
self.run_push(push, Some((addr, path)), cx)
+19 -5
View File
@@ -31,20 +31,21 @@ impl GitRef {
}
/// How much to push to the grasp servers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum GitPushMode {
/// Mirror all branches and tags.
#[default]
All,
/// Push `refs/heads/main` only (repo creation).
Main,
/// Push only the named ref from the declared state.
Ref(String),
}
/// How to handle server-only refs when pushing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GitPushPolicy {
/// Reconcile the local refs with the grasp servers,
/// fetching missing refs before pushing.
/// Reconcile the local refs with the grasp servers, fetching missing refs before pushing.
#[default]
Reconcile,
/// Declare the local refs only and delete server-only refs while pushing.
@@ -280,7 +281,7 @@ impl SyncState {
.await?;
if !missing.is_empty() {
let (mode, policy) = (self.mode, self.policy);
let (mode, policy) = (self.mode.clone(), self.policy);
*self = Self::from_repo(&snapshot_path)?;
self.mode = mode;
self.policy = policy;
@@ -319,7 +320,11 @@ impl SyncState {
.map_err(|error| anyhow!("could not encode the repository owner: {error}"))?;
let mut outcome = PushOutcome::default();
let policy = self.policy;
let mode = self.mode.clone();
let refs = self.refs.clone();
let declared: Vec<String> = self
.refs
.iter()
@@ -374,7 +379,8 @@ impl SyncState {
let base = base.clone();
let owner = owner.clone();
let repo_id = announcement.id.clone();
let mode = self.mode;
let mode = mode.clone();
let refs = refs.clone();
let declared = declared.clone();
async move {
@@ -382,6 +388,14 @@ impl SyncState {
match mode {
GitPushMode::Main => repo.push_main(&base, &owner, &repo_id),
GitPushMode::Ref(name) => {
let Some(git_ref) = refs.iter().find(|git_ref| git_ref.name == name)
else {
return Err(anyhow!("ref {name} is not declared for this push"));
};
let refspec = format!("+{}:{}", git_ref.commit, name);
repo.push_refspecs(&base, &owner, &repo_id, &[refspec.as_str()])
}
GitPushMode::All => {
let mut refspecs = force_refspecs();
if policy == GitPushPolicy::ResetRemote {
+39 -1
View File
@@ -1,6 +1,6 @@
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::Error;
@@ -319,6 +319,44 @@ impl SyncStatusDirectory {
.unwrap_or(0)
}
/// Commit ids missing on Nostr, mapped to the checkout that holds them.
///
/// When `checkout` matches a tracked checkout, only that checkout contributes.
pub fn ahead_commits_of(
&self,
addr: &RepoAddr,
checkout: Option<&Path>,
cx: &App,
) -> HashMap<String, PathBuf> {
self.queue(addr, cx);
let Some(statuses) = self.statuses.get(addr) else {
return HashMap::new();
};
let selected: Vec<&CheckoutSyncStatus> = match checkout
.and_then(|path| statuses.iter().find(|status| status.path.as_path() == path))
{
Some(status) => vec![status],
None => statuses.iter().collect(),
};
let mut commits = HashMap::new();
for status in selected {
if status.status.head.is_none() {
continue;
}
for id in &status.status.ahead_commits {
commits
.entry(id.clone())
.or_insert_with(|| status.path.clone());
}
}
commits
}
fn queue(&self, addr: &RepoAddr, cx: &App) {
if self.with_pending(|pending| pending.insert(addr.clone())) {
let store = SyncStatusStore::global(cx);