chore: restructure backend
This commit is contained in:
@@ -1,3 +1,4 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -10,7 +11,7 @@ use gpui::{
|
|||||||
UniformListScrollHandle, WeakEntity, Window, div, uniform_list,
|
UniformListScrollHandle, WeakEntity, Window, div, uniform_list,
|
||||||
};
|
};
|
||||||
use signed_git::{CommitList, FileCommit, Repo};
|
use signed_git::{CommitList, FileCommit, Repo};
|
||||||
use signed_state::{Backend, RepoStore, SyncStatusDirectory};
|
use signed_state::RepoStore;
|
||||||
use ui::alert::{Alert, AlertSeverity, AlertStyle};
|
use ui::alert::{Alert, AlertSeverity, AlertStyle};
|
||||||
use ui::avatar::Avatar;
|
use ui::avatar::Avatar;
|
||||||
use ui::button::{Button, ButtonVariant};
|
use ui::button::{Button, ButtonVariant};
|
||||||
@@ -47,13 +48,14 @@ pub struct RepoHistoryView {
|
|||||||
store: Entity<RepoStore>,
|
store: Entity<RepoStore>,
|
||||||
workspace: WeakEntity<AppRoot>,
|
workspace: WeakEntity<AppRoot>,
|
||||||
detail: WeakEntity<RepoDetailView>,
|
detail: WeakEntity<RepoDetailView>,
|
||||||
sync_directory: Entity<SyncStatusDirectory>,
|
|
||||||
worktree: Option<PathBuf>,
|
worktree: Option<PathBuf>,
|
||||||
all_commits: Option<Arc<CommitList>>,
|
all_commits: Option<Arc<CommitList>>,
|
||||||
loading_all_commits: bool,
|
loading_all_commits: bool,
|
||||||
/// The loaded commit list, shared with the render without a per-frame copy.
|
/// The loaded commit list, shared with the render without a per-frame copy.
|
||||||
commits: Arc<Vec<FileCommit>>,
|
commits: Arc<Vec<FileCommit>>,
|
||||||
rows: Arc<Vec<HistoryRow>>,
|
rows: Arc<Vec<HistoryRow>>,
|
||||||
|
/// Commit ids that exist in a local checkout but not on Nostr.
|
||||||
|
ahead: Arc<HashMap<String, PathBuf>>,
|
||||||
/// The last load failure, shown instead of the empty list.
|
/// The last load failure, shown instead of the empty list.
|
||||||
error: Option<SharedString>,
|
error: Option<SharedString>,
|
||||||
scroll_handle: UniformListScrollHandle,
|
scroll_handle: UniformListScrollHandle,
|
||||||
@@ -66,18 +68,17 @@ impl RepoHistoryView {
|
|||||||
store: Entity<RepoStore>,
|
store: Entity<RepoStore>,
|
||||||
workspace: WeakEntity<AppRoot>,
|
workspace: WeakEntity<AppRoot>,
|
||||||
detail: WeakEntity<RepoDetailView>,
|
detail: WeakEntity<RepoDetailView>,
|
||||||
sync_directory: Entity<SyncStatusDirectory>,
|
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
store,
|
store,
|
||||||
workspace,
|
workspace,
|
||||||
detail,
|
detail,
|
||||||
sync_directory,
|
|
||||||
worktree: None,
|
worktree: None,
|
||||||
all_commits: None,
|
all_commits: None,
|
||||||
loading_all_commits: false,
|
loading_all_commits: false,
|
||||||
commits: Arc::new(Vec::new()),
|
commits: Arc::new(Vec::new()),
|
||||||
rows: Arc::new(Vec::new()),
|
rows: Arc::new(Vec::new()),
|
||||||
|
ahead: Arc::new(HashMap::new()),
|
||||||
error: None,
|
error: None,
|
||||||
scroll_handle: UniformListScrollHandle::new(),
|
scroll_handle: UniformListScrollHandle::new(),
|
||||||
load_task: None,
|
load_task: None,
|
||||||
@@ -88,6 +89,14 @@ impl RepoHistoryView {
|
|||||||
self.worktree = path;
|
self.worktree = path;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn set_ahead(&mut self, ahead: HashMap<String, PathBuf>, cx: &mut Context<Self>) {
|
||||||
|
let next = Arc::new(ahead);
|
||||||
|
if *self.ahead != *next {
|
||||||
|
self.ahead = next;
|
||||||
|
cx.notify();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn worktree(&self) -> Option<&Path> {
|
pub fn worktree(&self) -> Option<&Path> {
|
||||||
self.worktree.as_deref()
|
self.worktree.as_deref()
|
||||||
}
|
}
|
||||||
@@ -224,6 +233,8 @@ impl RepoHistoryView {
|
|||||||
|
|
||||||
impl Render for RepoHistoryView {
|
impl Render for RepoHistoryView {
|
||||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
|
let scroll_handle = self.scroll_handle.clone();
|
||||||
|
|
||||||
let Some(list) = self.all_commits.as_ref() else {
|
let Some(list) = self.all_commits.as_ref() else {
|
||||||
return if self.loading_all_commits {
|
return if self.loading_all_commits {
|
||||||
Spinner::centered("commits-loading").into_any_element()
|
Spinner::centered("commits-loading").into_any_element()
|
||||||
@@ -272,27 +283,8 @@ impl Render for RepoHistoryView {
|
|||||||
}));
|
}));
|
||||||
let detail = self.detail.clone();
|
let detail = self.detail.clone();
|
||||||
|
|
||||||
let backend = Backend::global(cx);
|
|
||||||
let user = backend.read(cx).current_user();
|
|
||||||
|
|
||||||
let author = user.is_some_and(|user| self.store.read(cx).is_author(&user));
|
|
||||||
let checkout = self.worktree.clone();
|
|
||||||
|
|
||||||
let pushing = self.store.read(cx).pushing;
|
let pushing = self.store.read(cx).pushing;
|
||||||
let scroll_handle = self.scroll_handle.clone();
|
let ahead = Arc::clone(&self.ahead);
|
||||||
|
|
||||||
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();
|
|
||||||
|
|
||||||
v_flex()
|
v_flex()
|
||||||
.relative()
|
.relative()
|
||||||
@@ -318,8 +310,8 @@ impl Render for RepoHistoryView {
|
|||||||
let browse_commit = browse_commit.clone();
|
let browse_commit = browse_commit.clone();
|
||||||
|
|
||||||
let ahead = ahead
|
let ahead = ahead
|
||||||
.iter()
|
.get(commit.id.as_str())
|
||||||
.find(|(id, _)| id.starts_with(commit.id.as_str()));
|
.map(|path| (commit.id.to_string(), path.clone()));
|
||||||
|
|
||||||
h_flex()
|
h_flex()
|
||||||
.id(row_id.clone())
|
.id(row_id.clone())
|
||||||
|
|||||||
@@ -78,6 +78,8 @@ struct AboutModel {
|
|||||||
nip05: Option<SharedString>,
|
nip05: Option<SharedString>,
|
||||||
ngit_command: SharedString,
|
ngit_command: SharedString,
|
||||||
nak_command: SharedString,
|
nak_command: SharedString,
|
||||||
|
description: SharedString,
|
||||||
|
clone_commands: Arc<Vec<String>>,
|
||||||
avatar_seed: SharedString,
|
avatar_seed: SharedString,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,6 +111,8 @@ impl AboutModel {
|
|||||||
nip05: nip05.map(SharedString::from),
|
nip05: nip05.map(SharedString::from),
|
||||||
ngit_command,
|
ngit_command,
|
||||||
nak_command,
|
nak_command,
|
||||||
|
description: SharedString::from(announcement.description()),
|
||||||
|
clone_commands: Arc::new(announcement.clone_urls()),
|
||||||
avatar_seed,
|
avatar_seed,
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -206,14 +210,8 @@ impl RepoDetailView {
|
|||||||
let tabs = AppRoot::repo_tabs(&store, &workspace, cx);
|
let tabs = AppRoot::repo_tabs(&store, &workspace, cx);
|
||||||
let refs = RefSwitcher::new(weak.clone(), window, cx);
|
let refs = RefSwitcher::new(weak.clone(), window, cx);
|
||||||
|
|
||||||
let history = cx.new(|_| {
|
let history =
|
||||||
RepoHistoryView::new(
|
cx.new(|_| RepoHistoryView::new(store.clone(), workspace.clone(), weak.clone()));
|
||||||
store.clone(),
|
|
||||||
workspace.clone(),
|
|
||||||
weak.clone(),
|
|
||||||
sync_directory.clone(),
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
let mut subscriptions = vec![];
|
let mut subscriptions = vec![];
|
||||||
|
|
||||||
@@ -392,11 +390,11 @@ impl RepoDetailView {
|
|||||||
return displayed.to_path_buf();
|
return displayed.to_path_buf();
|
||||||
}
|
}
|
||||||
|
|
||||||
self.sync_directory
|
let statuses = self.sync_directory.read(cx).statuses_of(addr);
|
||||||
.read_with(cx, |directory, cx| directory.statuses_of(addr, cx))
|
statuses
|
||||||
.into_iter()
|
.iter()
|
||||||
.find(|checkout| checkout.status.head.is_some() && checkout.status.ahead_total > 0)
|
.find(|checkout| checkout.status.head.is_some() && checkout.status.ahead_total > 0)
|
||||||
.map(|checkout| checkout.path)
|
.map(|checkout| checkout.path.clone())
|
||||||
.unwrap_or_else(|| displayed.to_path_buf())
|
.unwrap_or_else(|| displayed.to_path_buf())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -414,6 +412,29 @@ impl RepoDetailView {
|
|||||||
} else {
|
} else {
|
||||||
self.reload_history_source(false, cx);
|
self.reload_history_source(false, cx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let backend = Backend::global(cx);
|
||||||
|
let checkout = self.history.read(cx).worktree().map(Path::to_path_buf);
|
||||||
|
|
||||||
|
let ahead = self
|
||||||
|
.store
|
||||||
|
.read(cx)
|
||||||
|
.addr()
|
||||||
|
.cloned()
|
||||||
|
.filter(|_| {
|
||||||
|
let user = backend.read(cx).current_user();
|
||||||
|
user.is_some_and(|user| self.store.read(cx).is_author(&user))
|
||||||
|
})
|
||||||
|
.map(|addr| {
|
||||||
|
self.sync_directory
|
||||||
|
.read(cx)
|
||||||
|
.ahead_commits_of(&addr, checkout.as_deref())
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
self.history.update(cx, |history, cx| {
|
||||||
|
history.set_ahead(ahead, cx);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Points the commit list at its source again, reloading a mirror whose HEAD moved.
|
/// Points the commit list at its source again, reloading a mirror whose HEAD moved.
|
||||||
@@ -1379,7 +1400,7 @@ impl RepoDetailView {
|
|||||||
let nak_command = header.nak_command.clone();
|
let nak_command = header.nak_command.clone();
|
||||||
|
|
||||||
let name = self.store.read(cx).display_name();
|
let name = self.store.read(cx).display_name();
|
||||||
let description = announcement.description();
|
let description = header.description.clone();
|
||||||
|
|
||||||
let announcement_for_menu = Arc::clone(&header.announcement);
|
let announcement_for_menu = Arc::clone(&header.announcement);
|
||||||
let weak_menu_open = cx.weak_entity();
|
let weak_menu_open = cx.weak_entity();
|
||||||
@@ -1388,7 +1409,7 @@ impl RepoDetailView {
|
|||||||
let weak_download = cx.weak_entity();
|
let weak_download = cx.weak_entity();
|
||||||
let ngit_for_popover = ngit_command.clone();
|
let ngit_for_popover = ngit_command.clone();
|
||||||
let nak_for_popover = nak_command.clone();
|
let nak_for_popover = nak_command.clone();
|
||||||
let git_for_popover = Arc::new(announcement.clone_urls());
|
let git_for_popover = Arc::clone(&header.clone_commands);
|
||||||
|
|
||||||
h_flex()
|
h_flex()
|
||||||
.p_6()
|
.p_6()
|
||||||
|
|||||||
@@ -107,27 +107,22 @@ impl Announcement {
|
|||||||
RepoAddr::new(self.owner, self.id.clone())
|
RepoAddr::new(self.owner, self.id.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the name, defaulting to "Untitled".
|
|
||||||
pub fn name(&self) -> String {
|
|
||||||
self.name.clone().unwrap_or("Untitled".into())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Matches a `u` tag pointing at the base or a shared earliest unique commit.
|
/// Matches a `u` tag pointing at the base or a shared earliest unique commit.
|
||||||
pub fn is_fork_of(&self, base: &RepoAddr, base_euc: Option<&str>) -> bool {
|
pub fn is_fork_of(&self, base: &RepoAddr, base_euc: Option<&str>) -> bool {
|
||||||
if self.addr() == *base {
|
if self.addr() == *base {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.upstream.as_ref().and_then(|u| u.addr.as_ref()) == Some(base) {
|
if self.upstream.as_ref().and_then(|u| u.addr.as_ref()) == Some(base) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
base_euc.is_some_and(|euc| self.euc.as_deref() == Some(euc))
|
base_euc.is_some_and(|euc| self.euc.as_deref() == Some(euc))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the description, defaulting to "No description".
|
/// Returns the description, defaulting to "No description".
|
||||||
pub fn description(&self) -> String {
|
pub fn description(&self) -> &str {
|
||||||
self.description
|
self.description.as_deref().unwrap_or("No description")
|
||||||
.clone()
|
|
||||||
.unwrap_or("No description".to_string())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds the owner to the maintainers unless a `u` tag marks this a subordinate fork.
|
/// Adds the owner to the maintainers unless a `u` tag marks this a subordinate fork.
|
||||||
@@ -149,344 +144,3 @@ impl Announcement {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
const MAINTAINER_HEX: &str = "68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272";
|
|
||||||
|
|
||||||
/// Returns the test signer keys.
|
|
||||||
fn keys() -> Keys {
|
|
||||||
Keys::new(
|
|
||||||
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
|
|
||||||
.expect("valid secret key"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a signed repo announcement event from raw tags.
|
|
||||||
fn announcement_event(tags: &[&[&str]]) -> Event {
|
|
||||||
let tags: Vec<Tag> = tags
|
|
||||||
.iter()
|
|
||||||
.map(|t| Tag::parse(t.to_vec()).expect("valid tag"))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
EventBuilder::new(Kind::GitRepoAnnouncement)
|
|
||||||
.tags(tags)
|
|
||||||
.finalize(&keys())
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parses an event carrying every supported tag.
|
|
||||||
#[test]
|
|
||||||
fn parses_full_announcement() {
|
|
||||||
let event = announcement_event(&[
|
|
||||||
&["d", "my-repo"],
|
|
||||||
&["name", "My Repo"],
|
|
||||||
&["description", "A test repository"],
|
|
||||||
&["web", "https://example.com/repo"],
|
|
||||||
&["clone", "https://example.com/repo.git"],
|
|
||||||
&["relays", "wss://relay.example.com"],
|
|
||||||
&["r", "aa231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
|
||||||
&["maintainers", MAINTAINER_HEX],
|
|
||||||
&["t", "rust"],
|
|
||||||
&["t", "nostr"],
|
|
||||||
]);
|
|
||||||
|
|
||||||
let announcement = Announcement::from_event(&event).expect("parses");
|
|
||||||
|
|
||||||
assert_eq!(announcement.owner, keys().public_key());
|
|
||||||
assert_eq!(announcement.id, "my-repo");
|
|
||||||
assert_eq!(announcement.name.as_deref(), Some("My Repo"));
|
|
||||||
assert_eq!(
|
|
||||||
announcement.description.as_deref(),
|
|
||||||
Some("A test repository")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
announcement.web,
|
|
||||||
vec![Url::parse("https://example.com/repo").unwrap()]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
announcement.clone,
|
|
||||||
vec![Url::parse("https://example.com/repo.git").unwrap()]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
announcement.relays,
|
|
||||||
vec![RelayUrl::parse("wss://relay.example.com").unwrap()]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
announcement.euc.as_deref(),
|
|
||||||
Some("aa231c4c6a5777dc89b42207b499891a344add5c")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
announcement.maintainers,
|
|
||||||
vec![PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")]
|
|
||||||
);
|
|
||||||
assert_eq!(announcement.hashtags, vec!["rust", "nostr"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Skips malformed clone, relay, and maintainer values.
|
|
||||||
#[test]
|
|
||||||
fn drops_malformed_values() {
|
|
||||||
let event = announcement_event(&[
|
|
||||||
&["d", "my-repo"],
|
|
||||||
&["clone", "not a url"],
|
|
||||||
&["relays", "wss://good.example.com"],
|
|
||||||
&["maintainers", "not-a-pubkey"],
|
|
||||||
]);
|
|
||||||
|
|
||||||
let announcement = Announcement::from_event(&event).expect("parses");
|
|
||||||
|
|
||||||
assert!(announcement.clone.is_empty());
|
|
||||||
assert_eq!(
|
|
||||||
announcement.relays,
|
|
||||||
vec![RelayUrl::parse("wss://good.example.com").unwrap()]
|
|
||||||
);
|
|
||||||
assert!(announcement.maintainers.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parses the `u` tag into an upstream coordinate.
|
|
||||||
#[test]
|
|
||||||
fn parses_upstream_tag() {
|
|
||||||
let event = announcement_event(&[
|
|
||||||
&["d", "my-fork"],
|
|
||||||
&[
|
|
||||||
"u",
|
|
||||||
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream|https://example.com/upstream.git",
|
|
||||||
"wss://relay.example.com",
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
|
|
||||||
let announcement = Announcement::from_event(&event).expect("parses");
|
|
||||||
let upstream = announcement.upstream.expect("parses the u tag");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
upstream.addr,
|
|
||||||
Some(RepoAddr::new(
|
|
||||||
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
|
|
||||||
"upstream"
|
|
||||||
))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
upstream.raw,
|
|
||||||
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream|https://example.com/upstream.git"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
upstream.display().to_string(),
|
|
||||||
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Matches a fork through its `u` tag coordinate.
|
|
||||||
#[test]
|
|
||||||
fn is_fork_of_matches_the_u_tag_coordinate() {
|
|
||||||
let base = RepoAddr::new(
|
|
||||||
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
|
|
||||||
"upstream",
|
|
||||||
);
|
|
||||||
let event = announcement_event(&[&["d", "my-fork"], &["u", &base.to_string()]]);
|
|
||||||
let fork = Announcement::from_event(&event).expect("parses");
|
|
||||||
|
|
||||||
assert!(fork.is_fork_of(&base, None));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Matches forks sharing the base's earliest unique commit.
|
|
||||||
#[test]
|
|
||||||
fn is_fork_of_matches_a_shared_euc() {
|
|
||||||
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
|
||||||
let base_event = announcement_event(&[&["d", "upstream"], &["r", euc, "euc"]]);
|
|
||||||
let base = Announcement::from_event(&base_event).expect("parses");
|
|
||||||
let base_addr = base.addr();
|
|
||||||
|
|
||||||
let fork_event = announcement_event(&[&["d", "mirror"], &["r", euc, "euc"]]);
|
|
||||||
let fork = Announcement::from_event(&fork_event).expect("parses");
|
|
||||||
assert!(fork.is_fork_of(&base_addr, base.euc.as_deref()));
|
|
||||||
|
|
||||||
let other_event = announcement_event(&[
|
|
||||||
&["d", "other"],
|
|
||||||
&["r", "bb231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
|
||||||
]);
|
|
||||||
let other = Announcement::from_event(&other_event).expect("parses");
|
|
||||||
assert!(!other.is_fork_of(&base_addr, base.euc.as_deref()));
|
|
||||||
|
|
||||||
assert!(!fork.is_fork_of(&base_addr, None));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Matches permanent forks whose `u` tag points at the base despite a diverged EUC.
|
|
||||||
#[test]
|
|
||||||
fn is_fork_of_matches_permanent_forks_with_a_diverged_euc() {
|
|
||||||
let base = RepoAddr::new(
|
|
||||||
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
|
|
||||||
"upstream",
|
|
||||||
);
|
|
||||||
let base_euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
|
||||||
let event = announcement_event(&[
|
|
||||||
&["d", "my-fork"],
|
|
||||||
&["u", &base.to_string()],
|
|
||||||
&["r", "cc231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
|
||||||
]);
|
|
||||||
let fork = Announcement::from_event(&event).expect("parses");
|
|
||||||
|
|
||||||
assert!(fork.is_fork_of(&base, Some(base_euc)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Includes the owner among maintainers for primary repositories.
|
|
||||||
#[test]
|
|
||||||
fn effective_maintainers_include_owner_for_primary_repos() {
|
|
||||||
let event = announcement_event(&[&["d", "my-repo"], &["maintainers", MAINTAINER_HEX]]);
|
|
||||||
|
|
||||||
let announcement = Announcement::from_event(&event).expect("parses");
|
|
||||||
let maintainers = announcement.effective_maintainers();
|
|
||||||
|
|
||||||
assert_eq!(maintainers.len(), 2);
|
|
||||||
assert!(maintainers.contains(&announcement.owner));
|
|
||||||
assert!(maintainers.contains(&PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Excludes the owner from maintainers for subordinate forks.
|
|
||||||
#[test]
|
|
||||||
fn effective_maintainers_exclude_owner_for_subordinate_forks() {
|
|
||||||
let event = announcement_event(&[
|
|
||||||
&["d", "my-fork"],
|
|
||||||
&["u", "30617:abc:upstream|https://example.com/upstream.git"],
|
|
||||||
&["maintainers", MAINTAINER_HEX],
|
|
||||||
]);
|
|
||||||
|
|
||||||
let announcement = Announcement::from_event(&event).expect("parses");
|
|
||||||
let maintainers = announcement.effective_maintainers();
|
|
||||||
|
|
||||||
assert!(!maintainers.contains(&announcement.owner));
|
|
||||||
assert_eq!(
|
|
||||||
maintainers,
|
|
||||||
vec![PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const OWNER_KEYS: [&str; 3] = [
|
|
||||||
"0000000000000000000000000000000000000000000000000000000000000001",
|
|
||||||
"0000000000000000000000000000000000000000000000000000000000000002",
|
|
||||||
"0000000000000000000000000000000000000000000000000000000000000003",
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Builds an announcement event signed by the given owner key.
|
|
||||||
fn owned_announcement_event(owner: &str, tags: &[&[&str]]) -> Event {
|
|
||||||
let keys = Keys::new(SecretKey::from_hex(owner).expect("valid secret key"));
|
|
||||||
let tags: Vec<Tag> = tags
|
|
||||||
.iter()
|
|
||||||
.map(|t| Tag::parse(t.to_vec()).expect("valid tag"))
|
|
||||||
.collect();
|
|
||||||
EventBuilder::new(Kind::GitRepoAnnouncement)
|
|
||||||
.tags(tags)
|
|
||||||
.finalize(&keys)
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds one announcement owned by the owner key at the given index.
|
|
||||||
fn owned_announcements(owner_ix: usize, tags: &[&[&str]]) -> Vec<Announcement> {
|
|
||||||
vec![
|
|
||||||
Announcement::from_event(&owned_announcement_event(OWNER_KEYS[owner_ix], tags))
|
|
||||||
.expect("parses"),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Places the user's own forks before everyone else's.
|
|
||||||
#[test]
|
|
||||||
fn fork_candidates_orders_own_forks_first() {
|
|
||||||
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
|
||||||
let clone = "https://grasp.example/npub1x/my-fork.git";
|
|
||||||
|
|
||||||
let base_addr = RepoAddr::new(
|
|
||||||
PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey"),
|
|
||||||
"upstream",
|
|
||||||
);
|
|
||||||
let all = vec![
|
|
||||||
owned_announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "other-project"],
|
|
||||||
&["r", "bb231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
owned_announcements(
|
|
||||||
1,
|
|
||||||
&[&["d", "my-fork"], &["r", euc, "euc"], &["clone", clone]],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
owned_announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "their-fork"],
|
|
||||||
&["u", &base_addr.to_string()],
|
|
||||||
&["clone", clone],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
];
|
|
||||||
|
|
||||||
let user = PublicKey::from_hex(OWNER_KEYS[1]).expect("pubkey");
|
|
||||||
let forks = Announcement::forks_in(&all, &base_addr, Some(euc), Some(user));
|
|
||||||
|
|
||||||
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
|
|
||||||
assert_eq!(ids, vec!["my-fork", "their-fork"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Excludes the base itself, unrelated repos, and repos without clone URLs.
|
|
||||||
#[test]
|
|
||||||
fn fork_candidates_excludes_base_unrelated_and_unfetchable() {
|
|
||||||
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
|
||||||
let base_owner = PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey");
|
|
||||||
let base_addr = RepoAddr::new(base_owner, "upstream");
|
|
||||||
|
|
||||||
let mut all = vec![
|
|
||||||
owned_announcements(0, &[&["d", "upstream"], &["r", euc, "euc"]])
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
owned_announcements(1, &[&["d", "no-clone-fork"], &["r", euc, "euc"]])
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
owned_announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "other"],
|
|
||||||
&["r", "cc231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
owned_announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "mirror"],
|
|
||||||
&["r", euc, "euc"],
|
|
||||||
&["clone", "https://grasp.example/x/mirror.git"],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
];
|
|
||||||
|
|
||||||
let forks = Announcement::forks_in(&all, &base_addr, Some(euc), Some(base_owner));
|
|
||||||
assert_eq!(forks.len(), 1);
|
|
||||||
assert_eq!(forks[0].id, "mirror");
|
|
||||||
|
|
||||||
all.push(
|
|
||||||
owned_announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "u-fork"],
|
|
||||||
&["u", &base_addr.to_string()],
|
|
||||||
&["clone", "https://grasp.example/x/u-fork.git"],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
);
|
|
||||||
let forks = Announcement::forks_in(&all, &base_addr, None, Some(base_owner));
|
|
||||||
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
|
|
||||||
assert_eq!(ids, vec!["u-fork"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -32,28 +32,37 @@ const GIT_ROOT_KINDS: [Kind; 4] = [
|
|||||||
Kind::GitRepoAnnouncement,
|
Kind::GitRepoAnnouncement,
|
||||||
];
|
];
|
||||||
|
|
||||||
pub fn is_repo_kind(kind: Kind) -> bool {
|
|
||||||
kind == Kind::GitRepoAnnouncement
|
|
||||||
|| kind == Kind::RepoState
|
|
||||||
|| kind == Kind::EventDeletion
|
|
||||||
|| kind == Kind::RequestToVanish
|
|
||||||
|| ACTIVITY_KINDS.contains(&kind)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tag_kind(event: &Event, name: &str) -> Option<Kind> {
|
|
||||||
event
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.find(|tag| tag.kind() == name)
|
|
||||||
.and_then(|tag| tag.content())
|
|
||||||
.and_then(|value| value.parse::<Kind>().ok())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Filters;
|
pub struct Filters;
|
||||||
|
|
||||||
impl Filters {
|
impl Filters {
|
||||||
const DELETIONS_LOOKBACK: Duration = Duration::from_secs(3 * 365 * 86_400);
|
const DELETIONS_LOOKBACK: Duration = Duration::from_secs(3 * 365 * 86_400);
|
||||||
|
|
||||||
|
pub fn is_repo_kind(kind: Kind) -> bool {
|
||||||
|
kind == Kind::GitRepoAnnouncement
|
||||||
|
|| kind == Kind::RepoState
|
||||||
|
|| kind == Kind::EventDeletion
|
||||||
|
|| kind == Kind::RequestToVanish
|
||||||
|
|| ACTIVITY_KINDS.contains(&kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tag_kind(event: &Event, name: &str) -> Option<Kind> {
|
||||||
|
event
|
||||||
|
.tags
|
||||||
|
.iter()
|
||||||
|
.find(|tag| tag.kind() == name)
|
||||||
|
.and_then(|tag| tag.content())
|
||||||
|
.and_then(|value| value.parse::<Kind>().ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn is_git_comment(event: &Event) -> bool {
|
||||||
|
event.kind == Kind::Comment
|
||||||
|
&& Self::tag_kind(event, "K").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn is_git_status(event: &Event) -> bool {
|
||||||
|
Self::tag_kind(event, "k").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn statuses_for(roots: impl IntoIterator<Item = EventId>) -> Filter {
|
pub fn statuses_for(roots: impl IntoIterator<Item = EventId>) -> Filter {
|
||||||
Filter::new()
|
Filter::new()
|
||||||
.kinds([
|
.kinds([
|
||||||
@@ -160,69 +169,3 @@ impl Filters {
|
|||||||
.since(Self::deletions_since())
|
.since(Self::deletions_since())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn is_git_comment(event: &Event) -> bool {
|
|
||||||
event.kind == Kind::Comment
|
|
||||||
&& tag_kind(event, "K").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn is_git_status(event: &Event) -> bool {
|
|
||||||
tag_kind(event, "k").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::GitEvent;
|
|
||||||
|
|
||||||
fn keys(seed: u8) -> Keys {
|
|
||||||
let mut hex = "00000000000000000000000000000000000000000000000000000000000000".to_string();
|
|
||||||
hex.push_str(&format!("{seed:02x}"));
|
|
||||||
Keys::new(SecretKey::from_hex(&hex).expect("valid secret key"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn signed(author: &Keys, kind: Kind, tags: Vec<Tag>) -> Event {
|
|
||||||
EventBuilder::new(kind)
|
|
||||||
.tags(tags)
|
|
||||||
.finalize(author)
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn kind_tag(name: &str, kind: Kind) -> Tag {
|
|
||||||
Tag::parse([name, &kind.as_u16().to_string()]).expect("valid kind tag")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn comment_activity_depends_on_the_uppercase_k_tag() {
|
|
||||||
let on_git = signed(&keys(1), Kind::Comment, vec![kind_tag("K", Kind::GitIssue)]);
|
|
||||||
let on_repo = signed(
|
|
||||||
&keys(1),
|
|
||||||
Kind::Comment,
|
|
||||||
vec![kind_tag("K", Kind::GitRepoAnnouncement)],
|
|
||||||
);
|
|
||||||
let on_note = signed(&keys(1), Kind::Comment, vec![kind_tag("K", Kind::TextNote)]);
|
|
||||||
|
|
||||||
assert!(on_git.is_git_activity());
|
|
||||||
assert!(on_repo.is_git_activity());
|
|
||||||
assert!(!on_note.is_git_activity());
|
|
||||||
assert!(!signed(&keys(1), Kind::Comment, Vec::new()).is_git_activity());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn status_activity_depends_on_the_lowercase_k_tag() {
|
|
||||||
let status = signed(
|
|
||||||
&keys(1),
|
|
||||||
Kind::GitStatusClosed,
|
|
||||||
vec![kind_tag("k", Kind::GitPullRequest)],
|
|
||||||
);
|
|
||||||
let unrelated = signed(
|
|
||||||
&keys(1),
|
|
||||||
Kind::GitStatusClosed,
|
|
||||||
vec![kind_tag("k", Kind::Metadata)],
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(status.is_git_activity());
|
|
||||||
assert!(!unrelated.is_git_activity());
|
|
||||||
assert!(!signed(&keys(1), Kind::GitStatusClosed, Vec::new()).is_git_activity());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -89,11 +89,11 @@ impl GitEvent for Event {
|
|||||||
fn is_git_activity(&self) -> bool {
|
fn is_git_activity(&self) -> bool {
|
||||||
match self.kind {
|
match self.kind {
|
||||||
Kind::GitIssue | Kind::GitPatch | Kind::GitPullRequest => true,
|
Kind::GitIssue | Kind::GitPatch | Kind::GitPullRequest => true,
|
||||||
Kind::Comment => crate::filters::is_git_comment(self),
|
Kind::Comment => crate::Filters::is_git_comment(self),
|
||||||
Kind::GitStatusOpen
|
Kind::GitStatusOpen
|
||||||
| Kind::GitStatusApplied
|
| Kind::GitStatusApplied
|
||||||
| Kind::GitStatusClosed
|
| Kind::GitStatusClosed
|
||||||
| Kind::GitStatusDraft => crate::filters::is_git_status(self),
|
| Kind::GitStatusDraft => crate::Filters::is_git_status(self),
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,97 +76,3 @@ where
|
|||||||
|
|
||||||
items
|
items
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// Derives deterministic signer keys from a seed byte.
|
|
||||||
fn keys(seed: u8) -> Keys {
|
|
||||||
let mut hex = "00000000000000000000000000000000000000000000000000000000000000".to_string();
|
|
||||||
hex.push_str(&format!("{seed:02x}"));
|
|
||||||
Keys::new(SecretKey::from_hex(&hex).expect("valid secret key"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a signed event with a fixed timestamp.
|
|
||||||
fn signed(author: &Keys, kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
|
|
||||||
EventBuilder::new(kind)
|
|
||||||
.tags(tags)
|
|
||||||
.custom_created_at(Timestamp::from_secs(created_at))
|
|
||||||
.finalize(author)
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds an uppercase `E` tag for the event.
|
|
||||||
fn uppercase_e_tag(event: &Event) -> Tag {
|
|
||||||
Tag::parse(["E", &event.id.to_hex()]).expect("valid E tag")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds an event lookup closure over a slice.
|
|
||||||
fn lookup(events: &[Event]) -> impl Fn(EventId) -> Option<Event> + '_ {
|
|
||||||
move |id| events.iter().find(|event| event.id == id).cloned()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a git issue event with a subject tag.
|
|
||||||
fn titled_issue(author: &Keys, title: &str, at: u64) -> Event {
|
|
||||||
signed(
|
|
||||||
author,
|
|
||||||
Kind::GitIssue,
|
|
||||||
vec![Tag::parse(["subject", title]).expect("valid subject tag")],
|
|
||||||
at,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Merges the user's own events into the matching thread.
|
|
||||||
#[test]
|
|
||||||
fn group_merges_own_events_into_the_matching_thread() {
|
|
||||||
let me = keys(1);
|
|
||||||
let issue = titled_issue(&me, "Add retry logic", 100);
|
|
||||||
let mine = signed(
|
|
||||||
&me,
|
|
||||||
Kind::Comment,
|
|
||||||
vec![
|
|
||||||
uppercase_e_tag(&issue),
|
|
||||||
Tag::parse(["K", "1621"]).expect("K tag"),
|
|
||||||
],
|
|
||||||
150,
|
|
||||||
);
|
|
||||||
let reply = signed(
|
|
||||||
&keys(2),
|
|
||||||
Kind::Comment,
|
|
||||||
vec![
|
|
||||||
uppercase_e_tag(&issue),
|
|
||||||
Tag::parse(["K", "1621"]).expect("K tag"),
|
|
||||||
],
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
|
|
||||||
let context = [issue.clone(), mine.clone(), reply.clone()];
|
|
||||||
let items = group(
|
|
||||||
[reply.clone()],
|
|
||||||
[issue.clone(), mine.clone()],
|
|
||||||
me.public_key(),
|
|
||||||
&InboxReadState::default(),
|
|
||||||
&lookup(&context),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(items.len(), 1);
|
|
||||||
assert_eq!(items[0].root, issue.id);
|
|
||||||
assert_eq!(
|
|
||||||
items[0].root_event.as_ref().map(|event| event.id),
|
|
||||||
Some(issue.id)
|
|
||||||
);
|
|
||||||
assert_eq!(items[0].kind(), Some(Kind::GitIssue));
|
|
||||||
assert_eq!(items[0].title(), "Add retry logic");
|
|
||||||
assert_eq!(items[0].events, vec![reply.clone()]);
|
|
||||||
assert_eq!(items[0].own_events, vec![mine.clone(), issue.clone()]);
|
|
||||||
assert_eq!(
|
|
||||||
items[0]
|
|
||||||
.timeline(5)
|
|
||||||
.iter()
|
|
||||||
.map(|event| event.id)
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
vec![issue.id, mine.id, reply.id]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -138,112 +138,3 @@ where
|
|||||||
.and_then(|content| EventId::from_hex(content).ok())
|
.and_then(|content| EventId::from_hex(content).ok())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// Derives deterministic signer keys from a seed byte.
|
|
||||||
fn keys(seed: u8) -> Keys {
|
|
||||||
let mut hex = "00000000000000000000000000000000000000000000000000000000000000".to_string();
|
|
||||||
hex.push_str(&format!("{seed:02x}"));
|
|
||||||
Keys::new(SecretKey::from_hex(&hex).expect("valid secret key"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a signed event with a fixed timestamp.
|
|
||||||
fn signed(author: &Keys, kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
|
|
||||||
EventBuilder::new(kind)
|
|
||||||
.tags(tags)
|
|
||||||
.custom_created_at(Timestamp::from_secs(created_at))
|
|
||||||
.finalize(author)
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a plain lowercase `e` tag for the event.
|
|
||||||
fn e_tag(event: &Event) -> Tag {
|
|
||||||
Tag::parse(["e", &event.id.to_hex()]).expect("valid e tag")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a four-value `e` tag with the given marker.
|
|
||||||
fn marked_e_tag(event: &Event, marker: &str) -> Tag {
|
|
||||||
Tag::parse(["e", &event.id.to_hex(), "wss://relay.example.com", marker])
|
|
||||||
.expect("valid e tag")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds an uppercase `E` tag for the event.
|
|
||||||
fn uppercase_e_tag(event: &Event) -> Tag {
|
|
||||||
Tag::parse(["E", &event.id.to_hex()]).expect("valid E tag")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds an event lookup closure over a slice.
|
|
||||||
fn lookup(events: &[Event]) -> impl Fn(EventId) -> Option<Event> + '_ {
|
|
||||||
move |id| events.iter().find(|event| event.id == id).cloned()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a git issue event.
|
|
||||||
fn issue(author: &Keys, at: u64) -> Event {
|
|
||||||
signed(author, Kind::GitIssue, Vec::new(), at)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolves a comment to its uppercase `E` root.
|
|
||||||
#[test]
|
|
||||||
fn comment_resolves_to_its_uppercase_root() {
|
|
||||||
let issue = issue(&keys(1), 100);
|
|
||||||
let comment = signed(
|
|
||||||
&keys(2),
|
|
||||||
Kind::Comment,
|
|
||||||
vec![
|
|
||||||
uppercase_e_tag(&issue),
|
|
||||||
Tag::parse(["K", "1621"]).expect("valid K tag"),
|
|
||||||
],
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
let events = [issue.clone(), comment.clone()];
|
|
||||||
assert_eq!(
|
|
||||||
ThreadResolver::new(&lookup(&events)).notification_root(&comment),
|
|
||||||
Some(issue.id)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolves a child patch to its root patch.
|
|
||||||
#[test]
|
|
||||||
fn child_patch_resolves_to_the_root_patch() {
|
|
||||||
let root_patch = signed(&keys(1), Kind::GitPatch, Vec::new(), 100);
|
|
||||||
let child_patch = signed(&keys(1), Kind::GitPatch, vec![e_tag(&root_patch)], 200);
|
|
||||||
let events = [root_patch.clone(), child_patch.clone()];
|
|
||||||
assert_eq!(
|
|
||||||
ThreadResolver::new(&lookup(&events)).notification_root(&child_patch),
|
|
||||||
Some(root_patch.id)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolves a status through its `root` marker tag.
|
|
||||||
#[test]
|
|
||||||
fn status_resolves_via_the_root_marker() {
|
|
||||||
let issue = issue(&keys(1), 100);
|
|
||||||
let status = signed(
|
|
||||||
&keys(2),
|
|
||||||
Kind::GitStatusClosed,
|
|
||||||
vec![marked_e_tag(&issue, "root")],
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
let events = [issue.clone(), status.clone()];
|
|
||||||
assert_eq!(
|
|
||||||
ThreadResolver::new(&lookup(&events)).notification_root(&status),
|
|
||||||
Some(issue.id)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Follows a nested comment chain to the issue root.
|
|
||||||
#[test]
|
|
||||||
fn nested_comment_chain_follows_to_the_root() {
|
|
||||||
let issue = issue(&keys(1), 100);
|
|
||||||
let reply = signed(&keys(2), Kind::Comment, vec![uppercase_e_tag(&issue)], 200);
|
|
||||||
let nested = signed(&keys(3), Kind::Comment, vec![uppercase_e_tag(&reply)], 300);
|
|
||||||
let events = [issue.clone(), reply, nested.clone()];
|
|
||||||
assert_eq!(
|
|
||||||
ThreadResolver::new(&lookup(&events)).notification_root(&nested),
|
|
||||||
Some(issue.id)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -115,166 +115,3 @@ impl<'a> PullRequest<'a> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// Returns the test signer keys.
|
|
||||||
fn keys() -> Keys {
|
|
||||||
Keys::new(
|
|
||||||
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
|
|
||||||
.expect("valid secret key"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a signed pull request event.
|
|
||||||
fn pr_event(content: &str, tags: Vec<Tag>) -> Event {
|
|
||||||
EventBuilder::new(Kind::GitPullRequest)
|
|
||||||
.content(content)
|
|
||||||
.tags(tags)
|
|
||||||
.finalize(&keys())
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a signed patch event with a fixed timestamp.
|
|
||||||
fn patch_event(content: &str, tags: Vec<Tag>, created_at: u64) -> Event {
|
|
||||||
EventBuilder::new(Kind::GitPatch)
|
|
||||||
.content(content)
|
|
||||||
.tags(tags)
|
|
||||||
.custom_created_at(Timestamp::from(created_at))
|
|
||||||
.finalize(&keys())
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Joins the full patch series into one diff.
|
|
||||||
#[test]
|
|
||||||
fn pull_request_patch_joins_the_whole_patch_set() {
|
|
||||||
let root = patch_event("patch-one", vec![], 100);
|
|
||||||
let second = patch_event("patch-two", vec![Tag::event(root.id)], 200);
|
|
||||||
let pr = pr_event("description", vec![Tag::event(root.id)]);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
PullRequest::new(&pr).patch([&root, &second]),
|
|
||||||
"patch-one\npatch-two"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
PullRequest::new(&pr).patches([&root, &second]),
|
|
||||||
vec![&root, &second]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Orders patches by walking the reply chain.
|
|
||||||
#[test]
|
|
||||||
fn pull_request_patches_walks_the_reply_chain_in_order() {
|
|
||||||
let root = patch_event("patch-one", vec![], 100);
|
|
||||||
let second = patch_event("patch-two", vec![Tag::event(root.id)], 200);
|
|
||||||
let third = patch_event("patch-three", vec![Tag::event(second.id)], 300);
|
|
||||||
let pr = pr_event("description", vec![Tag::event(root.id)]);
|
|
||||||
|
|
||||||
let series = PullRequest::new(&pr).patches([&third, &root, &second]);
|
|
||||||
assert_eq!(
|
|
||||||
series
|
|
||||||
.iter()
|
|
||||||
.map(|p| p.content.as_str())
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
vec!["patch-one", "patch-two", "patch-three"]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Finds the patch series through the declared tip commit.
|
|
||||||
#[test]
|
|
||||||
fn pull_request_patches_finds_the_set_via_the_tip_commit() {
|
|
||||||
let root = patch_event("patch-one", vec![], 100);
|
|
||||||
let tip = "1111111111111111111111111111111111111111";
|
|
||||||
let last = patch_event(
|
|
||||||
"patch-two",
|
|
||||||
vec![
|
|
||||||
Tag::event(root.id),
|
|
||||||
Tag::parse(["r", tip]).expect("valid tag"),
|
|
||||||
],
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
let pr = pr_event(
|
|
||||||
"description",
|
|
||||||
vec![Tag::parse(["c", tip]).expect("valid tag")],
|
|
||||||
);
|
|
||||||
|
|
||||||
let series = PullRequest::new(&pr).patches([&root, &last]);
|
|
||||||
assert_eq!(
|
|
||||||
series
|
|
||||||
.iter()
|
|
||||||
.map(|p| p.content.as_str())
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
vec!["patch-one", "patch-two"]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const COMMIT_HEX: &str = "1111111111111111111111111111111111111111";
|
|
||||||
const OTHER_ROOT_HEX: &str = "2222222222222222222222222222222222222222";
|
|
||||||
|
|
||||||
/// Builds a signed event with a fixed timestamp.
|
|
||||||
fn signed_at(kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
|
|
||||||
EventBuilder::new(kind)
|
|
||||||
.tags(tags)
|
|
||||||
.custom_created_at(Timestamp::from(created_at))
|
|
||||||
.finalize(&keys())
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds the pull request root used by the update tests.
|
|
||||||
fn pr_root() -> Event {
|
|
||||||
signed_at(
|
|
||||||
Kind::GitPullRequest,
|
|
||||||
vec![
|
|
||||||
Tag::parse(["c", COMMIT_HEX]).expect("valid tag"),
|
|
||||||
Tag::parse(["branch-name", "feature/x"]).expect("valid tag"),
|
|
||||||
],
|
|
||||||
100,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Picks the newest update targeting the root.
|
|
||||||
#[test]
|
|
||||||
fn latest_update_picks_newest_revision_of_the_root() {
|
|
||||||
let root = pr_root();
|
|
||||||
let root_hex = root.id.to_hex();
|
|
||||||
|
|
||||||
let revision = |created_at: u64| {
|
|
||||||
signed_at(
|
|
||||||
Kind::GitPullRequestUpdate,
|
|
||||||
vec![Tag::parse(["E", &root_hex]).expect("valid tag")],
|
|
||||||
created_at,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
let unrelated = signed_at(
|
|
||||||
Kind::GitPullRequestUpdate,
|
|
||||||
vec![Tag::parse(["E", OTHER_ROOT_HEX]).expect("valid tag")],
|
|
||||||
999,
|
|
||||||
);
|
|
||||||
|
|
||||||
let events = [unrelated, revision(200), root.clone(), revision(300)];
|
|
||||||
let latest = PullRequest::latest_update(events.iter(), &root).expect("an update");
|
|
||||||
|
|
||||||
assert_eq!(latest.created_at.as_secs(), 300);
|
|
||||||
assert_eq!(latest.kind, Kind::GitPullRequestUpdate);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ignores updates from authors other than the root owner.
|
|
||||||
#[test]
|
|
||||||
fn latest_update_ignores_other_authors() {
|
|
||||||
let root = pr_root();
|
|
||||||
let root_hex = root.id.to_hex();
|
|
||||||
let other = Keys::new(
|
|
||||||
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000002")
|
|
||||||
.expect("valid secret key"),
|
|
||||||
);
|
|
||||||
let stranger = EventBuilder::new(Kind::GitPullRequestUpdate)
|
|
||||||
.tags([Tag::parse(["E", &root_hex]).expect("valid tag")])
|
|
||||||
.custom_created_at(Timestamp::from(999))
|
|
||||||
.finalize(&other)
|
|
||||||
.expect("signed event");
|
|
||||||
|
|
||||||
assert!(PullRequest::latest_update([&stranger, &root].into_iter(), &root).is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -45,90 +45,3 @@ impl RepoStatus {
|
|||||||
.unwrap_or(RepoStatus::Open)
|
.unwrap_or(RepoStatus::Open)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::GitEvent;
|
|
||||||
|
|
||||||
const ROOT_ID_HEX: &str = "1111111111111111111111111111111111111111111111111111111111111111";
|
|
||||||
const OTHER_ID_HEX: &str = "2222222222222222222222222222222222222222222222222222222222222222";
|
|
||||||
|
|
||||||
fn keys_from_hex(hex: &str) -> Keys {
|
|
||||||
Keys::new(SecretKey::from_hex(hex).expect("valid secret key"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn root_event_id() -> EventId {
|
|
||||||
EventId::from_hex(ROOT_ID_HEX).expect("valid event id")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn status_event(author: &Keys, kind: Kind, root: EventId, created_at: u64) -> Event {
|
|
||||||
EventBuilder::new(kind)
|
|
||||||
.tags([Tag::event(root)])
|
|
||||||
.custom_created_at(Timestamp::from(created_at))
|
|
||||||
.finalize(author)
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn references_root_matches_e_tag() {
|
|
||||||
let root = root_event_id();
|
|
||||||
let event = EventBuilder::new(Kind::GitStatusOpen)
|
|
||||||
.tags([Tag::event(root)])
|
|
||||||
.finalize(&keys_from_hex(
|
|
||||||
"0000000000000000000000000000000000000000000000000000000000000001",
|
|
||||||
))
|
|
||||||
.expect("signed event");
|
|
||||||
|
|
||||||
assert!(event.references_root(&root));
|
|
||||||
assert!(!event.references_root(&EventId::from_hex(OTHER_ID_HEX).expect("valid id")));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn latest_status_wins() {
|
|
||||||
let owner =
|
|
||||||
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
|
|
||||||
let maintainer =
|
|
||||||
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
|
|
||||||
let root = root_event_id();
|
|
||||||
|
|
||||||
let statuses = [
|
|
||||||
status_event(&maintainer, Kind::GitStatusClosed, root, 100),
|
|
||||||
status_event(&owner, Kind::GitStatusOpen, root, 200),
|
|
||||||
];
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
RepoStatus::resolve(
|
|
||||||
statuses.iter(),
|
|
||||||
&owner.public_key(),
|
|
||||||
&[maintainer.public_key()]
|
|
||||||
),
|
|
||||||
RepoStatus::Open
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ignores_statuses_from_others() {
|
|
||||||
let owner =
|
|
||||||
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
|
|
||||||
let maintainer =
|
|
||||||
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
|
|
||||||
let stranger =
|
|
||||||
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000003");
|
|
||||||
let root = root_event_id();
|
|
||||||
|
|
||||||
let statuses = [
|
|
||||||
status_event(&stranger, Kind::GitStatusClosed, root, 300),
|
|
||||||
status_event(&maintainer, Kind::GitStatusDraft, root, 100),
|
|
||||||
];
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
RepoStatus::resolve(
|
|
||||||
statuses.iter(),
|
|
||||||
&owner.public_key(),
|
|
||||||
&[maintainer.public_key()]
|
|
||||||
),
|
|
||||||
RepoStatus::Draft
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,324 @@
|
|||||||
|
use nostr::prelude::*;
|
||||||
|
use signed_core::{Announcement, RepoAddr};
|
||||||
|
|
||||||
|
const MAINTAINER_HEX: &str = "68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272";
|
||||||
|
|
||||||
|
fn keys() -> Keys {
|
||||||
|
Keys::new(
|
||||||
|
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
|
||||||
|
.expect("valid secret key"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn announcement_event(tags: &[&[&str]]) -> Event {
|
||||||
|
let tags: Vec<Tag> = tags
|
||||||
|
.iter()
|
||||||
|
.map(|t| Tag::parse(t.to_vec()).expect("valid tag"))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
EventBuilder::new(Kind::GitRepoAnnouncement)
|
||||||
|
.tags(tags)
|
||||||
|
.finalize(&keys())
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_full_announcement() {
|
||||||
|
let event = announcement_event(&[
|
||||||
|
&["d", "my-repo"],
|
||||||
|
&["name", "My Repo"],
|
||||||
|
&["description", "A test repository"],
|
||||||
|
&["web", "https://example.com/repo"],
|
||||||
|
&["clone", "https://example.com/repo.git"],
|
||||||
|
&["relays", "wss://relay.example.com"],
|
||||||
|
&["r", "aa231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
||||||
|
&["maintainers", MAINTAINER_HEX],
|
||||||
|
&["t", "rust"],
|
||||||
|
&["t", "nostr"],
|
||||||
|
]);
|
||||||
|
|
||||||
|
let announcement = Announcement::from_event(&event).expect("parses");
|
||||||
|
|
||||||
|
assert_eq!(announcement.owner, keys().public_key());
|
||||||
|
assert_eq!(announcement.id, "my-repo");
|
||||||
|
assert_eq!(announcement.name.as_deref(), Some("My Repo"));
|
||||||
|
assert_eq!(
|
||||||
|
announcement.description.as_deref(),
|
||||||
|
Some("A test repository")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
announcement.web,
|
||||||
|
vec![Url::parse("https://example.com/repo").unwrap()]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
announcement.clone,
|
||||||
|
vec![Url::parse("https://example.com/repo.git").unwrap()]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
announcement.relays,
|
||||||
|
vec![RelayUrl::parse("wss://relay.example.com").unwrap()]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
announcement.euc.as_deref(),
|
||||||
|
Some("aa231c4c6a5777dc89b42207b499891a344add5c")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
announcement.maintainers,
|
||||||
|
vec![PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")]
|
||||||
|
);
|
||||||
|
assert_eq!(announcement.hashtags, vec!["rust", "nostr"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn drops_malformed_values() {
|
||||||
|
let event = announcement_event(&[
|
||||||
|
&["d", "my-repo"],
|
||||||
|
&["clone", "not a url"],
|
||||||
|
&["relays", "wss://good.example.com"],
|
||||||
|
&["maintainers", "not-a-pubkey"],
|
||||||
|
]);
|
||||||
|
|
||||||
|
let announcement = Announcement::from_event(&event).expect("parses");
|
||||||
|
|
||||||
|
assert!(announcement.clone.is_empty());
|
||||||
|
assert_eq!(
|
||||||
|
announcement.relays,
|
||||||
|
vec![RelayUrl::parse("wss://good.example.com").unwrap()]
|
||||||
|
);
|
||||||
|
assert!(announcement.maintainers.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_upstream_tag() {
|
||||||
|
let event = announcement_event(&[
|
||||||
|
&["d", "my-fork"],
|
||||||
|
&[
|
||||||
|
"u",
|
||||||
|
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream|https://example.com/upstream.git",
|
||||||
|
"wss://relay.example.com",
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
let announcement = Announcement::from_event(&event).expect("parses");
|
||||||
|
let upstream = announcement.upstream.expect("parses the u tag");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
upstream.addr,
|
||||||
|
Some(RepoAddr::new(
|
||||||
|
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
|
||||||
|
"upstream"
|
||||||
|
))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
upstream.raw,
|
||||||
|
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream|https://example.com/upstream.git"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
upstream.display().to_string(),
|
||||||
|
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn is_fork_of_matches_the_u_tag_coordinate() {
|
||||||
|
let base = RepoAddr::new(
|
||||||
|
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
|
||||||
|
"upstream",
|
||||||
|
);
|
||||||
|
let event = announcement_event(&[&["d", "my-fork"], &["u", &base.to_string()]]);
|
||||||
|
let fork = Announcement::from_event(&event).expect("parses");
|
||||||
|
|
||||||
|
assert!(fork.is_fork_of(&base, None));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn is_fork_of_matches_a_shared_euc() {
|
||||||
|
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
||||||
|
let base_event = announcement_event(&[&["d", "upstream"], &["r", euc, "euc"]]);
|
||||||
|
let base = Announcement::from_event(&base_event).expect("parses");
|
||||||
|
let base_addr = base.addr();
|
||||||
|
|
||||||
|
let fork_event = announcement_event(&[&["d", "mirror"], &["r", euc, "euc"]]);
|
||||||
|
let fork = Announcement::from_event(&fork_event).expect("parses");
|
||||||
|
assert!(fork.is_fork_of(&base_addr, base.euc.as_deref()));
|
||||||
|
|
||||||
|
let other_event = announcement_event(&[
|
||||||
|
&["d", "other"],
|
||||||
|
&["r", "bb231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
||||||
|
]);
|
||||||
|
let other = Announcement::from_event(&other_event).expect("parses");
|
||||||
|
assert!(!other.is_fork_of(&base_addr, base.euc.as_deref()));
|
||||||
|
|
||||||
|
assert!(!fork.is_fork_of(&base_addr, None));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn is_fork_of_matches_permanent_forks_with_a_diverged_euc() {
|
||||||
|
let base = RepoAddr::new(
|
||||||
|
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
|
||||||
|
"upstream",
|
||||||
|
);
|
||||||
|
let base_euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
||||||
|
let event = announcement_event(&[
|
||||||
|
&["d", "my-fork"],
|
||||||
|
&["u", &base.to_string()],
|
||||||
|
&["r", "cc231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
||||||
|
]);
|
||||||
|
let fork = Announcement::from_event(&event).expect("parses");
|
||||||
|
|
||||||
|
assert!(fork.is_fork_of(&base, Some(base_euc)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effective_maintainers_include_owner_for_primary_repos() {
|
||||||
|
let event = announcement_event(&[&["d", "my-repo"], &["maintainers", MAINTAINER_HEX]]);
|
||||||
|
|
||||||
|
let announcement = Announcement::from_event(&event).expect("parses");
|
||||||
|
let maintainers = announcement.effective_maintainers();
|
||||||
|
|
||||||
|
assert_eq!(maintainers.len(), 2);
|
||||||
|
assert!(maintainers.contains(&announcement.owner));
|
||||||
|
assert!(maintainers.contains(&PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effective_maintainers_exclude_owner_for_subordinate_forks() {
|
||||||
|
let event = announcement_event(&[
|
||||||
|
&["d", "my-fork"],
|
||||||
|
&["u", "30617:abc:upstream|https://example.com/upstream.git"],
|
||||||
|
&["maintainers", MAINTAINER_HEX],
|
||||||
|
]);
|
||||||
|
|
||||||
|
let announcement = Announcement::from_event(&event).expect("parses");
|
||||||
|
let maintainers = announcement.effective_maintainers();
|
||||||
|
|
||||||
|
assert!(!maintainers.contains(&announcement.owner));
|
||||||
|
assert_eq!(
|
||||||
|
maintainers,
|
||||||
|
vec![PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const OWNER_KEYS: [&str; 3] = [
|
||||||
|
"0000000000000000000000000000000000000000000000000000000000000001",
|
||||||
|
"0000000000000000000000000000000000000000000000000000000000000002",
|
||||||
|
"0000000000000000000000000000000000000000000000000000000000000003",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn owned_announcement_event(owner: &str, tags: &[&[&str]]) -> Event {
|
||||||
|
let keys = Keys::new(SecretKey::from_hex(owner).expect("valid secret key"));
|
||||||
|
let tags: Vec<Tag> = tags
|
||||||
|
.iter()
|
||||||
|
.map(|t| Tag::parse(t.to_vec()).expect("valid tag"))
|
||||||
|
.collect();
|
||||||
|
EventBuilder::new(Kind::GitRepoAnnouncement)
|
||||||
|
.tags(tags)
|
||||||
|
.finalize(&keys)
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned_announcements(owner_ix: usize, tags: &[&[&str]]) -> Vec<Announcement> {
|
||||||
|
vec![
|
||||||
|
Announcement::from_event(&owned_announcement_event(OWNER_KEYS[owner_ix], tags))
|
||||||
|
.expect("parses"),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fork_candidates_orders_own_forks_first() {
|
||||||
|
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
||||||
|
let clone = "https://grasp.example/npub1x/my-fork.git";
|
||||||
|
|
||||||
|
let base_addr = RepoAddr::new(
|
||||||
|
PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey"),
|
||||||
|
"upstream",
|
||||||
|
);
|
||||||
|
let all = vec![
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "other-project"],
|
||||||
|
&["r", "bb231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(
|
||||||
|
1,
|
||||||
|
&[&["d", "my-fork"], &["r", euc, "euc"], &["clone", clone]],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "their-fork"],
|
||||||
|
&["u", &base_addr.to_string()],
|
||||||
|
&["clone", clone],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let user = PublicKey::from_hex(OWNER_KEYS[1]).expect("pubkey");
|
||||||
|
let forks = Announcement::forks_in(&all, &base_addr, Some(euc), Some(user));
|
||||||
|
|
||||||
|
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
|
||||||
|
assert_eq!(ids, vec!["my-fork", "their-fork"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fork_candidates_excludes_base_unrelated_and_unfetchable() {
|
||||||
|
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
||||||
|
let base_owner = PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey");
|
||||||
|
let base_addr = RepoAddr::new(base_owner, "upstream");
|
||||||
|
|
||||||
|
let mut all = vec![
|
||||||
|
owned_announcements(0, &[&["d", "upstream"], &["r", euc, "euc"]])
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(1, &[&["d", "no-clone-fork"], &["r", euc, "euc"]])
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "other"],
|
||||||
|
&["r", "cc231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "mirror"],
|
||||||
|
&["r", euc, "euc"],
|
||||||
|
&["clone", "https://grasp.example/x/mirror.git"],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let forks = Announcement::forks_in(&all, &base_addr, Some(euc), Some(base_owner));
|
||||||
|
assert_eq!(forks.len(), 1);
|
||||||
|
assert_eq!(forks[0].id, "mirror");
|
||||||
|
|
||||||
|
all.push(
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "u-fork"],
|
||||||
|
&["u", &base_addr.to_string()],
|
||||||
|
&["clone", "https://grasp.example/x/u-fork.git"],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
let forks = Announcement::forks_in(&all, &base_addr, None, Some(base_owner));
|
||||||
|
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
|
||||||
|
assert_eq!(ids, vec!["u-fork"]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
use nostr::prelude::*;
|
||||||
|
|
||||||
|
pub fn keys(seed: u8) -> Keys {
|
||||||
|
let mut hex = "00000000000000000000000000000000000000000000000000000000000000".to_string();
|
||||||
|
hex.push_str(&format!("{seed:02x}"));
|
||||||
|
Keys::new(SecretKey::from_hex(&hex).expect("valid secret key"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn signed(author: &Keys, kind: Kind, tags: Vec<Tag>) -> Event {
|
||||||
|
EventBuilder::new(kind)
|
||||||
|
.tags(tags)
|
||||||
|
.finalize(author)
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kind_tag(name: &str, kind: Kind) -> Tag {
|
||||||
|
Tag::parse([name, &kind.as_u16().to_string()]).expect("valid kind tag")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn uppercase_e_tag(event: &Event) -> Tag {
|
||||||
|
Tag::parse(["E", &event.id.to_hex()]).expect("valid E tag")
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::{keys, kind_tag, signed};
|
||||||
|
use nostr::prelude::*;
|
||||||
|
use signed_core::GitEvent;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn comment_activity_depends_on_the_uppercase_k_tag() {
|
||||||
|
let on_git = signed(&keys(1), Kind::Comment, vec![kind_tag("K", Kind::GitIssue)]);
|
||||||
|
let on_repo = signed(
|
||||||
|
&keys(1),
|
||||||
|
Kind::Comment,
|
||||||
|
vec![kind_tag("K", Kind::GitRepoAnnouncement)],
|
||||||
|
);
|
||||||
|
let on_note = signed(&keys(1), Kind::Comment, vec![kind_tag("K", Kind::TextNote)]);
|
||||||
|
|
||||||
|
assert!(on_git.is_git_activity());
|
||||||
|
assert!(on_repo.is_git_activity());
|
||||||
|
assert!(!on_note.is_git_activity());
|
||||||
|
assert!(!signed(&keys(1), Kind::Comment, Vec::new()).is_git_activity());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_activity_depends_on_the_lowercase_k_tag() {
|
||||||
|
let status = signed(
|
||||||
|
&keys(1),
|
||||||
|
Kind::GitStatusClosed,
|
||||||
|
vec![kind_tag("k", Kind::GitPullRequest)],
|
||||||
|
);
|
||||||
|
let unrelated = signed(
|
||||||
|
&keys(1),
|
||||||
|
Kind::GitStatusClosed,
|
||||||
|
vec![kind_tag("k", Kind::Metadata)],
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(status.is_git_activity());
|
||||||
|
assert!(!unrelated.is_git_activity());
|
||||||
|
assert!(!signed(&keys(1), Kind::GitStatusClosed, Vec::new()).is_git_activity());
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
use nostr::prelude::*;
|
||||||
|
use signed_core::inbox::{InboxReadState, ThreadResolver, group};
|
||||||
|
|
||||||
|
fn keys(seed: u8) -> Keys {
|
||||||
|
let mut hex = "00000000000000000000000000000000000000000000000000000000000000".to_string();
|
||||||
|
hex.push_str(&format!("{seed:02x}"));
|
||||||
|
Keys::new(SecretKey::from_hex(&hex).expect("valid secret key"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signed(author: &Keys, kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
|
||||||
|
EventBuilder::new(kind)
|
||||||
|
.tags(tags)
|
||||||
|
.custom_created_at(Timestamp::from_secs(created_at))
|
||||||
|
.finalize(author)
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn e_tag(event: &Event) -> Tag {
|
||||||
|
Tag::parse(["e", &event.id.to_hex()]).expect("valid e tag")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn marked_e_tag(event: &Event, marker: &str) -> Tag {
|
||||||
|
Tag::parse(["e", &event.id.to_hex(), "wss://relay.example.com", marker]).expect("valid e tag")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn uppercase_e_tag(event: &Event) -> Tag {
|
||||||
|
Tag::parse(["E", &event.id.to_hex()]).expect("valid E tag")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lookup(events: &[Event]) -> impl Fn(EventId) -> Option<Event> + '_ {
|
||||||
|
move |id| events.iter().find(|event| event.id == id).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn issue(author: &Keys, at: u64) -> Event {
|
||||||
|
signed(author, Kind::GitIssue, Vec::new(), at)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn titled_issue(author: &Keys, title: &str, at: u64) -> Event {
|
||||||
|
signed(
|
||||||
|
author,
|
||||||
|
Kind::GitIssue,
|
||||||
|
vec![Tag::parse(["subject", title]).expect("valid subject tag")],
|
||||||
|
at,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn group_merges_own_events_into_the_matching_thread() {
|
||||||
|
let me = keys(1);
|
||||||
|
let issue = titled_issue(&me, "Add retry logic", 100);
|
||||||
|
let mine = signed(
|
||||||
|
&me,
|
||||||
|
Kind::Comment,
|
||||||
|
vec![
|
||||||
|
uppercase_e_tag(&issue),
|
||||||
|
Tag::parse(["K", "1621"]).expect("K tag"),
|
||||||
|
],
|
||||||
|
150,
|
||||||
|
);
|
||||||
|
let reply = signed(
|
||||||
|
&keys(2),
|
||||||
|
Kind::Comment,
|
||||||
|
vec![
|
||||||
|
uppercase_e_tag(&issue),
|
||||||
|
Tag::parse(["K", "1621"]).expect("K tag"),
|
||||||
|
],
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
|
||||||
|
let context = [issue.clone(), mine.clone(), reply.clone()];
|
||||||
|
let items = group(
|
||||||
|
[reply.clone()],
|
||||||
|
[issue.clone(), mine.clone()],
|
||||||
|
me.public_key(),
|
||||||
|
&InboxReadState::default(),
|
||||||
|
&lookup(&context),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(items.len(), 1);
|
||||||
|
assert_eq!(items[0].root, issue.id);
|
||||||
|
assert_eq!(
|
||||||
|
items[0].root_event.as_ref().map(|event| event.id),
|
||||||
|
Some(issue.id)
|
||||||
|
);
|
||||||
|
assert_eq!(items[0].kind(), Some(Kind::GitIssue));
|
||||||
|
assert_eq!(items[0].title(), "Add retry logic");
|
||||||
|
assert_eq!(items[0].events, vec![reply.clone()]);
|
||||||
|
assert_eq!(items[0].own_events, vec![mine.clone(), issue.clone()]);
|
||||||
|
assert_eq!(
|
||||||
|
items[0]
|
||||||
|
.timeline(5)
|
||||||
|
.iter()
|
||||||
|
.map(|event| event.id)
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec![issue.id, mine.id, reply.id]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn comment_resolves_to_its_uppercase_root() {
|
||||||
|
let issue = issue(&keys(1), 100);
|
||||||
|
let comment = signed(
|
||||||
|
&keys(2),
|
||||||
|
Kind::Comment,
|
||||||
|
vec![
|
||||||
|
uppercase_e_tag(&issue),
|
||||||
|
Tag::parse(["K", "1621"]).expect("valid K tag"),
|
||||||
|
],
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
let events = [issue.clone(), comment.clone()];
|
||||||
|
assert_eq!(
|
||||||
|
ThreadResolver::new(&lookup(&events)).notification_root(&comment),
|
||||||
|
Some(issue.id)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn child_patch_resolves_to_the_root_patch() {
|
||||||
|
let root_patch = signed(&keys(1), Kind::GitPatch, Vec::new(), 100);
|
||||||
|
let child_patch = signed(&keys(1), Kind::GitPatch, vec![e_tag(&root_patch)], 200);
|
||||||
|
let events = [root_patch.clone(), child_patch.clone()];
|
||||||
|
assert_eq!(
|
||||||
|
ThreadResolver::new(&lookup(&events)).notification_root(&child_patch),
|
||||||
|
Some(root_patch.id)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_resolves_via_the_root_marker() {
|
||||||
|
let issue = issue(&keys(1), 100);
|
||||||
|
let status = signed(
|
||||||
|
&keys(2),
|
||||||
|
Kind::GitStatusClosed,
|
||||||
|
vec![marked_e_tag(&issue, "root")],
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
let events = [issue.clone(), status.clone()];
|
||||||
|
assert_eq!(
|
||||||
|
ThreadResolver::new(&lookup(&events)).notification_root(&status),
|
||||||
|
Some(issue.id)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nested_comment_chain_follows_to_the_root() {
|
||||||
|
let issue = issue(&keys(1), 100);
|
||||||
|
let reply = signed(&keys(2), Kind::Comment, vec![uppercase_e_tag(&issue)], 200);
|
||||||
|
let nested = signed(&keys(3), Kind::Comment, vec![uppercase_e_tag(&reply)], 300);
|
||||||
|
let events = [issue.clone(), reply, nested.clone()];
|
||||||
|
assert_eq!(
|
||||||
|
ThreadResolver::new(&lookup(&events)).notification_root(&nested),
|
||||||
|
Some(issue.id)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
use nostr::prelude::*;
|
||||||
|
use signed_core::PullRequest;
|
||||||
|
|
||||||
|
fn keys() -> Keys {
|
||||||
|
Keys::new(
|
||||||
|
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
|
||||||
|
.expect("valid secret key"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pr_event(content: &str, tags: Vec<Tag>) -> Event {
|
||||||
|
EventBuilder::new(Kind::GitPullRequest)
|
||||||
|
.content(content)
|
||||||
|
.tags(tags)
|
||||||
|
.finalize(&keys())
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patch_event(content: &str, tags: Vec<Tag>, created_at: u64) -> Event {
|
||||||
|
EventBuilder::new(Kind::GitPatch)
|
||||||
|
.content(content)
|
||||||
|
.tags(tags)
|
||||||
|
.custom_created_at(Timestamp::from(created_at))
|
||||||
|
.finalize(&keys())
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pull_request_patch_joins_the_whole_patch_set() {
|
||||||
|
let root = patch_event("patch-one", vec![], 100);
|
||||||
|
let second = patch_event("patch-two", vec![Tag::event(root.id)], 200);
|
||||||
|
let pr = pr_event("description", vec![Tag::event(root.id)]);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
PullRequest::new(&pr).patch([&root, &second]),
|
||||||
|
"patch-one\npatch-two"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
PullRequest::new(&pr).patches([&root, &second]),
|
||||||
|
vec![&root, &second]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pull_request_patches_walks_the_reply_chain_in_order() {
|
||||||
|
let root = patch_event("patch-one", vec![], 100);
|
||||||
|
let second = patch_event("patch-two", vec![Tag::event(root.id)], 200);
|
||||||
|
let third = patch_event("patch-three", vec![Tag::event(second.id)], 300);
|
||||||
|
let pr = pr_event("description", vec![Tag::event(root.id)]);
|
||||||
|
|
||||||
|
let series = PullRequest::new(&pr).patches([&third, &root, &second]);
|
||||||
|
assert_eq!(
|
||||||
|
series
|
||||||
|
.iter()
|
||||||
|
.map(|p| p.content.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec!["patch-one", "patch-two", "patch-three"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pull_request_patches_finds_the_set_via_the_tip_commit() {
|
||||||
|
let root = patch_event("patch-one", vec![], 100);
|
||||||
|
let tip = "1111111111111111111111111111111111111111";
|
||||||
|
let last = patch_event(
|
||||||
|
"patch-two",
|
||||||
|
vec![
|
||||||
|
Tag::event(root.id),
|
||||||
|
Tag::parse(["r", tip]).expect("valid tag"),
|
||||||
|
],
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
let pr = pr_event(
|
||||||
|
"description",
|
||||||
|
vec![Tag::parse(["c", tip]).expect("valid tag")],
|
||||||
|
);
|
||||||
|
|
||||||
|
let series = PullRequest::new(&pr).patches([&root, &last]);
|
||||||
|
assert_eq!(
|
||||||
|
series
|
||||||
|
.iter()
|
||||||
|
.map(|p| p.content.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec!["patch-one", "patch-two"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const COMMIT_HEX: &str = "1111111111111111111111111111111111111111";
|
||||||
|
const OTHER_ROOT_HEX: &str = "2222222222222222222222222222222222222222";
|
||||||
|
|
||||||
|
fn signed_at(kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
|
||||||
|
EventBuilder::new(kind)
|
||||||
|
.tags(tags)
|
||||||
|
.custom_created_at(Timestamp::from(created_at))
|
||||||
|
.finalize(&keys())
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pr_root() -> Event {
|
||||||
|
signed_at(
|
||||||
|
Kind::GitPullRequest,
|
||||||
|
vec![
|
||||||
|
Tag::parse(["c", COMMIT_HEX]).expect("valid tag"),
|
||||||
|
Tag::parse(["branch-name", "feature/x"]).expect("valid tag"),
|
||||||
|
],
|
||||||
|
100,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn latest_update_picks_newest_revision_of_the_root() {
|
||||||
|
let root = pr_root();
|
||||||
|
let root_hex = root.id.to_hex();
|
||||||
|
|
||||||
|
let revision = |created_at: u64| {
|
||||||
|
signed_at(
|
||||||
|
Kind::GitPullRequestUpdate,
|
||||||
|
vec![Tag::parse(["E", &root_hex]).expect("valid tag")],
|
||||||
|
created_at,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let unrelated = signed_at(
|
||||||
|
Kind::GitPullRequestUpdate,
|
||||||
|
vec![Tag::parse(["E", OTHER_ROOT_HEX]).expect("valid tag")],
|
||||||
|
999,
|
||||||
|
);
|
||||||
|
|
||||||
|
let events = [unrelated, revision(200), root.clone(), revision(300)];
|
||||||
|
let latest = PullRequest::latest_update(events.iter(), &root).expect("an update");
|
||||||
|
|
||||||
|
assert_eq!(latest.created_at.as_secs(), 300);
|
||||||
|
assert_eq!(latest.kind, Kind::GitPullRequestUpdate);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn latest_update_ignores_other_authors() {
|
||||||
|
let root = pr_root();
|
||||||
|
let root_hex = root.id.to_hex();
|
||||||
|
let other = Keys::new(
|
||||||
|
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000002")
|
||||||
|
.expect("valid secret key"),
|
||||||
|
);
|
||||||
|
let stranger = EventBuilder::new(Kind::GitPullRequestUpdate)
|
||||||
|
.tags([Tag::parse(["E", &root_hex]).expect("valid tag")])
|
||||||
|
.custom_created_at(Timestamp::from(999))
|
||||||
|
.finalize(&other)
|
||||||
|
.expect("signed event");
|
||||||
|
|
||||||
|
assert!(PullRequest::latest_update([&stranger, &root].into_iter(), &root).is_none());
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
use nostr::prelude::*;
|
||||||
|
use signed_core::{GitEvent, RepoStatus};
|
||||||
|
|
||||||
|
const ROOT_ID_HEX: &str = "1111111111111111111111111111111111111111111111111111111111111111";
|
||||||
|
const OTHER_ID_HEX: &str = "2222222222222222222222222222222222222222222222222222222222222222";
|
||||||
|
|
||||||
|
fn keys_from_hex(hex: &str) -> Keys {
|
||||||
|
Keys::new(SecretKey::from_hex(hex).expect("valid secret key"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root_event_id() -> EventId {
|
||||||
|
EventId::from_hex(ROOT_ID_HEX).expect("valid event id")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_event(author: &Keys, kind: Kind, root: EventId, created_at: u64) -> Event {
|
||||||
|
EventBuilder::new(kind)
|
||||||
|
.tags([Tag::event(root)])
|
||||||
|
.custom_created_at(Timestamp::from(created_at))
|
||||||
|
.finalize(author)
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn references_root_matches_e_tag() {
|
||||||
|
let root = root_event_id();
|
||||||
|
let event = EventBuilder::new(Kind::GitStatusOpen)
|
||||||
|
.tags([Tag::event(root)])
|
||||||
|
.finalize(&keys_from_hex(
|
||||||
|
"0000000000000000000000000000000000000000000000000000000000000001",
|
||||||
|
))
|
||||||
|
.expect("signed event");
|
||||||
|
|
||||||
|
assert!(event.references_root(&root));
|
||||||
|
assert!(!event.references_root(&EventId::from_hex(OTHER_ID_HEX).expect("valid id")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn latest_status_wins() {
|
||||||
|
let owner = keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
|
||||||
|
let maintainer =
|
||||||
|
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
|
||||||
|
let root = root_event_id();
|
||||||
|
|
||||||
|
let statuses = [
|
||||||
|
status_event(&maintainer, Kind::GitStatusClosed, root, 100),
|
||||||
|
status_event(&owner, Kind::GitStatusOpen, root, 200),
|
||||||
|
];
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
RepoStatus::resolve(
|
||||||
|
statuses.iter(),
|
||||||
|
&owner.public_key(),
|
||||||
|
&[maintainer.public_key()]
|
||||||
|
),
|
||||||
|
RepoStatus::Open
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ignores_statuses_from_others() {
|
||||||
|
let owner = keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
|
||||||
|
let maintainer =
|
||||||
|
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
|
||||||
|
let stranger =
|
||||||
|
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000003");
|
||||||
|
let root = root_event_id();
|
||||||
|
|
||||||
|
let statuses = [
|
||||||
|
status_event(&stranger, Kind::GitStatusClosed, root, 300),
|
||||||
|
status_event(&maintainer, Kind::GitStatusDraft, root, 100),
|
||||||
|
];
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
RepoStatus::resolve(
|
||||||
|
statuses.iter(),
|
||||||
|
&owner.public_key(),
|
||||||
|
&[maintainer.public_key()]
|
||||||
|
),
|
||||||
|
RepoStatus::Draft
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -7,6 +7,15 @@ pub enum DiffLineKind {
|
|||||||
Deletion,
|
Deletion,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum DiffStatus {
|
||||||
|
Added,
|
||||||
|
Modified,
|
||||||
|
Deleted,
|
||||||
|
Renamed,
|
||||||
|
Copied,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct DiffLine {
|
pub struct DiffLine {
|
||||||
pub kind: DiffLineKind,
|
pub kind: DiffLineKind,
|
||||||
@@ -55,15 +64,6 @@ impl DiffHunk {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum DiffStatus {
|
|
||||||
Added,
|
|
||||||
Modified,
|
|
||||||
Deleted,
|
|
||||||
Renamed,
|
|
||||||
Copied,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct FileDiff {
|
pub struct FileDiff {
|
||||||
pub path: String,
|
pub path: String,
|
||||||
|
|||||||
@@ -81,39 +81,42 @@ impl FileCommit {
|
|||||||
},
|
},
|
||||||
String::from_utf8_lossy(author.name).trim().to_string(),
|
String::from_utf8_lossy(author.name).trim().to_string(),
|
||||||
time.seconds,
|
time.seconds,
|
||||||
format_commit_date(time),
|
Self::format_date(time),
|
||||||
commit.parent_ids().map(|id| id.to_string()).collect(),
|
commit.parent_ids().map(|id| id.to_string()).collect(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Formats a gix time as "Nov 21, 2026 at 4:40 AM GMT+7" in the commit's own offset.
|
/// Formats a gix time as "Nov 21, 2026 at 4:40 AM GMT+7" in the commit's own offset.
|
||||||
pub(crate) fn format_commit_date(time: gix::date::Time) -> String {
|
pub(crate) fn format_date(time: gix::date::Time) -> String {
|
||||||
let Ok(timestamp) = jiff::Timestamp::from_second(time.seconds) else {
|
let Ok(timestamp) = jiff::Timestamp::from_second(time.seconds) else {
|
||||||
return String::new();
|
return String::new();
|
||||||
};
|
};
|
||||||
let Ok(offset) = jiff::tz::Offset::from_seconds(time.offset) else {
|
|
||||||
return String::new();
|
|
||||||
};
|
|
||||||
let datetime = offset.to_datetime(timestamp);
|
|
||||||
|
|
||||||
let label = datetime.strftime("%b %-d, %Y at %-I:%M %p").to_string();
|
let Ok(offset) = jiff::tz::Offset::from_seconds(time.offset) else {
|
||||||
format!("{label} {}", gmt_label(time.offset))
|
return String::new();
|
||||||
}
|
};
|
||||||
|
|
||||||
/// The GMT offset label for a seconds offset, e.g. "GMT", "GMT+7", "GMT-5:30".
|
let datetime = offset.to_datetime(timestamp);
|
||||||
fn gmt_label(offset: i32) -> String {
|
let label = datetime.strftime("%b %-d, %Y at %-I:%M %p").to_string();
|
||||||
if offset == 0 {
|
|
||||||
return "GMT".to_owned();
|
format!("{label} {}", Self::gmt_label(time.offset))
|
||||||
}
|
}
|
||||||
|
|
||||||
let sign = if offset < 0 { '-' } else { '+' };
|
/// The GMT offset label for a seconds offset, e.g. "GMT", "GMT+7", "GMT-5:30".
|
||||||
let total_minutes = offset.abs() / 60;
|
fn gmt_label(offset: i32) -> String {
|
||||||
let hours = total_minutes / 60;
|
if offset == 0 {
|
||||||
let minutes = total_minutes % 60;
|
return "GMT".to_owned();
|
||||||
if minutes == 0 {
|
}
|
||||||
format!("GMT{sign}{hours}")
|
|
||||||
} else {
|
let sign = if offset < 0 { '-' } else { '+' };
|
||||||
format!("GMT{sign}{hours}:{minutes:02}")
|
let total_minutes = offset.abs() / 60;
|
||||||
|
let hours = total_minutes / 60;
|
||||||
|
let minutes = total_minutes % 60;
|
||||||
|
|
||||||
|
if minutes == 0 {
|
||||||
|
format!("GMT{sign}{hours}")
|
||||||
|
} else {
|
||||||
|
format!("GMT{sign}{hours}:{minutes:02}")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,16 +8,13 @@ mod scan;
|
|||||||
mod sync;
|
mod sync;
|
||||||
mod worktree;
|
mod worktree;
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
||||||
pub use cache::GitCache;
|
pub use cache::GitCache;
|
||||||
pub use diff::{CommitDiff, DiffHunk, DiffLine, DiffLineKind, DiffStatus, FileDiff};
|
pub use diff::{CommitDiff, DiffHunk, DiffLine, DiffLineKind, DiffStatus, FileDiff};
|
||||||
pub use history::{CommitList, FileCommit, MAX_LISTED_COMMITS};
|
pub use history::{CommitList, FileCommit, MAX_LISTED_COMMITS};
|
||||||
pub use nip34::{GraspSignals, Nip34Binding, Nip34Kind};
|
pub use nip34::{GraspSignals, Nip34Binding, Nip34Kind};
|
||||||
pub use patch::PatchParser;
|
pub use patch::PatchParser;
|
||||||
pub use repo::{Repo, RepoRefState};
|
pub use repo::{Repo, RepoRefState};
|
||||||
pub use scan::{LocalRepo, find_git_repos};
|
pub use scan::LocalRepo;
|
||||||
pub use sync::{RefSync, RepoSyncStatus};
|
pub use sync::{RefSync, RepoSyncStatus};
|
||||||
pub use worktree::WorktreeSnapshot;
|
pub use worktree::WorktreeSnapshot;
|
||||||
|
|
||||||
@@ -34,18 +31,3 @@ where
|
|||||||
self.map_err(|exn| anyhow::Error::from(exn.into_error()))
|
self.map_err(|exn| anyhow::Error::from(exn.into_error()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
fn git_in(dir: &std::path::Path, args: &[&str]) -> anyhow::Result<String> {
|
|
||||||
let output = Repo::run_git(dir, args, "git")?;
|
|
||||||
|
|
||||||
if !output.status.success() {
|
|
||||||
anyhow::bail!(
|
|
||||||
"git {} failed: {}",
|
|
||||||
args.join(" "),
|
|
||||||
String::from_utf8_lossy(&output.stderr).trim()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,11 +1,5 @@
|
|||||||
use nostr::prelude::*;
|
use nostr::prelude::*;
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
pub(crate) struct Nip34Json {
|
|
||||||
pub(crate) identifier: Option<String>,
|
|
||||||
pub(crate) owner: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum Nip34Kind {
|
pub enum Nip34Kind {
|
||||||
Initialized,
|
Initialized,
|
||||||
@@ -13,6 +7,12 @@ pub enum Nip34Kind {
|
|||||||
ToolingOnly,
|
ToolingOnly,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub(crate) struct Nip34Json {
|
||||||
|
pub(crate) identifier: Option<String>,
|
||||||
|
pub(crate) owner: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||||
pub struct GraspSignals {
|
pub struct GraspSignals {
|
||||||
pub nip34_json: bool,
|
pub nip34_json: bool,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use diffy::patch_set::{FileOperation, FilePatch, ParseOptions, PatchSet};
|
|||||||
use diffy::{Hunk, Line};
|
use diffy::{Hunk, Line};
|
||||||
|
|
||||||
use crate::diff::{CommitDiff, DiffHunk, DiffLineKind, DiffStatus, FileDiff, HunkBuilder};
|
use crate::diff::{CommitDiff, DiffHunk, DiffLineKind, DiffStatus, FileDiff, HunkBuilder};
|
||||||
use crate::history::{FileCommit, format_commit_date};
|
use crate::history::FileCommit;
|
||||||
|
|
||||||
pub struct PatchParser;
|
pub struct PatchParser;
|
||||||
|
|
||||||
@@ -75,7 +75,7 @@ impl PatchParser {
|
|||||||
.map(Self::name_from_address)
|
.map(Self::name_from_address)
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
time.map(|time| time.seconds).unwrap_or(0),
|
time.map(|time| time.seconds).unwrap_or(0),
|
||||||
time.map(format_commit_date).unwrap_or_default(),
|
time.map(FileCommit::format_date).unwrap_or_default(),
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1847,7 +1847,9 @@ impl Repo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Matches grasp URLs by shape: two path segments with an npub owner.
|
/// Matches grasp URLs by shape: two path segments with an npub owner.
|
||||||
pub(crate) fn is_grasp_url(url: &str) -> bool {
|
///
|
||||||
|
/// Returns whether a URL has the grasp server clone shape.
|
||||||
|
pub fn is_grasp_url(url: &str) -> bool {
|
||||||
let Ok(parsed) = Url::parse(url) else {
|
let Ok(parsed) = Url::parse(url) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
@@ -1943,240 +1945,3 @@ impl Repo {
|
|||||||
.unwrap_or_else(|| url.to_owned())
|
.unwrap_or_else(|| url.to_owned())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::path::Path;
|
|
||||||
use std::process::Command;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// Creates a fresh repository in a temp directory.
|
|
||||||
fn init_repo() -> (tempfile::TempDir, std::path::PathBuf) {
|
|
||||||
let dir = tempfile::tempdir().expect("tempdir");
|
|
||||||
let path = dir.path().join("repo");
|
|
||||||
std::fs::create_dir_all(&path).expect("mkdir");
|
|
||||||
git(&path, &["init", "-q"]);
|
|
||||||
(dir, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs `git` in `dir`, failing the test on a non-zero exit.
|
|
||||||
fn git(dir: &Path, args: &[&str]) {
|
|
||||||
let status = Command::new("git")
|
|
||||||
.current_dir(dir)
|
|
||||||
.env("GIT_AUTHOR_NAME", "Test Author")
|
|
||||||
.env("GIT_AUTHOR_EMAIL", "test@example.com")
|
|
||||||
.env("GIT_COMMITTER_NAME", "Test Author")
|
|
||||||
.env("GIT_COMMITTER_EMAIL", "test@example.com")
|
|
||||||
.env("GIT_EDITOR", "true")
|
|
||||||
.args(args)
|
|
||||||
.status()
|
|
||||||
.expect("spawn git");
|
|
||||||
assert!(status.success(), "git {args:?} failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates a fresh public key.
|
|
||||||
fn key() -> PublicKey {
|
|
||||||
Keys::generate().public_key()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes a NIP-34 coordinate as an `naddr` string.
|
|
||||||
fn naddr(kind: Kind, owner: PublicKey, identifier: &str) -> String {
|
|
||||||
let coordinate = Coordinate::new(kind, owner).identifier(identifier);
|
|
||||||
Nip19Coordinate::new(coordinate, Vec::<RelayUrl>::new())
|
|
||||||
.to_bech32()
|
|
||||||
.expect("naddr")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Opens the repository at `path` and returns its NIP-34 binding.
|
|
||||||
fn binding_of(path: &Path) -> Option<Nip34Binding> {
|
|
||||||
Repo::open(path).ok()?.nip34_binding()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn plain_repository_has_no_binding() {
|
|
||||||
let (_dir, path) = init_repo();
|
|
||||||
assert!(binding_of(&path).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nip34_json_marks_a_repository_initialized() {
|
|
||||||
let (_dir, path) = init_repo();
|
|
||||||
let owner = key();
|
|
||||||
let npub = owner.to_bech32().expect("npub");
|
|
||||||
std::fs::write(
|
|
||||||
path.join("nip34.json"),
|
|
||||||
format!(r#"{{"identifier":"my-repo","owner":"{npub}"}}"#),
|
|
||||||
)
|
|
||||||
.expect("write");
|
|
||||||
|
|
||||||
let binding = binding_of(&path).expect("binding");
|
|
||||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
|
||||||
assert!(binding.signals.nip34_json);
|
|
||||||
assert_eq!(binding.owner, Some(owner));
|
|
||||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn malformed_nip34_json_is_ignored() {
|
|
||||||
let (_dir, path) = init_repo();
|
|
||||||
std::fs::write(path.join("nip34.json"), b"not json").expect("write");
|
|
||||||
|
|
||||||
assert!(binding_of(&path).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn commit_patch_applies_cleanly_to_parent() {
|
|
||||||
let (dir, path) = init_repo();
|
|
||||||
git(&path, &["config", "user.name", "Test Author"]);
|
|
||||||
git(&path, &["config", "user.email", "test@example.com"]);
|
|
||||||
std::fs::write(path.join("file.txt"), "one\n").expect("write");
|
|
||||||
git(&path, &["add", "."]);
|
|
||||||
git(&path, &["commit", "-q", "-m", "first"]);
|
|
||||||
std::fs::write(path.join("file.txt"), "two\n").expect("write");
|
|
||||||
std::fs::write(path.join("file2.txt"), "added\n").expect("write");
|
|
||||||
git(&path, &["add", "."]);
|
|
||||||
git(&path, &["commit", "-q", "-m", "second"]);
|
|
||||||
|
|
||||||
let patch = Repo::open(&path)
|
|
||||||
.expect("open repo")
|
|
||||||
.commit_patch("HEAD")
|
|
||||||
.expect("commit patch");
|
|
||||||
assert!(patch.contains("diff --git a/file.txt b/file.txt"));
|
|
||||||
assert!(patch.contains("diff --git a/file2.txt b/file2.txt"));
|
|
||||||
assert!(patch.contains("--- /dev/null"));
|
|
||||||
assert!(patch.contains("+added"));
|
|
||||||
|
|
||||||
let patch_path = dir.path().join("head.patch");
|
|
||||||
std::fs::write(&patch_path, &patch).expect("write patch");
|
|
||||||
git(&path, &["checkout", "-q", "--detach", "HEAD~1"]);
|
|
||||||
git(
|
|
||||||
&path,
|
|
||||||
&["apply", patch_path.to_str().expect("utf8 patch path")],
|
|
||||||
);
|
|
||||||
|
|
||||||
let applied = std::fs::read_to_string(path.join("file.txt")).expect("read");
|
|
||||||
assert_eq!(applied, "two\n");
|
|
||||||
assert_eq!(
|
|
||||||
std::fs::read_to_string(path.join("file2.txt")).expect("read"),
|
|
||||||
"added\n"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nak_exclude_and_state_refs_are_detected() {
|
|
||||||
let (_dir, path) = init_repo();
|
|
||||||
|
|
||||||
std::fs::create_dir_all(path.join(".git/info")).expect("mkdir");
|
|
||||||
std::fs::write(path.join(".git/info/exclude"), "nip34.json\n").expect("write");
|
|
||||||
|
|
||||||
git(&path, &["commit", "-q", "--allow-empty", "-m", "initial"]);
|
|
||||||
git(
|
|
||||||
&path,
|
|
||||||
&["update-ref", "refs/heads/nip34/state/HEAD", "HEAD"],
|
|
||||||
);
|
|
||||||
|
|
||||||
let binding = binding_of(&path).expect("binding");
|
|
||||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
|
||||||
assert!(binding.signals.nip34_excluded);
|
|
||||||
assert!(binding.signals.nip34_state_refs);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nostr_repo_config_marks_a_repository_initialized() {
|
|
||||||
let (_dir, path) = init_repo();
|
|
||||||
let owner = key();
|
|
||||||
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
|
|
||||||
git(&path, &["config", "nostr.repo", &naddr]);
|
|
||||||
|
|
||||||
let binding = binding_of(&path).expect("binding");
|
|
||||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
|
||||||
assert!(binding.signals.nostr_repo_config);
|
|
||||||
assert_eq!(binding.owner, Some(owner));
|
|
||||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_written_nostr_repo_marker_is_detected() {
|
|
||||||
let (_dir, path) = init_repo();
|
|
||||||
let owner = key();
|
|
||||||
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
|
|
||||||
|
|
||||||
Repo::open(&path)
|
|
||||||
.expect("open")
|
|
||||||
.set_nostr_repo(&naddr)
|
|
||||||
.expect("write marker");
|
|
||||||
|
|
||||||
let binding = binding_of(&path).expect("binding");
|
|
||||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
|
||||||
assert!(binding.signals.nostr_repo_config);
|
|
||||||
assert_eq!(binding.owner, Some(owner));
|
|
||||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nostr_remote_is_a_nip34_clone() {
|
|
||||||
let (_dir, path) = init_repo();
|
|
||||||
let owner = key();
|
|
||||||
let npub = owner.to_bech32().expect("npub");
|
|
||||||
let url = format!("nostr://{npub}/relay.ngit.dev/my-repo");
|
|
||||||
git(&path, &["remote", "add", "origin", &url]);
|
|
||||||
|
|
||||||
let binding = binding_of(&path).expect("binding");
|
|
||||||
assert_eq!(binding.kind, Nip34Kind::Cloned);
|
|
||||||
assert!(binding.signals.nostr_remote);
|
|
||||||
assert_eq!(binding.owner, Some(owner));
|
|
||||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nak_grasp_remote_marks_a_repository_initialized() {
|
|
||||||
let (_dir, path) = init_repo();
|
|
||||||
let owner = key();
|
|
||||||
let npub = owner.to_bech32().expect("npub");
|
|
||||||
let url = format!("https://gitnostr.com/{npub}/my-repo.git");
|
|
||||||
git(
|
|
||||||
&path,
|
|
||||||
&["config", "remote.nip34/grasp/gitnostr.com.url", &url],
|
|
||||||
);
|
|
||||||
|
|
||||||
let binding = binding_of(&path).expect("binding");
|
|
||||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
|
||||||
assert!(binding.signals.nip34_grasp_remote);
|
|
||||||
assert!(binding.signals.grasp_remote);
|
|
||||||
assert_eq!(binding.grasp_urls, vec![url]);
|
|
||||||
assert_eq!(binding.owner, Some(owner));
|
|
||||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nostr_cache_alone_is_tooling_only() {
|
|
||||||
let (_dir, path) = init_repo();
|
|
||||||
std::fs::write(path.join(".git/nostr-cache.lmdb"), b"cache").expect("write");
|
|
||||||
|
|
||||||
let binding = binding_of(&path).expect("binding");
|
|
||||||
assert_eq!(binding.kind, Nip34Kind::ToolingOnly);
|
|
||||||
assert!(binding.signals.nostr_cache);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn grasp_urls_are_recognised_by_shape() {
|
|
||||||
let owner = key();
|
|
||||||
let npub = owner.to_bech32().expect("npub");
|
|
||||||
|
|
||||||
assert!(Repo::is_grasp_url(&format!(
|
|
||||||
"https://gitnostr.com/{npub}/my-repo.git"
|
|
||||||
)));
|
|
||||||
assert!(Repo::is_grasp_url(&format!(
|
|
||||||
"grasp://gitnostr.com/{npub}/my-repo.git"
|
|
||||||
)));
|
|
||||||
|
|
||||||
assert!(!Repo::is_grasp_url("https://gitnostr.com/my-repo.git"));
|
|
||||||
assert!(!Repo::is_grasp_url(
|
|
||||||
"https://gitnostr.com/not-a-pubkey/my-repo.git"
|
|
||||||
));
|
|
||||||
assert!(!Repo::is_grasp_url(&format!(
|
|
||||||
"ssh://gitnostr.com/{npub}/my-repo.git"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -19,69 +19,69 @@ impl LocalRepo {
|
|||||||
pub fn new(path: PathBuf, nip34: Option<Nip34Binding>) -> Self {
|
pub fn new(path: PathBuf, nip34: Option<Nip34Binding>) -> Self {
|
||||||
Self { path, nip34 }
|
Self { path, nip34 }
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Finds git repositories under `root` up to `SCAN_MAX_DEPTH` deep, without descending into them.
|
/// Finds git repositories under `root` up to `SCAN_MAX_DEPTH` deep, without descending into them.
|
||||||
pub fn find_git_repos(root: &Path) -> Vec<LocalRepo> {
|
pub fn find_all(root: &Path) -> Vec<Self> {
|
||||||
let Ok(root) = root.canonicalize() else {
|
let Ok(root) = root.canonicalize() else {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
};
|
};
|
||||||
|
|
||||||
let found = Arc::new(Mutex::new(Vec::<PathBuf>::new()));
|
let found = Arc::new(Mutex::new(Vec::<PathBuf>::new()));
|
||||||
|
|
||||||
let walker = WalkBuilder::new(&root)
|
let walker = WalkBuilder::new(&root)
|
||||||
.max_depth(Some(SCAN_MAX_DEPTH))
|
.max_depth(Some(SCAN_MAX_DEPTH))
|
||||||
.require_git(false)
|
.require_git(false)
|
||||||
.filter_entry({
|
.filter_entry({
|
||||||
let found = found.clone();
|
let found = found.clone();
|
||||||
move |entry| {
|
move |entry| {
|
||||||
let Some(kind) = entry.file_type() else {
|
let Some(kind) = entry.file_type() else {
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
if !kind.is_dir() {
|
if !kind.is_dir() {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if entry.file_name() == std::ffi::OsStr::new(".git") {
|
if entry.file_name() == std::ffi::OsStr::new(".git") {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
let dir = entry.path();
|
let dir = entry.path();
|
||||||
let Ok(repo) = gix::discover(dir) else {
|
let Ok(repo) = gix::discover(dir) else {
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
let Some(workdir) = repo.workdir() else {
|
let Some(workdir) = repo.workdir() else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
if workdir != dir {
|
if workdir != dir {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
match found.lock() {
|
match found.lock() {
|
||||||
Ok(mut repos) => repos.push(dir.to_path_buf()),
|
Ok(mut repos) => repos.push(dir.to_path_buf()),
|
||||||
Err(poisoned) => poisoned.into_inner().push(dir.to_path_buf()),
|
Err(poisoned) => poisoned.into_inner().push(dir.to_path_buf()),
|
||||||
|
}
|
||||||
|
false
|
||||||
}
|
}
|
||||||
false
|
})
|
||||||
}
|
.build();
|
||||||
})
|
|
||||||
.build();
|
|
||||||
|
|
||||||
for _ in walker {}
|
for _ in walker {}
|
||||||
|
|
||||||
let mut repos = match found.lock() {
|
let mut repos = match found.lock() {
|
||||||
Ok(mut repos) => std::mem::take(&mut *repos),
|
Ok(mut repos) => std::mem::take(&mut *repos),
|
||||||
Err(poisoned) => std::mem::take(&mut *poisoned.into_inner()),
|
Err(poisoned) => std::mem::take(&mut *poisoned.into_inner()),
|
||||||
};
|
};
|
||||||
repos.sort();
|
|
||||||
|
|
||||||
repos
|
repos.sort();
|
||||||
.into_iter()
|
repos
|
||||||
.map(|path| {
|
.into_iter()
|
||||||
let nip34 = Repo::open(&path).ok().and_then(|repo| repo.nip34_binding());
|
.map(|path| {
|
||||||
LocalRepo::new(path, nip34)
|
let nip34 = Repo::open(&path).ok().and_then(|repo| repo.nip34_binding());
|
||||||
})
|
LocalRepo::new(path, nip34)
|
||||||
.collect()
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
use nostr::prelude::Keys;
|
use nostr::prelude::*;
|
||||||
use signed_core::RepoAddr;
|
use signed_core::RepoAddr;
|
||||||
|
use signed_git::{DiffStatus, GitCache, LocalRepo, Nip34Binding, Nip34Kind, PatchParser, Repo};
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn blocks_parent_components() {
|
fn blocks_parent_components() {
|
||||||
@@ -827,6 +826,11 @@ fn git_run(dir: &Path, args: &[&str]) -> std::process::Output {
|
|||||||
output
|
output
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn git_in(dir: &Path, args: &[&str]) -> anyhow::Result<String> {
|
||||||
|
let output = git_run(dir, args);
|
||||||
|
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn find_git_repos_reports_the_outermost_repository() {
|
fn find_git_repos_reports_the_outermost_repository() {
|
||||||
let root = tempfile::tempdir().expect("tempdir");
|
let root = tempfile::tempdir().expect("tempdir");
|
||||||
@@ -837,7 +841,7 @@ fn find_git_repos_reports_the_outermost_repository() {
|
|||||||
let plain_dir = root.path().join("plain").join("deep");
|
let plain_dir = root.path().join("plain").join("deep");
|
||||||
std::fs::create_dir_all(&plain_dir).expect("mkdir");
|
std::fs::create_dir_all(&plain_dir).expect("mkdir");
|
||||||
|
|
||||||
let repos = find_git_repos(root.path());
|
let repos = LocalRepo::find_all(root.path());
|
||||||
|
|
||||||
assert_eq!(repos.len(), 1);
|
assert_eq!(repos.len(), 1);
|
||||||
assert_eq!(repos[0].path, repo_dir.canonicalize().expect("canonical"));
|
assert_eq!(repos[0].path, repo_dir.canonicalize().expect("canonical"));
|
||||||
@@ -855,7 +859,7 @@ fn find_git_repos_skips_repositories_nested_in_repositories() {
|
|||||||
std::fs::create_dir_all(&nested).expect("mkdir");
|
std::fs::create_dir_all(&nested).expect("mkdir");
|
||||||
git_run(&nested, &["init", "-q"]);
|
git_run(&nested, &["init", "-q"]);
|
||||||
|
|
||||||
let repos = find_git_repos(root.path());
|
let repos = LocalRepo::find_all(root.path());
|
||||||
|
|
||||||
assert_eq!(repos.len(), 1);
|
assert_eq!(repos.len(), 1);
|
||||||
assert_eq!(repos[0].path, outer.canonicalize().expect("canonical"));
|
assert_eq!(repos[0].path, outer.canonicalize().expect("canonical"));
|
||||||
@@ -869,7 +873,7 @@ fn find_git_repos_ignores_a_repository_above_the_scan_root() {
|
|||||||
let root = outer.path().join("scan");
|
let root = outer.path().join("scan");
|
||||||
std::fs::create_dir_all(&root).expect("mkdir");
|
std::fs::create_dir_all(&root).expect("mkdir");
|
||||||
|
|
||||||
assert!(find_git_repos(&root).is_empty());
|
assert!(LocalRepo::find_all(&root).is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates an empty bare server repository for push tests.
|
/// Creates an empty bare server repository for push tests.
|
||||||
@@ -1066,3 +1070,232 @@ fn read_at_reads_the_files_of_that_commit() {
|
|||||||
.is_err()
|
.is_err()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates a fresh repository in a temp directory.
|
||||||
|
fn init_repo() -> (tempfile::TempDir, std::path::PathBuf) {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let path = dir.path().join("repo");
|
||||||
|
std::fs::create_dir_all(&path).expect("mkdir");
|
||||||
|
git(&path, &["init", "-q"]);
|
||||||
|
(dir, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `git` in `dir`, failing the test on a non-zero exit.
|
||||||
|
fn git(dir: &Path, args: &[&str]) {
|
||||||
|
let status = Command::new("git")
|
||||||
|
.current_dir(dir)
|
||||||
|
.env("GIT_AUTHOR_NAME", "Test Author")
|
||||||
|
.env("GIT_AUTHOR_EMAIL", "test@example.com")
|
||||||
|
.env("GIT_COMMITTER_NAME", "Test Author")
|
||||||
|
.env("GIT_COMMITTER_EMAIL", "test@example.com")
|
||||||
|
.env("GIT_EDITOR", "true")
|
||||||
|
.args(args)
|
||||||
|
.status()
|
||||||
|
.expect("spawn git");
|
||||||
|
assert!(status.success(), "git {args:?} failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates a fresh public key.
|
||||||
|
fn key() -> PublicKey {
|
||||||
|
Keys::generate().public_key()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a NIP-34 coordinate as an `naddr` string.
|
||||||
|
fn naddr(kind: Kind, owner: PublicKey, identifier: &str) -> String {
|
||||||
|
let coordinate = Coordinate::new(kind, owner).identifier(identifier);
|
||||||
|
Nip19Coordinate::new(coordinate, Vec::<RelayUrl>::new())
|
||||||
|
.to_bech32()
|
||||||
|
.expect("naddr")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the repository at `path` and returns its NIP-34 binding.
|
||||||
|
fn binding_of(path: &Path) -> Option<Nip34Binding> {
|
||||||
|
Repo::open(path).ok()?.nip34_binding()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plain_repository_has_no_binding() {
|
||||||
|
let (_dir, path) = init_repo();
|
||||||
|
assert!(binding_of(&path).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nip34_json_marks_a_repository_initialized() {
|
||||||
|
let (_dir, path) = init_repo();
|
||||||
|
let owner = key();
|
||||||
|
let npub = owner.to_bech32().expect("npub");
|
||||||
|
std::fs::write(
|
||||||
|
path.join("nip34.json"),
|
||||||
|
format!(r#"{{"identifier":"my-repo","owner":"{npub}"}}"#),
|
||||||
|
)
|
||||||
|
.expect("write");
|
||||||
|
|
||||||
|
let binding = binding_of(&path).expect("binding");
|
||||||
|
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||||
|
assert!(binding.signals.nip34_json);
|
||||||
|
assert_eq!(binding.owner, Some(owner));
|
||||||
|
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_nip34_json_is_ignored() {
|
||||||
|
let (_dir, path) = init_repo();
|
||||||
|
std::fs::write(path.join("nip34.json"), b"not json").expect("write");
|
||||||
|
|
||||||
|
assert!(binding_of(&path).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn commit_patch_applies_cleanly_to_parent() {
|
||||||
|
let (dir, path) = init_repo();
|
||||||
|
git(&path, &["config", "user.name", "Test Author"]);
|
||||||
|
git(&path, &["config", "user.email", "test@example.com"]);
|
||||||
|
std::fs::write(path.join("file.txt"), "one\n").expect("write");
|
||||||
|
git(&path, &["add", "."]);
|
||||||
|
git(&path, &["commit", "-q", "-m", "first"]);
|
||||||
|
std::fs::write(path.join("file.txt"), "two\n").expect("write");
|
||||||
|
std::fs::write(path.join("file2.txt"), "added\n").expect("write");
|
||||||
|
git(&path, &["add", "."]);
|
||||||
|
git(&path, &["commit", "-q", "-m", "second"]);
|
||||||
|
|
||||||
|
let patch = Repo::open(&path)
|
||||||
|
.expect("open repo")
|
||||||
|
.commit_patch("HEAD")
|
||||||
|
.expect("commit patch");
|
||||||
|
assert!(patch.contains("diff --git a/file.txt b/file.txt"));
|
||||||
|
assert!(patch.contains("diff --git a/file2.txt b/file2.txt"));
|
||||||
|
assert!(patch.contains("--- /dev/null"));
|
||||||
|
assert!(patch.contains("+added"));
|
||||||
|
|
||||||
|
let patch_path = dir.path().join("head.patch");
|
||||||
|
std::fs::write(&patch_path, &patch).expect("write patch");
|
||||||
|
git(&path, &["checkout", "-q", "--detach", "HEAD~1"]);
|
||||||
|
git(
|
||||||
|
&path,
|
||||||
|
&["apply", patch_path.to_str().expect("utf8 patch path")],
|
||||||
|
);
|
||||||
|
|
||||||
|
let applied = std::fs::read_to_string(path.join("file.txt")).expect("read");
|
||||||
|
assert_eq!(applied, "two\n");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(path.join("file2.txt")).expect("read"),
|
||||||
|
"added\n"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nak_exclude_and_state_refs_are_detected() {
|
||||||
|
let (_dir, path) = init_repo();
|
||||||
|
|
||||||
|
std::fs::create_dir_all(path.join(".git/info")).expect("mkdir");
|
||||||
|
std::fs::write(path.join(".git/info/exclude"), "nip34.json\n").expect("write");
|
||||||
|
|
||||||
|
git(&path, &["commit", "-q", "--allow-empty", "-m", "initial"]);
|
||||||
|
git(
|
||||||
|
&path,
|
||||||
|
&["update-ref", "refs/heads/nip34/state/HEAD", "HEAD"],
|
||||||
|
);
|
||||||
|
|
||||||
|
let binding = binding_of(&path).expect("binding");
|
||||||
|
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||||
|
assert!(binding.signals.nip34_excluded);
|
||||||
|
assert!(binding.signals.nip34_state_refs);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nostr_repo_config_marks_a_repository_initialized() {
|
||||||
|
let (_dir, path) = init_repo();
|
||||||
|
let owner = key();
|
||||||
|
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
|
||||||
|
git(&path, &["config", "nostr.repo", &naddr]);
|
||||||
|
|
||||||
|
let binding = binding_of(&path).expect("binding");
|
||||||
|
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||||
|
assert!(binding.signals.nostr_repo_config);
|
||||||
|
assert_eq!(binding.owner, Some(owner));
|
||||||
|
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_written_nostr_repo_marker_is_detected() {
|
||||||
|
let (_dir, path) = init_repo();
|
||||||
|
let owner = key();
|
||||||
|
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
|
||||||
|
|
||||||
|
Repo::open(&path)
|
||||||
|
.expect("open")
|
||||||
|
.set_nostr_repo(&naddr)
|
||||||
|
.expect("write marker");
|
||||||
|
|
||||||
|
let binding = binding_of(&path).expect("binding");
|
||||||
|
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||||
|
assert!(binding.signals.nostr_repo_config);
|
||||||
|
assert_eq!(binding.owner, Some(owner));
|
||||||
|
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nostr_remote_is_a_nip34_clone() {
|
||||||
|
let (_dir, path) = init_repo();
|
||||||
|
let owner = key();
|
||||||
|
let npub = owner.to_bech32().expect("npub");
|
||||||
|
let url = format!("nostr://{npub}/relay.ngit.dev/my-repo");
|
||||||
|
git(&path, &["remote", "add", "origin", &url]);
|
||||||
|
|
||||||
|
let binding = binding_of(&path).expect("binding");
|
||||||
|
assert_eq!(binding.kind, Nip34Kind::Cloned);
|
||||||
|
assert!(binding.signals.nostr_remote);
|
||||||
|
assert_eq!(binding.owner, Some(owner));
|
||||||
|
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nak_grasp_remote_marks_a_repository_initialized() {
|
||||||
|
let (_dir, path) = init_repo();
|
||||||
|
let owner = key();
|
||||||
|
let npub = owner.to_bech32().expect("npub");
|
||||||
|
let url = format!("https://gitnostr.com/{npub}/my-repo.git");
|
||||||
|
git(
|
||||||
|
&path,
|
||||||
|
&["config", "remote.nip34/grasp/gitnostr.com.url", &url],
|
||||||
|
);
|
||||||
|
|
||||||
|
let binding = binding_of(&path).expect("binding");
|
||||||
|
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||||
|
assert!(binding.signals.nip34_grasp_remote);
|
||||||
|
assert!(binding.signals.grasp_remote);
|
||||||
|
assert_eq!(binding.grasp_urls, vec![url]);
|
||||||
|
assert_eq!(binding.owner, Some(owner));
|
||||||
|
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nostr_cache_alone_is_tooling_only() {
|
||||||
|
let (_dir, path) = init_repo();
|
||||||
|
std::fs::write(path.join(".git/nostr-cache.lmdb"), b"cache").expect("write");
|
||||||
|
|
||||||
|
let binding = binding_of(&path).expect("binding");
|
||||||
|
assert_eq!(binding.kind, Nip34Kind::ToolingOnly);
|
||||||
|
assert!(binding.signals.nostr_cache);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grasp_urls_are_recognised_by_shape() {
|
||||||
|
let owner = key();
|
||||||
|
let npub = owner.to_bech32().expect("npub");
|
||||||
|
|
||||||
|
assert!(Repo::is_grasp_url(&format!(
|
||||||
|
"https://gitnostr.com/{npub}/my-repo.git"
|
||||||
|
)));
|
||||||
|
assert!(Repo::is_grasp_url(&format!(
|
||||||
|
"grasp://gitnostr.com/{npub}/my-repo.git"
|
||||||
|
)));
|
||||||
|
|
||||||
|
assert!(!Repo::is_grasp_url("https://gitnostr.com/my-repo.git"));
|
||||||
|
assert!(!Repo::is_grasp_url(
|
||||||
|
"https://gitnostr.com/not-a-pubkey/my-repo.git"
|
||||||
|
));
|
||||||
|
assert!(!Repo::is_grasp_url(&format!(
|
||||||
|
"ssh://gitnostr.com/{npub}/my-repo.git"
|
||||||
|
)));
|
||||||
|
}
|
||||||
@@ -8,43 +8,6 @@ use nostr_connect::client::AuthUrlHandler;
|
|||||||
use nostr_sdk::error::Error as SignerError;
|
use nostr_sdk::error::Error as SignerError;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct UniversalSigner {
|
|
||||||
inner: Arc<RwLock<Arc<dyn InnerSigner>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl UniversalSigner {
|
|
||||||
pub fn new<T>(signer: T) -> Self
|
|
||||||
where
|
|
||||||
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
|
|
||||||
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
|
|
||||||
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
|
|
||||||
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
|
|
||||||
{
|
|
||||||
Self {
|
|
||||||
inner: Arc::new(RwLock::new(Arc::new(InnerSignerImpl(signer)))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn swap_inner<T>(&self, new_signer: T)
|
|
||||||
where
|
|
||||||
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
|
|
||||||
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
|
|
||||||
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
|
|
||||||
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
|
|
||||||
{
|
|
||||||
*self
|
|
||||||
.inner
|
|
||||||
.write()
|
|
||||||
.unwrap_or_else(|error| error.into_inner()) = Arc::new(InnerSignerImpl(new_signer));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A poisoned lock still holds a usable signer, so it is recovered instead of panicking.
|
|
||||||
fn inner(&self) -> Arc<dyn InnerSigner> {
|
|
||||||
Arc::clone(&self.inner.read().unwrap_or_else(|error| error.into_inner()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
trait InnerSigner: fmt::Debug + Send + Sync + 'static {
|
trait InnerSigner: fmt::Debug + Send + Sync + 'static {
|
||||||
fn get_public_key_async(
|
fn get_public_key_async(
|
||||||
&self,
|
&self,
|
||||||
@@ -121,6 +84,43 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct UniversalSigner {
|
||||||
|
inner: Arc<RwLock<Arc<dyn InnerSigner>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UniversalSigner {
|
||||||
|
pub fn new<T>(signer: T) -> Self
|
||||||
|
where
|
||||||
|
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
|
||||||
|
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
|
||||||
|
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
|
||||||
|
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
Self {
|
||||||
|
inner: Arc::new(RwLock::new(Arc::new(InnerSignerImpl(signer)))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn swap_inner<T>(&self, new_signer: T)
|
||||||
|
where
|
||||||
|
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
|
||||||
|
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
|
||||||
|
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
|
||||||
|
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
*self
|
||||||
|
.inner
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(|error| error.into_inner()) = Arc::new(InnerSignerImpl(new_signer));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A poisoned lock still holds a usable signer, so it is recovered instead of panicking.
|
||||||
|
fn inner(&self) -> Arc<dyn InnerSigner> {
|
||||||
|
Arc::clone(&self.inner.read().unwrap_or_else(|error| error.into_inner()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl AsyncGetPublicKey for UniversalSigner {
|
impl AsyncGetPublicKey for UniversalSigner {
|
||||||
type Error = SignerError;
|
type Error = SignerError;
|
||||||
|
|
||||||
|
|||||||
+133
-127
@@ -11,7 +11,7 @@ use nostr::event::IntoEventBuilder;
|
|||||||
use nostr::nips::nip19::Nip19Coordinate;
|
use nostr::nips::nip19::Nip19Coordinate;
|
||||||
use nostr_connect::prelude::*;
|
use nostr_connect::prelude::*;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use signed_core::{Announcement, Filters, RepoAddr, filters};
|
use signed_core::{Announcement, Filters, RepoAddr};
|
||||||
use signed_git::{GitCache, Repo};
|
use signed_git::{GitCache, Repo};
|
||||||
use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update};
|
use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update};
|
||||||
|
|
||||||
@@ -52,6 +52,54 @@ impl BackendEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum UpdateEvent {
|
||||||
|
Profile(PublicKey),
|
||||||
|
Grasp(PublicKey),
|
||||||
|
Repo(Update),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UpdateEvent {
|
||||||
|
async fn next(
|
||||||
|
notifications: &mut (impl futures::Stream<Item = ClientNotification> + Unpin),
|
||||||
|
seen: &mut HashSet<EventId>,
|
||||||
|
) -> Option<Self> {
|
||||||
|
loop {
|
||||||
|
match notifications.next().await {
|
||||||
|
Some(ClientNotification::Message { message, .. }) => {
|
||||||
|
let RelayMessage::Event { event, .. } = *message else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let update = match event.kind {
|
||||||
|
Kind::Metadata => UpdateEvent::Profile(event.pubkey),
|
||||||
|
Kind::GitUserGraspList => UpdateEvent::Grasp(event.pubkey),
|
||||||
|
kind if Filters::is_repo_kind(kind) => {
|
||||||
|
UpdateEvent::Repo(Update::from_event(&event))
|
||||||
|
}
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
|
||||||
|
if seen.insert(event.id) {
|
||||||
|
// Bounded, so a long session does not keep every event id.
|
||||||
|
if seen.len() >= MAX_SEEN_EVENT_IDS {
|
||||||
|
seen.clear();
|
||||||
|
}
|
||||||
|
return Some(update);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(_) => continue,
|
||||||
|
None => return None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventEmitter<BackendEvent> for Backend {}
|
||||||
|
|
||||||
|
struct GlobalBackend(Entity<Backend>);
|
||||||
|
|
||||||
|
impl Global for GlobalBackend {}
|
||||||
|
|
||||||
pub struct Backend {
|
pub struct Backend {
|
||||||
client: Client,
|
client: Client,
|
||||||
signer: UniversalSigner,
|
signer: UniversalSigner,
|
||||||
@@ -61,14 +109,9 @@ pub struct Backend {
|
|||||||
pushing_repos: Entity<HashSet<RepoAddr>>,
|
pushing_repos: Entity<HashSet<RepoAddr>>,
|
||||||
/// Bumped by every explicit identity action, results from an older session are dropped.
|
/// Bumped by every explicit identity action, results from an older session are dropped.
|
||||||
session: u64,
|
session: u64,
|
||||||
|
_pump: Task<Result<(), Error>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct GlobalBackend(Entity<Backend>);
|
|
||||||
|
|
||||||
impl Global for GlobalBackend {}
|
|
||||||
|
|
||||||
impl EventEmitter<BackendEvent> for Backend {}
|
|
||||||
|
|
||||||
impl Backend {
|
impl Backend {
|
||||||
pub fn global(cx: &App) -> Entity<Self> {
|
pub fn global(cx: &App) -> Entity<Self> {
|
||||||
cx.global::<GlobalBackend>().0.clone()
|
cx.global::<GlobalBackend>().0.clone()
|
||||||
@@ -105,7 +148,6 @@ impl Backend {
|
|||||||
|
|
||||||
loop {
|
loop {
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
|
|
||||||
if now >= deadline {
|
if now >= deadline {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -156,8 +198,6 @@ impl Backend {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
pump.detach();
|
|
||||||
|
|
||||||
cx.defer(move |cx| {
|
cx.defer(move |cx| {
|
||||||
weak.update(cx, |this, cx| {
|
weak.update(cx, |this, cx| {
|
||||||
this.restore_session(cx);
|
this.restore_session(cx);
|
||||||
@@ -173,6 +213,7 @@ impl Backend {
|
|||||||
passphrase_required: false,
|
passphrase_required: false,
|
||||||
pushing_repos: cx.new(|_| HashSet::new()),
|
pushing_repos: cx.new(|_| HashSet::new()),
|
||||||
session: 0,
|
session: 0,
|
||||||
|
_pump: pump,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,7 +246,7 @@ impl Backend {
|
|||||||
this.set_signer(keys, session, cx);
|
this.set_signer(keys, session, cx);
|
||||||
})?;
|
})?;
|
||||||
} else if content.starts_with("bunker://") {
|
} else if content.starts_with("bunker://") {
|
||||||
let (base, keys) = extract_master_key(&content)?;
|
let (base, keys) = Self::extract_master_key(&content)?;
|
||||||
let uri = NostrConnectUri::parse(base)?;
|
let uri = NostrConnectUri::parse(base)?;
|
||||||
let signer = NostrConnect::builder(uri, keys)
|
let signer = NostrConnect::builder(uri, keys)
|
||||||
.auth_url_handler(Arc::new(SignedAuthUrlHandler))
|
.auth_url_handler(Arc::new(SignedAuthUrlHandler))
|
||||||
@@ -380,7 +421,7 @@ impl Backend {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let keys = Keys::generate();
|
let keys = Keys::generate();
|
||||||
let credential = with_master_key(&uri_string, &keys);
|
let credential = Self::with_master_key(&uri_string, &keys);
|
||||||
let write = cx.write_credentials(USER_KEYRING, "bunker", credential.as_bytes());
|
let write = cx.write_credentials(USER_KEYRING, "bunker", credential.as_bytes());
|
||||||
let session = self.supersede_session();
|
let session = self.supersede_session();
|
||||||
|
|
||||||
@@ -611,7 +652,7 @@ impl Backend {
|
|||||||
let commit = work.await?;
|
let commit = work.await?;
|
||||||
let commit_sha = Sha1Hash::from_str(&commit).map_err(|_| anyhow!("invalid id"))?;
|
let commit_sha = Sha1Hash::from_str(&commit).map_err(|_| anyhow!("invalid id"))?;
|
||||||
|
|
||||||
let announcement = build_announcement(
|
let announcement = Self::build_announcement(
|
||||||
&repo_id,
|
&repo_id,
|
||||||
&name,
|
&name,
|
||||||
&description,
|
&description,
|
||||||
@@ -641,9 +682,15 @@ impl Backend {
|
|||||||
Ok::<(), Error>(())
|
Ok::<(), Error>(())
|
||||||
};
|
};
|
||||||
|
|
||||||
let event =
|
let event = Self::announce_and_push_or_retract(
|
||||||
announce_and_push_or_retract(&client, &signer, &state, announcement, cx, on_step)
|
&client,
|
||||||
.await?;
|
&signer,
|
||||||
|
&state,
|
||||||
|
announcement,
|
||||||
|
cx,
|
||||||
|
on_step,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let announcement = Announcement::from_event(&event)
|
let announcement = Announcement::from_event(&event)
|
||||||
.ok_or_else(|| anyhow!("failed to parse announcement"))?;
|
.ok_or_else(|| anyhow!("failed to parse announcement"))?;
|
||||||
@@ -723,7 +770,8 @@ impl Backend {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let euc = euc.and_then(|commit: String| Sha1Hash::from_str(&commit).ok());
|
let euc = euc.and_then(|commit: String| Sha1Hash::from_str(&commit).ok());
|
||||||
let ann = build_announcement(&repo_id, &name, &description, &owner, &servers, euc);
|
let ann =
|
||||||
|
Self::build_announcement(&repo_id, &name, &description, &owner, &servers, euc);
|
||||||
|
|
||||||
let on_step = &mut |status: PushStepStatus, cx: &mut AsyncApp| {
|
let on_step = &mut |status: PushStepStatus, cx: &mut AsyncApp| {
|
||||||
this.update(cx, |_, cx| {
|
this.update(cx, |_, cx| {
|
||||||
@@ -736,7 +784,8 @@ impl Backend {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let event =
|
let event =
|
||||||
announce_and_push_or_retract(&client, &signer, &state, ann, cx, on_step).await?;
|
Self::announce_and_push_or_retract(&client, &signer, &state, ann, cx, on_step)
|
||||||
|
.await?;
|
||||||
|
|
||||||
if let Some(base) = servers.first().and_then(grasp_base_url) {
|
if let Some(base) = servers.first().and_then(grasp_base_url) {
|
||||||
let url = format!("{base}/{owner}/{repo_id}.git");
|
let url = format!("{base}/{owner}/{repo_id}.git");
|
||||||
@@ -1296,7 +1345,6 @@ impl Backend {
|
|||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
cx.emit(BackendEvent::Synced);
|
cx.emit(BackendEvent::Synced);
|
||||||
cx.notify();
|
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -1336,124 +1384,82 @@ impl Backend {
|
|||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fn build_announcement(
|
fn build_announcement(
|
||||||
repo_id: &str,
|
repo_id: &str,
|
||||||
name: &str,
|
name: &str,
|
||||||
description: &str,
|
description: &str,
|
||||||
owner: &str,
|
owner: &str,
|
||||||
servers: &[RelayUrl],
|
servers: &[RelayUrl],
|
||||||
euc: Option<Sha1Hash>,
|
euc: Option<Sha1Hash>,
|
||||||
) -> GitRepositoryAnnouncement {
|
) -> GitRepositoryAnnouncement {
|
||||||
GitRepositoryAnnouncement {
|
GitRepositoryAnnouncement {
|
||||||
id: repo_id.to_owned(),
|
id: repo_id.to_owned(),
|
||||||
name: Some(name.to_owned()),
|
name: Some(name.to_owned()),
|
||||||
description: (!description.is_empty()).then(|| description.to_owned()),
|
description: (!description.is_empty()).then(|| description.to_owned()),
|
||||||
web: Vec::new(),
|
web: Vec::new(),
|
||||||
clone: servers
|
clone: servers
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|relay| grasp_clone_url(relay, owner, repo_id))
|
.filter_map(|relay| grasp_clone_url(relay, owner, repo_id))
|
||||||
.collect(),
|
.collect(),
|
||||||
relays: servers.to_vec(),
|
relays: servers.to_vec(),
|
||||||
euc,
|
euc,
|
||||||
maintainers: Vec::new(),
|
maintainers: Vec::new(),
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Announces a repository and pushes its state to grasp, retracting the announcement on failure.
|
|
||||||
async fn announce_and_push_or_retract<S, P>(
|
|
||||||
client: &Client,
|
|
||||||
signer: &S,
|
|
||||||
state: &SyncState,
|
|
||||||
announcement: GitRepositoryAnnouncement,
|
|
||||||
cx: &mut AsyncApp,
|
|
||||||
on_step: &mut P,
|
|
||||||
) -> Result<Event, Error>
|
|
||||||
where
|
|
||||||
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
|
||||||
P: FnMut(PushStepStatus, &mut AsyncApp) -> Result<(), Error>,
|
|
||||||
{
|
|
||||||
let state_event = state
|
|
||||||
.state_event(&announcement.id)
|
|
||||||
.finalize_async(signer)
|
|
||||||
.await?;
|
|
||||||
let announcement_event = announcement.finalize_async(signer).await?;
|
|
||||||
|
|
||||||
match state
|
|
||||||
.announce_and_push(client, announcement_event.clone(), state_event, cx, on_step)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(event) => Ok(event),
|
|
||||||
Err(e) => {
|
|
||||||
let retracted =
|
|
||||||
SyncState::retract_announcement(client, signer, announcement_event.id).await;
|
|
||||||
let retraction = match retracted {
|
|
||||||
Ok(()) => "The announcement has been retracted".to_owned(),
|
|
||||||
Err(error) => format!(
|
|
||||||
"Retracting the announcement failed: {error}; delete the repository to clean it up"
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
bail!("{e}. {retraction}");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
enum UpdateEvent {
|
/// Announces a repository and pushes its state to grasp, retracting the announcement on failure.
|
||||||
Profile(PublicKey),
|
async fn announce_and_push_or_retract<S, P>(
|
||||||
Grasp(PublicKey),
|
client: &Client,
|
||||||
Repo(Update),
|
signer: &S,
|
||||||
}
|
state: &SyncState,
|
||||||
|
announcement: GitRepositoryAnnouncement,
|
||||||
|
cx: &mut AsyncApp,
|
||||||
|
on_step: &mut P,
|
||||||
|
) -> Result<Event, Error>
|
||||||
|
where
|
||||||
|
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
||||||
|
P: FnMut(PushStepStatus, &mut AsyncApp) -> Result<(), Error>,
|
||||||
|
{
|
||||||
|
let state_event = state
|
||||||
|
.state_event(&announcement.id)
|
||||||
|
.finalize_async(signer)
|
||||||
|
.await?;
|
||||||
|
let announcement_event = announcement.finalize_async(signer).await?;
|
||||||
|
|
||||||
impl UpdateEvent {
|
match state
|
||||||
async fn next(
|
.announce_and_push(client, announcement_event.clone(), state_event, cx, on_step)
|
||||||
notifications: &mut (impl futures::Stream<Item = ClientNotification> + Unpin),
|
.await
|
||||||
seen: &mut HashSet<EventId>,
|
{
|
||||||
) -> Option<Self> {
|
Ok(event) => Ok(event),
|
||||||
loop {
|
Err(e) => {
|
||||||
match notifications.next().await {
|
let retracted =
|
||||||
Some(ClientNotification::Message { message, .. }) => {
|
SyncState::retract_announcement(client, signer, announcement_event.id).await;
|
||||||
let RelayMessage::Event { event, .. } = *message else {
|
let retraction = match retracted {
|
||||||
continue;
|
Ok(()) => "The announcement has been retracted".to_owned(),
|
||||||
};
|
Err(error) => format!(
|
||||||
|
"Retracting the announcement failed: {error}; delete the repository to clean it up"
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
let update = match event.kind {
|
bail!("{e}. {retraction}");
|
||||||
Kind::Metadata => UpdateEvent::Profile(event.pubkey),
|
|
||||||
Kind::GitUserGraspList => UpdateEvent::Grasp(event.pubkey),
|
|
||||||
kind if filters::is_repo_kind(kind) => {
|
|
||||||
UpdateEvent::Repo(Update::from_event(&event))
|
|
||||||
}
|
|
||||||
_ => continue,
|
|
||||||
};
|
|
||||||
|
|
||||||
if seen.insert(event.id) {
|
|
||||||
// Bounded, so a long session does not keep every event id.
|
|
||||||
if seen.len() >= MAX_SEEN_EVENT_IDS {
|
|
||||||
seen.clear();
|
|
||||||
}
|
|
||||||
return Some(update);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(_) => continue,
|
|
||||||
None => return None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fn extract_master_key(credential: &str) -> Result<(&str, Keys), Error> {
|
fn extract_master_key(credential: &str) -> Result<(&str, Keys), Error> {
|
||||||
match credential.split_once("master=") {
|
match credential.split_once("master=") {
|
||||||
Some((base, nsec)) => {
|
Some((base, nsec)) => {
|
||||||
let keys = Keys::new(SecretKey::parse(nsec)?);
|
let keys = Keys::new(SecretKey::parse(nsec)?);
|
||||||
Ok((base.trim_end_matches(['?', '&']), keys))
|
Ok((base.trim_end_matches(['?', '&']), keys))
|
||||||
|
}
|
||||||
|
None => Ok((credential, Keys::generate())),
|
||||||
}
|
}
|
||||||
None => Ok((credential, Keys::generate())),
|
}
|
||||||
|
|
||||||
|
fn with_master_key(uri: &str, keys: &Keys) -> String {
|
||||||
|
let separator = if uri.contains('?') { '&' } else { '?' };
|
||||||
|
let nsec = keys.secret_key().to_bech32().expect("infallible");
|
||||||
|
format!("{uri}{separator}master={nsec}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_master_key(uri: &str, keys: &Keys) -> String {
|
|
||||||
let separator = if uri.contains('?') { '&' } else { '?' };
|
|
||||||
let nsec = keys.secret_key().to_bech32().expect("infallible");
|
|
||||||
format!("{uri}{separator}master={nsec}")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::HashMap;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::PathBuf;
|
||||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use gpui::{App, AppContext, Context, Entity, Global, Subscription};
|
use gpui::{App, AppContext, Context, Entity, Global, Subscription};
|
||||||
use nostr::prelude::*;
|
|
||||||
use settings::{CheckoutRecord, CheckoutsSettings, SettingsStore};
|
use settings::{CheckoutRecord, CheckoutsSettings, SettingsStore};
|
||||||
use signed_core::{Announcement, RepoAddr};
|
use signed_core::{Announcement, RepoAddr};
|
||||||
use signed_git::Repo;
|
use signed_git::Repo;
|
||||||
@@ -17,28 +16,11 @@ use crate::refresh::{RefreshGate, RefreshRequest};
|
|||||||
use crate::repos::RepoListStore;
|
use crate::repos::RepoListStore;
|
||||||
|
|
||||||
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
|
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
|
||||||
const MAX_STATUS_CHECKOUTS: usize = 8;
|
|
||||||
const LOCAL_POLL: Duration = Duration::from_secs(2);
|
|
||||||
const STATUS_POLL: Duration = Duration::from_secs(15);
|
|
||||||
const PUSH_POLL: Duration = Duration::from_secs(60);
|
|
||||||
|
|
||||||
struct GlobalCheckoutsStore(Entity<CheckoutsStore>);
|
struct GlobalCheckoutsStore(Entity<CheckoutsStore>);
|
||||||
|
|
||||||
impl Global for GlobalCheckoutsStore {}
|
impl Global for GlobalCheckoutsStore {}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct CheckoutStatus {
|
|
||||||
pub path: PathBuf,
|
|
||||||
/// A detached checkout is idle and yields no status.
|
|
||||||
pub branch: String,
|
|
||||||
/// For tip-based PR dedupe.
|
|
||||||
pub head: String,
|
|
||||||
/// `refs/remotes/origin/<branch>`, else `origin/HEAD` for new branches.
|
|
||||||
pub base: String,
|
|
||||||
/// Zero-ahead checkouts are dropped, so always above zero.
|
|
||||||
pub ahead: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Remembered {
|
struct Remembered {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
addr: RepoAddr,
|
addr: RepoAddr,
|
||||||
@@ -94,15 +76,8 @@ impl Remembered {
|
|||||||
|
|
||||||
pub struct CheckoutsStore {
|
pub struct CheckoutsStore {
|
||||||
by_repo: HashMap<RepoAddr, Vec<PathBuf>>,
|
by_repo: HashMap<RepoAddr, Vec<PathBuf>>,
|
||||||
statuses: HashMap<RepoAddr, Vec<CheckoutStatus>>,
|
|
||||||
status_requested: HashSet<RepoAddr>,
|
|
||||||
push_requested: HashSet<RepoAddr>,
|
|
||||||
push_statuses: HashMap<RepoAddr, Vec<CheckoutStatus>>,
|
|
||||||
requested_head: HashMap<RepoAddr, Option<String>>,
|
|
||||||
refresh: RefreshGate,
|
refresh: RefreshGate,
|
||||||
debounce_pending: bool,
|
debounce_pending: bool,
|
||||||
local_pending: bool,
|
|
||||||
last_full_sync: Option<Instant>,
|
|
||||||
checkouts_settings: CheckoutsSettings,
|
checkouts_settings: CheckoutsSettings,
|
||||||
_subscriptions: Vec<Subscription>,
|
_subscriptions: Vec<Subscription>,
|
||||||
}
|
}
|
||||||
@@ -146,15 +121,14 @@ impl CheckoutsStore {
|
|||||||
this.refresh(cx);
|
this.refresh(cx);
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Another identity's repositories must not keep the old statuses alive.
|
// Another identity's repositories must not keep the old associations alive.
|
||||||
subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| {
|
subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| {
|
||||||
if matches!(event, BackendEvent::SignerChanged) {
|
if matches!(event, BackendEvent::SignerChanged) {
|
||||||
this.status_requested.clear();
|
let had_state = !this.by_repo.is_empty();
|
||||||
this.push_requested.clear();
|
this.by_repo.clear();
|
||||||
this.requested_head.clear();
|
if had_state {
|
||||||
this.statuses.clear();
|
cx.notify();
|
||||||
this.push_statuses.clear();
|
}
|
||||||
cx.notify();
|
|
||||||
|
|
||||||
this.refresh(cx);
|
this.refresh(cx);
|
||||||
}
|
}
|
||||||
@@ -173,15 +147,8 @@ impl CheckoutsStore {
|
|||||||
|
|
||||||
Self {
|
Self {
|
||||||
by_repo: HashMap::new(),
|
by_repo: HashMap::new(),
|
||||||
statuses: HashMap::new(),
|
|
||||||
status_requested: HashSet::new(),
|
|
||||||
push_requested: HashSet::new(),
|
|
||||||
push_statuses: HashMap::new(),
|
|
||||||
requested_head: HashMap::new(),
|
|
||||||
refresh: RefreshGate::default(),
|
refresh: RefreshGate::default(),
|
||||||
debounce_pending: false,
|
debounce_pending: false,
|
||||||
local_pending: false,
|
|
||||||
last_full_sync: None,
|
|
||||||
checkouts_settings,
|
checkouts_settings,
|
||||||
_subscriptions: subscriptions,
|
_subscriptions: subscriptions,
|
||||||
}
|
}
|
||||||
@@ -221,60 +188,7 @@ impl CheckoutsStore {
|
|||||||
self.by_repo.get(addr).cloned().unwrap_or_default()
|
self.by_repo.get(addr).cloned().unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn request_statuses(
|
fn refresh(&mut self, cx: &mut Context<Self>) {
|
||||||
&mut self,
|
|
||||||
addr: &RepoAddr,
|
|
||||||
announced_head: Option<String>,
|
|
||||||
cx: &mut Context<Self>,
|
|
||||||
) {
|
|
||||||
self.status_requested.insert(addr.clone());
|
|
||||||
if announced_head != self.requested_head.get(addr).cloned().flatten() {
|
|
||||||
self.requested_head.insert(addr.clone(), announced_head);
|
|
||||||
}
|
|
||||||
self.refresh(cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn ready_statuses_of(&self, addr: &RepoAddr) -> Vec<CheckoutStatus> {
|
|
||||||
self.statuses.get(addr).cloned().unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn request_push_statuses(&mut self, addr: &RepoAddr, cx: &mut Context<Self>) {
|
|
||||||
self.push_requested.insert(addr.clone());
|
|
||||||
self.refresh(cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn checkout_pushed(&mut self, addr: &RepoAddr, path: &Path, cx: &mut Context<Self>) {
|
|
||||||
let mut removed = false;
|
|
||||||
|
|
||||||
if let Some(statuses) = self.push_statuses.get_mut(addr) {
|
|
||||||
let before = statuses.len();
|
|
||||||
statuses.retain(|status| status.path.as_path() != path);
|
|
||||||
removed = statuses.len() != before;
|
|
||||||
|
|
||||||
if removed && statuses.is_empty() {
|
|
||||||
self.push_statuses.remove(addr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if removed {
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
self.request_push_statuses(addr, cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn push_statuses_of(&self, addr: &RepoAddr) -> Vec<CheckoutStatus> {
|
|
||||||
self.push_statuses.get(addr).cloned().unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn unpushed(&self, addr: &RepoAddr) -> usize {
|
|
||||||
self.push_statuses
|
|
||||||
.get(addr)
|
|
||||||
.map(|list| list.iter().map(|status| status.ahead as usize).sum())
|
|
||||||
.unwrap_or(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh(&mut self, cx: &mut Context<Self>) {
|
|
||||||
if self.debounce_pending || self.refresh.request() != RefreshRequest::Schedule {
|
if self.debounce_pending || self.refresh.request() != RefreshRequest::Schedule {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -315,26 +229,11 @@ impl CheckoutsStore {
|
|||||||
let scanned = LocalReposStore::global(cx).read(cx).repos.clone();
|
let scanned = LocalReposStore::global(cx).read(cx).repos.clone();
|
||||||
let cache_root = Mirrors::root().canonicalize().ok();
|
let cache_root = Mirrors::root().canonicalize().ok();
|
||||||
|
|
||||||
let requested: Vec<(RepoAddr, Option<String>)> = self
|
|
||||||
.status_requested
|
|
||||||
.iter()
|
|
||||||
.map(|addr| {
|
|
||||||
(
|
|
||||||
addr.clone(),
|
|
||||||
self.requested_head.get(addr).cloned().flatten(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let push_requested: Vec<RepoAddr> = self.push_requested.iter().cloned().collect();
|
|
||||||
let poll = !self.status_requested.is_empty() || !self.push_requested.is_empty();
|
|
||||||
|
|
||||||
let work = cx.background_spawn(async move {
|
let work = cx.background_spawn(async move {
|
||||||
let mut facts: Vec<(PathBuf, Option<String>, Option<String>)> = Vec::new();
|
let mut facts = Vec::new();
|
||||||
for scanned in scanned.iter() {
|
for scanned in scanned.iter() {
|
||||||
let path = &scanned.path;
|
let path = &scanned.path;
|
||||||
|
|
||||||
// The browser's mirror clones are not user checkouts.
|
|
||||||
if cache_root
|
if cache_root
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.is_some_and(|root| path.starts_with(root))
|
.is_some_and(|root| path.starts_with(root))
|
||||||
@@ -342,15 +241,13 @@ impl CheckoutsStore {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let origin = Repo::open(path)
|
let (origin, root) = match Repo::open(path) {
|
||||||
.and_then(|repo| repo.origin_url())
|
Ok(repo) => (
|
||||||
.ok()
|
repo.origin_url().ok().flatten(),
|
||||||
.flatten();
|
repo.root_commit().ok().flatten(),
|
||||||
|
),
|
||||||
let root = Repo::open(path)
|
Err(_) => (None, None),
|
||||||
.and_then(|repo| repo.root_commit())
|
};
|
||||||
.ok()
|
|
||||||
.flatten();
|
|
||||||
|
|
||||||
facts.push((path.clone(), origin, root));
|
facts.push((path.clone(), origin, root));
|
||||||
}
|
}
|
||||||
@@ -358,283 +255,31 @@ impl CheckoutsStore {
|
|||||||
let associations =
|
let associations =
|
||||||
Remembered::resolve_associations(&remembered, &facts, announcements.iter());
|
Remembered::resolve_associations(&remembered, &facts, announcements.iter());
|
||||||
|
|
||||||
let associations: HashMap<RepoAddr, Vec<PathBuf>> = associations
|
associations
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(addr, paths)| (addr, paths.into_iter().filter(|p| p.is_dir()).collect()))
|
.map(|(addr, paths)| (addr, paths.into_iter().filter(|p| p.is_dir()).collect()))
|
||||||
.collect();
|
.collect::<HashMap<RepoAddr, Vec<PathBuf>>>()
|
||||||
|
|
||||||
let (statuses, push_statuses) =
|
|
||||||
CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, true);
|
|
||||||
|
|
||||||
(associations, statuses, push_statuses)
|
|
||||||
});
|
});
|
||||||
|
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
let (associations, statuses, push_statuses) = work.await;
|
let associations = work.await;
|
||||||
|
|
||||||
let again = this.update(cx, |this, cx| {
|
let again = this.update(cx, |this, cx| {
|
||||||
let associations_changed = this.by_repo != associations;
|
let changed = this.by_repo != associations;
|
||||||
let statuses_changed = this.statuses != statuses;
|
|
||||||
let push_statuses_changed = this.push_statuses != push_statuses;
|
|
||||||
|
|
||||||
this.by_repo = associations;
|
this.by_repo = associations;
|
||||||
this.statuses = statuses;
|
|
||||||
this.push_statuses = push_statuses;
|
|
||||||
|
|
||||||
// Notify only when something actually changed.
|
if changed {
|
||||||
if associations_changed || statuses_changed || push_statuses_changed {
|
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
this.last_full_sync = Some(Instant::now());
|
|
||||||
this.refresh.finish()
|
this.refresh.finish()
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
if again {
|
if again {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| this.refresh(cx))?;
|
||||||
this.refresh(cx);
|
|
||||||
})?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
if poll {
|
|
||||||
this.schedule_local_pass(cx);
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok::<(), Error>(())
|
Ok::<(), Error>(())
|
||||||
})
|
})
|
||||||
.detach();
|
.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn schedule_local_pass(&mut self, cx: &mut Context<Self>) {
|
|
||||||
if self.local_pending {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.local_pending = true;
|
|
||||||
|
|
||||||
cx.spawn(async move |this, cx| {
|
|
||||||
cx.background_executor().timer(LOCAL_POLL).await;
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.local_pending = false;
|
|
||||||
this.local_tick(cx);
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.detach();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn local_tick(&mut self, cx: &mut Context<Self>) {
|
|
||||||
if self.status_requested.is_empty() && self.push_requested.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.refresh.running() || self.debounce_pending {
|
|
||||||
self.schedule_local_pass(cx);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let cadence = if self.status_requested.is_empty() {
|
|
||||||
PUSH_POLL
|
|
||||||
} else {
|
|
||||||
STATUS_POLL
|
|
||||||
};
|
|
||||||
|
|
||||||
let full_due = self
|
|
||||||
.last_full_sync
|
|
||||||
.is_none_or(|sync| sync.elapsed() >= cadence);
|
|
||||||
|
|
||||||
if full_due {
|
|
||||||
self.last_full_sync = Some(Instant::now());
|
|
||||||
self.refresh(cx);
|
|
||||||
} else {
|
|
||||||
self.run_local_statuses(cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
self.schedule_local_pass(cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_local_statuses(&mut self, cx: &mut Context<Self>) {
|
|
||||||
let associations = self.by_repo.clone();
|
|
||||||
|
|
||||||
let requested: Vec<(RepoAddr, Option<String>)> = self
|
|
||||||
.status_requested
|
|
||||||
.iter()
|
|
||||||
.map(|addr| {
|
|
||||||
(
|
|
||||||
addr.clone(),
|
|
||||||
self.requested_head.get(addr).cloned().flatten(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let push_requested: Vec<RepoAddr> = self.push_requested.iter().cloned().collect();
|
|
||||||
|
|
||||||
let work = cx.background_spawn(async move {
|
|
||||||
CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, false)
|
|
||||||
});
|
|
||||||
|
|
||||||
cx.spawn(async move |this, cx| {
|
|
||||||
let (statuses, push_statuses) = work.await;
|
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
if this.refresh.running() || this.debounce_pending {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let statuses_changed = this.statuses != statuses;
|
|
||||||
let push_statuses_changed = this.push_statuses != push_statuses;
|
|
||||||
|
|
||||||
this.statuses = statuses;
|
|
||||||
this.push_statuses = push_statuses;
|
|
||||||
|
|
||||||
if statuses_changed || push_statuses_changed {
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok::<(), anyhow::Error>(())
|
|
||||||
})
|
|
||||||
.detach();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn checkout_status(path: &Path, announced_head: Option<&str>) -> Option<CheckoutStatus> {
|
|
||||||
let repo = Repo::try_open(path)?;
|
|
||||||
let branches = repo.branches().ok()?;
|
|
||||||
|
|
||||||
if branches.is_empty() || repo.is_dirty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let branch = repo.current_branch()?;
|
|
||||||
let head = repo.head()?;
|
|
||||||
let base = announced_head
|
|
||||||
.filter(|name| branches.iter().any(|b| b == name))
|
|
||||||
.map(str::to_owned)
|
|
||||||
.or_else(|| branches.iter().find(|b| *b == "main").cloned())
|
|
||||||
.or_else(|| branches.first().cloned())?;
|
|
||||||
|
|
||||||
if base == branch {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let ahead = repo.commits_ahead(&base, &branch);
|
|
||||||
(ahead > 0).then_some(CheckoutStatus {
|
|
||||||
path: path.to_path_buf(),
|
|
||||||
branch,
|
|
||||||
head,
|
|
||||||
base,
|
|
||||||
ahead,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns checkouts that are ahead of their remote tracking branch.
|
|
||||||
fn checkout_push_status(path: &Path, fetch: bool) -> Option<CheckoutStatus> {
|
|
||||||
let repo = Repo::try_open(path)?;
|
|
||||||
if repo.is_dirty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let branch = repo.current_branch()?;
|
|
||||||
let head = repo.head()?;
|
|
||||||
let origin = repo.origin_url().ok().flatten()?;
|
|
||||||
|
|
||||||
if fetch && let Err(e) = repo.fetch_refs(&[origin], "+refs/heads/*:refs/remotes/origin/*") {
|
|
||||||
log::warn!("failed to fetch refs for {path:?}: {e}");
|
|
||||||
}
|
|
||||||
|
|
||||||
let remote = format!("refs/remotes/origin/{branch}");
|
|
||||||
|
|
||||||
// If the branch is new and has no remote tracking branch, fall back to origin/HEAD.
|
|
||||||
let base = if repo.ref_exists(&remote) {
|
|
||||||
remote
|
|
||||||
} else if repo.ref_exists("refs/remotes/origin/HEAD") {
|
|
||||||
"refs/remotes/origin/HEAD".to_owned()
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
|
|
||||||
let ahead = repo.commits_ahead(&base, &branch);
|
|
||||||
|
|
||||||
(ahead > 0).then_some(CheckoutStatus {
|
|
||||||
path: path.to_path_buf(),
|
|
||||||
branch,
|
|
||||||
head,
|
|
||||||
base,
|
|
||||||
ahead,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn compute_statuses(
|
|
||||||
associations: &HashMap<RepoAddr, Vec<PathBuf>>,
|
|
||||||
requested: &[(RepoAddr, Option<String>)],
|
|
||||||
push_requested: &[RepoAddr],
|
|
||||||
fetch: bool,
|
|
||||||
) -> (
|
|
||||||
HashMap<RepoAddr, Vec<CheckoutStatus>>,
|
|
||||||
HashMap<RepoAddr, Vec<CheckoutStatus>>,
|
|
||||||
) {
|
|
||||||
let mut statuses: HashMap<RepoAddr, Vec<CheckoutStatus>> = HashMap::new();
|
|
||||||
for (addr, announced_head) in requested {
|
|
||||||
let Some(paths) = associations.get(addr) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
let list: Vec<CheckoutStatus> = paths
|
|
||||||
.iter()
|
|
||||||
.take(MAX_STATUS_CHECKOUTS)
|
|
||||||
.filter_map(|path| Self::checkout_status(path, announced_head.as_deref()))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
if !list.is_empty() {
|
|
||||||
statuses.insert(addr.clone(), list);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut push_statuses: HashMap<RepoAddr, Vec<CheckoutStatus>> = HashMap::new();
|
|
||||||
for addr in push_requested {
|
|
||||||
let Some(paths) = associations.get(addr) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
let list: Vec<CheckoutStatus> = paths
|
|
||||||
.iter()
|
|
||||||
.take(MAX_STATUS_CHECKOUTS)
|
|
||||||
.filter_map(|path| Self::checkout_push_status(path, fetch))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
if !list.is_empty() {
|
|
||||||
push_statuses.insert(addr.clone(), list);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
(statuses, push_statuses)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn pr_proposes_checkout(
|
|
||||||
pr: &Event,
|
|
||||||
open: bool,
|
|
||||||
user: PublicKey,
|
|
||||||
checkout: &CheckoutStatus,
|
|
||||||
) -> bool {
|
|
||||||
if pr.kind != Kind::GitPullRequest || !open || pr.pubkey != user {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let branch_matches = pr
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.find(|t| t.kind() == "branch-name")
|
|
||||||
.and_then(|t| t.content())
|
|
||||||
.is_some_and(|name| name == checkout.branch);
|
|
||||||
|
|
||||||
// A renamed branch falls back to the proposed tip commit.
|
|
||||||
let tip_matches = pr
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.find(|t| t.kind() == "c")
|
|
||||||
.and_then(|t| t.content())
|
|
||||||
.is_some_and(|tip| tip == checkout.head);
|
|
||||||
|
|
||||||
branch_matches || tip_matches
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,14 +33,18 @@ impl Inbox {
|
|||||||
self.loaded = false;
|
self.loaded = false;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
|
|
||||||
let backend = Backend::global(cx);
|
let backend = Backend::global(cx).downgrade();
|
||||||
let work = cx.background_spawn(async move { Self::load_state(&client, me).await });
|
let work = cx.background_spawn(async move { Self::load_state(&client, me).await });
|
||||||
|
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
let loaded = work.await;
|
let loaded = work.await;
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
if backend.read(cx).current_user() != Some(me) {
|
let matches = backend
|
||||||
|
.read_with(cx, |backend, _| backend.current_user() == Some(me))
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
if !matches {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,9 +64,13 @@ impl Inbox {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn reset(&mut self, cx: &mut Context<Self>) {
|
pub(crate) fn reset(&mut self, cx: &mut Context<Self>) {
|
||||||
|
let changed = self.loaded || self.state != InboxReadState::default();
|
||||||
self.state = InboxReadState::default();
|
self.state = InboxReadState::default();
|
||||||
self.loaded = false;
|
self.loaded = false;
|
||||||
cx.notify();
|
|
||||||
|
if changed {
|
||||||
|
cx.notify();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn persist(&mut self, cx: &mut Context<Self>) {
|
fn persist(&mut self, cx: &mut Context<Self>) {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ use std::path::{Path, PathBuf};
|
|||||||
|
|
||||||
pub use backend::{Backend, BackendEvent};
|
pub use backend::{Backend, BackendEvent};
|
||||||
pub use bootstrap::{sync_bootstrap_only, user_grasp_list_servers};
|
pub use bootstrap::{sync_bootstrap_only, user_grasp_list_servers};
|
||||||
pub use checkouts::{CheckoutStatus, CheckoutsStore};
|
pub use checkouts::CheckoutsStore;
|
||||||
pub use git_store::Mirrors;
|
pub use git_store::Mirrors;
|
||||||
use gpui::{App, AppContext};
|
use gpui::{App, AppContext};
|
||||||
pub use inbox::Inbox;
|
pub use inbox::Inbox;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
|||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use gpui::{App, AppContext, Context, Entity, Global, SharedString, Task};
|
use gpui::{App, AppContext, Context, Entity, Global, SharedString, Task};
|
||||||
use signed_core::{Announcement, RepoAddr};
|
use signed_core::{Announcement, RepoAddr};
|
||||||
use signed_git::{LocalRepo, Nip34Binding, find_git_repos};
|
use signed_git::{LocalRepo, Nip34Binding};
|
||||||
|
|
||||||
struct GlobalLocalReposStore(Entity<LocalReposStore>);
|
struct GlobalLocalReposStore(Entity<LocalReposStore>);
|
||||||
|
|
||||||
@@ -44,13 +44,19 @@ impl LocalReposStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove(&mut self, path: &Path, cx: &mut Context<Self>) {
|
pub fn remove(&mut self, path: &Path, cx: &mut Context<Self>) {
|
||||||
self.repos = Arc::new(
|
let Some(index) = self
|
||||||
self.repos
|
.repos
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|repo| repo.path.as_path() != path)
|
.position(|repo| repo.path.as_path() == path)
|
||||||
.cloned()
|
else {
|
||||||
.collect(),
|
return;
|
||||||
);
|
};
|
||||||
|
|
||||||
|
let mut repos = (*self.repos).clone();
|
||||||
|
repos.remove(index);
|
||||||
|
|
||||||
|
self.repos = Arc::new(repos);
|
||||||
|
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +78,7 @@ impl LocalReposStore {
|
|||||||
let work = cx.background_spawn(async move {
|
let work = cx.background_spawn(async move {
|
||||||
let mut repos = Vec::new();
|
let mut repos = Vec::new();
|
||||||
for root in roots.iter() {
|
for root in roots.iter() {
|
||||||
repos.extend(find_git_repos(root));
|
repos.extend(LocalRepo::find_all(root));
|
||||||
}
|
}
|
||||||
repos.sort_by(|a, b| a.path.cmp(&b.path));
|
repos.sort_by(|a, b| a.path.cmp(&b.path));
|
||||||
repos.dedup_by(|a, b| a.path == b.path);
|
repos.dedup_by(|a, b| a.path == b.path);
|
||||||
@@ -101,6 +107,14 @@ impl LocalReposStore {
|
|||||||
task.detach();
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn repo_addr(repo: &LocalRepo) -> Option<RepoAddr> {
|
||||||
|
let binding = repo.nip34.as_ref()?;
|
||||||
|
let owner = binding.owner?;
|
||||||
|
let identifier = binding.identifier.as_deref()?;
|
||||||
|
|
||||||
|
Some(RepoAddr::new(owner, identifier))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn resolve(
|
pub fn resolve(
|
||||||
repos: &[LocalRepo],
|
repos: &[LocalRepo],
|
||||||
known: &[Announcement],
|
known: &[Announcement],
|
||||||
@@ -111,7 +125,7 @@ impl LocalReposStore {
|
|||||||
repos
|
repos
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|repo| {
|
.filter_map(|repo| {
|
||||||
let addr = local_repo_addr(repo);
|
let addr = Self::repo_addr(repo);
|
||||||
|
|
||||||
if let Some(addr) = &addr
|
if let Some(addr) = &addr
|
||||||
&& shown.contains(addr)
|
&& shown.contains(addr)
|
||||||
@@ -153,11 +167,3 @@ impl ResolvedLocalRepo {
|
|||||||
.unwrap_or_else(|| SharedString::from("Untitled"))
|
.unwrap_or_else(|| SharedString::from("Untitled"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn local_repo_addr(repo: &LocalRepo) -> Option<RepoAddr> {
|
|
||||||
let binding = repo.nip34.as_ref()?;
|
|
||||||
let owner = binding.owner?;
|
|
||||||
let identifier = binding.identifier.as_deref()?;
|
|
||||||
|
|
||||||
Some(RepoAddr::new(owner, identifier))
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -30,21 +30,21 @@ impl PatchSeries {
|
|||||||
pub(crate) fn tip_commit(&self) -> Option<Sha1Hash> {
|
pub(crate) fn tip_commit(&self) -> Option<Sha1Hash> {
|
||||||
self.parts
|
self.parts
|
||||||
.last()
|
.last()
|
||||||
.and_then(|part| patch_current_commit(part))
|
.and_then(|part| Self::current_commit(part))
|
||||||
.and_then(|hex| hex.parse::<Sha1Hash>().ok())
|
.and_then(|hex| hex.parse::<Sha1Hash>().ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn commit_of(&self, index: usize) -> Option<&str> {
|
pub(crate) fn commit_of(&self, index: usize) -> Option<&str> {
|
||||||
self.parts
|
self.parts
|
||||||
.get(index)
|
.get(index)
|
||||||
.and_then(|part| patch_current_commit(part))
|
.and_then(|part| Self::current_commit(part))
|
||||||
.filter(|hex| hex.len() == 40)
|
.filter(|hex| hex.len() == 40)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// The `From <commit>` header on the first line.
|
/// The `From <commit>` header on the first line.
|
||||||
fn patch_current_commit(patch: &str) -> Option<&str> {
|
fn current_commit(patch: &str) -> Option<&str> {
|
||||||
let line = patch.lines().next()?;
|
let line = patch.lines().next()?;
|
||||||
let hex = line.strip_prefix("From ")?;
|
let hex = line.strip_prefix("From ")?;
|
||||||
hex.split_whitespace().next().filter(|hex| hex.len() == 40)
|
hex.split_whitespace().next().filter(|hex| hex.len() == 40)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,44 +1,6 @@
|
|||||||
use nostr::prelude::Url;
|
use nostr::prelude::Url;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
|
|
||||||
/// `ws://` grasp servers, like ngit, use `http(s)://<host>`.
|
|
||||||
pub(crate) fn grasp_base_url(relay: &RelayUrl) -> Option<String> {
|
|
||||||
let parsed = Url::parse(relay.as_str()).ok()?;
|
|
||||||
let host = parsed.host_str()?;
|
|
||||||
let port = parsed
|
|
||||||
.port()
|
|
||||||
.map(|port| format!(":{port}"))
|
|
||||||
.unwrap_or_default();
|
|
||||||
let scheme = if relay.scheme().is_secure() {
|
|
||||||
"https"
|
|
||||||
} else {
|
|
||||||
"http"
|
|
||||||
};
|
|
||||||
Some(format!("{scheme}://{host}{port}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn grasp_clone_url(relay: &RelayUrl, owner: &str, repo_id: &str) -> Option<Url> {
|
|
||||||
let base = grasp_base_url(relay)?;
|
|
||||||
Url::parse(&format!("{base}/{owner}/{repo_id}.git")).ok()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// GRASP-06 contributor namespace URL of a pull request tip.
|
|
||||||
pub(crate) fn grasp06_prs_url(base_url: &str, npub: &str, repo_id: &str) -> String {
|
|
||||||
format!("{base_url}/prs/{npub}/{repo_id}.git")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The author's GRASP-06 `/prs/` URLs come first.
|
|
||||||
pub(crate) fn pr_clone_urls(prs_urls: Vec<Url>, base_clone_urls: Vec<Url>) -> Vec<Url> {
|
|
||||||
let mut seen = std::collections::HashSet::new();
|
|
||||||
let mut urls = Vec::new();
|
|
||||||
for url in prs_urls.into_iter().chain(base_clone_urls) {
|
|
||||||
if seen.insert(url.to_string()) {
|
|
||||||
urls.push(url);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
urls
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct GraspServer {
|
pub struct GraspServer {
|
||||||
relay: RelayUrl,
|
relay: RelayUrl,
|
||||||
@@ -112,3 +74,43 @@ impl PushOutcome {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `ws://` grasp servers, like ngit, use `http(s)://<host>`.
|
||||||
|
pub(crate) fn grasp_base_url(relay: &RelayUrl) -> Option<String> {
|
||||||
|
let parsed = Url::parse(relay.as_str()).ok()?;
|
||||||
|
let host = parsed.host_str()?;
|
||||||
|
let port = parsed
|
||||||
|
.port()
|
||||||
|
.map(|port| format!(":{port}"))
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let scheme = if relay.scheme().is_secure() {
|
||||||
|
"https"
|
||||||
|
} else {
|
||||||
|
"http"
|
||||||
|
};
|
||||||
|
|
||||||
|
Some(format!("{scheme}://{host}{port}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn grasp_clone_url(relay: &RelayUrl, owner: &str, repo_id: &str) -> Option<Url> {
|
||||||
|
let base = grasp_base_url(relay)?;
|
||||||
|
Url::parse(&format!("{base}/{owner}/{repo_id}.git")).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GRASP-06 contributor namespace URL of a pull request tip.
|
||||||
|
pub(crate) fn grasp06_prs_url(base_url: &str, npub: &str, repo_id: &str) -> String {
|
||||||
|
format!("{base_url}/prs/{npub}/{repo_id}.git")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The author's GRASP-06 `/prs/` URLs come first.
|
||||||
|
pub(crate) fn pr_clone_urls(prs_urls: Vec<Url>, base_clone_urls: Vec<Url>) -> Vec<Url> {
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
let mut urls = Vec::new();
|
||||||
|
for url in prs_urls.into_iter().chain(base_clone_urls) {
|
||||||
|
if seen.insert(url.to_string()) {
|
||||||
|
urls.push(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
urls
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
#[derive(Debug, Default)]
|
|
||||||
pub struct RefreshGate {
|
|
||||||
running: bool,
|
|
||||||
dirty: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum RefreshRequest {
|
pub enum RefreshRequest {
|
||||||
Schedule,
|
Schedule,
|
||||||
Fold,
|
Fold,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct RefreshGate {
|
||||||
|
running: bool,
|
||||||
|
dirty: bool,
|
||||||
|
}
|
||||||
|
|
||||||
impl RefreshGate {
|
impl RefreshGate {
|
||||||
pub fn running(&self) -> bool {
|
pub fn running(&self) -> bool {
|
||||||
self.running
|
self.running
|
||||||
|
|||||||
+166
-198
@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet};
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use anyhow::{Error, bail};
|
use anyhow::{Error, bail};
|
||||||
use gpui::{App, AppContext, Context, SharedString, Subscription, Task};
|
use gpui::{App, AppContext, Context, Subscription, Task};
|
||||||
use nostr::event::IntoEventBuilder;
|
use nostr::event::IntoEventBuilder;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use settings::{EventFetchingStrategy, SettingsStore};
|
use settings::{EventFetchingStrategy, SettingsStore};
|
||||||
@@ -231,14 +231,6 @@ impl RepoStore {
|
|||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn name(&self) -> SharedString {
|
|
||||||
self.announcement
|
|
||||||
.as_ref()
|
|
||||||
.map_or(SharedString::default(), |a| {
|
|
||||||
SharedString::from(a.name.as_deref().unwrap_or("Unknown"))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn repo_filters(addr: &RepoAddr) -> Vec<Filter> {
|
fn repo_filters(addr: &RepoAddr) -> Vec<Filter> {
|
||||||
let mut filters = vec![
|
let mut filters = vec![
|
||||||
Filter::new()
|
Filter::new()
|
||||||
@@ -446,18 +438,18 @@ impl RepoStore {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
let status_by_root =
|
let status_by_root =
|
||||||
resolve_statuses(&issues, &patches, &pull_requests, &statuses, &maintainers);
|
Self::resolve_statuses(&issues, &patches, &pull_requests, &statuses, &maintainers);
|
||||||
|
|
||||||
let open_issue_count = issues
|
let open_issue_count = issues
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|issue| status_of(&status_by_root, issue) == RepoStatus::Open)
|
.filter(|issue| Self::status_in(&status_by_root, issue) == RepoStatus::Open)
|
||||||
.count();
|
.count();
|
||||||
|
|
||||||
let open_pr_count = pull_requests
|
let open_pr_count = pull_requests
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|pr| {
|
.filter(|pr| {
|
||||||
pr.kind == Kind::GitPullRequest
|
pr.kind == Kind::GitPullRequest
|
||||||
&& status_of(&status_by_root, pr) == RepoStatus::Open
|
&& Self::status_in(&status_by_root, pr) == RepoStatus::Open
|
||||||
})
|
})
|
||||||
.count();
|
.count();
|
||||||
|
|
||||||
@@ -588,7 +580,7 @@ impl RepoStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn status_of(&self, root: &Event) -> RepoStatus {
|
pub fn status_of(&self, root: &Event) -> RepoStatus {
|
||||||
status_of(&self.status_by_root, root)
|
Self::status_in(&self.status_by_root, root)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn issue_count(&self) -> usize {
|
pub fn issue_count(&self) -> usize {
|
||||||
@@ -655,10 +647,10 @@ impl RepoStore {
|
|||||||
.cloned();
|
.cloned();
|
||||||
|
|
||||||
let task = self.publish(
|
let task = self.publish(
|
||||||
comment_builder(root, parent, relay_hint.as_ref(), &addr, content),
|
Self::comment_builder(root, parent, relay_hint.as_ref(), &addr, content),
|
||||||
cx,
|
cx,
|
||||||
);
|
);
|
||||||
self.tasks.push(task);
|
self.track_task(task);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[expect(clippy::too_many_arguments, reason = "mirrors the PR event")]
|
#[expect(clippy::too_many_arguments, reason = "mirrors the PR event")]
|
||||||
@@ -749,7 +741,7 @@ impl RepoStore {
|
|||||||
};
|
};
|
||||||
|
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
let root_patch = match publish_patch_series(
|
let root_patch = match Self::publish_patch_series(
|
||||||
&client,
|
&client,
|
||||||
&signer,
|
&signer,
|
||||||
&addr,
|
&addr,
|
||||||
@@ -985,12 +977,13 @@ impl RepoStore {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// The store owns the publish so it outlives the panel that requested it.
|
// The store owns the publish so it outlives the panel that requested it.
|
||||||
this.tasks.push(cx.spawn(async move |_this, _cx| {
|
let task = cx.spawn(async move |_this, _cx| {
|
||||||
if done.send(publish.await).is_err() {
|
if done.send(publish.await).is_err() {
|
||||||
log::debug!("pull request publish finished after its panel closed");
|
log::debug!("pull request publish finished after its panel closed");
|
||||||
}
|
}
|
||||||
Ok::<(), Error>(())
|
Ok::<(), Error>(())
|
||||||
}));
|
});
|
||||||
|
this.track_task(task);
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
finished
|
finished
|
||||||
@@ -1066,7 +1059,7 @@ impl RepoStore {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
if let Err(e) = publish_patch_series(
|
if let Err(e) = Self::publish_patch_series(
|
||||||
&client,
|
&client,
|
||||||
&signer,
|
&signer,
|
||||||
&addr,
|
&addr,
|
||||||
@@ -1131,7 +1124,7 @@ impl RepoStore {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
self.track_task(task);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_status(&mut self, root: &Event, status: RepoStatus, cx: &mut Context<Self>) {
|
fn set_status(&mut self, root: &Event, status: RepoStatus, cx: &mut Context<Self>) {
|
||||||
@@ -1173,7 +1166,7 @@ impl RepoStore {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
let task = self.publish(builder, cx);
|
let task = self.publish(builder, cx);
|
||||||
self.tasks.push(task);
|
self.track_task(task);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn action_announcement(&self, cx: &App) -> Option<Announcement> {
|
fn action_announcement(&self, cx: &App) -> Option<Announcement> {
|
||||||
@@ -1250,13 +1243,18 @@ impl RepoStore {
|
|||||||
backend.push_checkout_commit(announcement, path.clone(), head, commit, cx)
|
backend.push_checkout_commit(announcement, path.clone(), head, commit, cx)
|
||||||
});
|
});
|
||||||
|
|
||||||
self.run_push(push, Some((addr, path)), cx)
|
self.run_push(push, Some(addr), cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn track_task(&mut self, task: Task<Result<(), Error>>) {
|
||||||
|
self.tasks.retain(|task| !task.is_ready());
|
||||||
|
self.tasks.push(task);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_push(
|
fn run_push(
|
||||||
&mut self,
|
&mut self,
|
||||||
push: Task<Result<PushOutcome, Error>>,
|
push: Task<Result<PushOutcome, Error>>,
|
||||||
pushed_checkout: Option<(RepoAddr, PathBuf)>,
|
pushed_checkout: Option<RepoAddr>,
|
||||||
cx: &mut Context<Self>,
|
cx: &mut Context<Self>,
|
||||||
) -> Task<Result<(), Error>> {
|
) -> Task<Result<(), Error>> {
|
||||||
self.pushing = true;
|
self.pushing = true;
|
||||||
@@ -1283,20 +1281,10 @@ impl RepoStore {
|
|||||||
this.last_error = None;
|
this.last_error = None;
|
||||||
this.last_push_warning = outcome.partial_warning();
|
this.last_push_warning = outcome.partial_warning();
|
||||||
|
|
||||||
if let Some((addr, path)) = &pushed_checkout {
|
|
||||||
let checkouts = CheckoutsStore::global(cx);
|
|
||||||
checkouts.update(cx, |store, cx| {
|
|
||||||
store.checkout_pushed(addr, path, cx);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let sync_status = SyncStatusStore::global(cx);
|
let sync_status = SyncStatusStore::global(cx);
|
||||||
let addr = pushed_checkout
|
let addr = pushed_checkout.clone().or_else(|| this.addr.clone());
|
||||||
.as_ref()
|
|
||||||
.map(|(addr, _)| addr.clone())
|
|
||||||
.or_else(|| this.addr.clone());
|
|
||||||
|
|
||||||
sync_status.read(cx).probe(addr);
|
sync_status.update(cx, |store, _| store.probe(addr));
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
this.last_error = Some(format!("Push failed: {e}"));
|
this.last_error = Some(format!("Push failed: {e}"));
|
||||||
@@ -1458,176 +1446,156 @@ impl RepoStore {
|
|||||||
|
|
||||||
task
|
task
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fn status_of(status_by_root: &HashMap<EventId, RepoStatus>, root: &Event) -> RepoStatus {
|
fn status_in(status_by_root: &HashMap<EventId, RepoStatus>, root: &Event) -> RepoStatus {
|
||||||
status_by_root
|
status_by_root
|
||||||
.get(&root.id)
|
.get(&root.id)
|
||||||
.copied()
|
.copied()
|
||||||
.unwrap_or(RepoStatus::Open)
|
.unwrap_or(RepoStatus::Open)
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_statuses(
|
|
||||||
issues: &[Event],
|
|
||||||
patches: &[Event],
|
|
||||||
pull_requests: &[Event],
|
|
||||||
statuses: &[Event],
|
|
||||||
maintainers: &[PublicKey],
|
|
||||||
) -> HashMap<EventId, RepoStatus> {
|
|
||||||
let mut by_root: HashMap<EventId, Vec<&Event>> = HashMap::new();
|
|
||||||
for event in statuses {
|
|
||||||
for tag in event.tags.iter() {
|
|
||||||
if matches!(tag.kind(), "e" | "E")
|
|
||||||
&& let Some(id) = tag.content().and_then(|hex| EventId::from_hex(hex).ok())
|
|
||||||
{
|
|
||||||
by_root.entry(id).or_default().push(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
issues
|
fn resolve_statuses(
|
||||||
.iter()
|
issues: &[Event],
|
||||||
.chain(patches)
|
patches: &[Event],
|
||||||
.chain(pull_requests)
|
pull_requests: &[Event],
|
||||||
.map(|root| {
|
statuses: &[Event],
|
||||||
let events = by_root.get(&root.id).map(Vec::as_slice).unwrap_or(&[]);
|
maintainers: &[PublicKey],
|
||||||
let status =
|
) -> HashMap<EventId, RepoStatus> {
|
||||||
signed_core::RepoStatus::resolve(events.iter().copied(), &root.pubkey, maintainers);
|
let mut by_root: HashMap<EventId, Vec<&Event>> = HashMap::new();
|
||||||
(root.id, status)
|
for event in statuses {
|
||||||
})
|
for tag in event.tags.iter() {
|
||||||
.collect()
|
if matches!(tag.kind(), "e" | "E")
|
||||||
}
|
&& let Some(id) = tag.content().and_then(|hex| EventId::from_hex(hex).ok())
|
||||||
|
{
|
||||||
|
by_root.entry(id).or_default().push(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Publish a patch series as a sequence of `git/patch` events.
|
issues
|
||||||
#[expect(clippy::too_many_arguments, reason = "independent inputs")]
|
.iter()
|
||||||
async fn publish_patch_series<S>(
|
.chain(patches)
|
||||||
client: &Client,
|
.chain(pull_requests)
|
||||||
signer: &S,
|
.map(|root| {
|
||||||
addr: &RepoAddr,
|
let events = by_root.get(&root.id).map(Vec::as_slice).unwrap_or(&[]);
|
||||||
owner: PublicKey,
|
let status = signed_core::RepoStatus::resolve(
|
||||||
euc: Option<&str>,
|
events.iter().copied(),
|
||||||
series: &PatchSeries,
|
&root.pubkey,
|
||||||
first_marker: &str,
|
maintainers,
|
||||||
reply_to: Option<EventId>,
|
);
|
||||||
) -> Result<Event, Error>
|
(root.id, status)
|
||||||
where
|
})
|
||||||
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
.collect()
|
||||||
{
|
}
|
||||||
let mut root: Option<Event> = None;
|
|
||||||
let mut previous = reply_to;
|
|
||||||
|
|
||||||
for (ix, part) in series.parts.iter().enumerate() {
|
/// Publish a patch series as a sequence of `git/patch` events.
|
||||||
let Some(commit) = series.commit_of(ix) else {
|
#[expect(clippy::too_many_arguments, reason = "independent inputs")]
|
||||||
return Err(anyhow::anyhow!(
|
async fn publish_patch_series<S>(
|
||||||
"patch {} of the series has no `From <commit-id>` header",
|
client: &Client,
|
||||||
ix + 1
|
signer: &S,
|
||||||
));
|
addr: &RepoAddr,
|
||||||
|
owner: PublicKey,
|
||||||
|
euc: Option<&str>,
|
||||||
|
series: &PatchSeries,
|
||||||
|
first_marker: &str,
|
||||||
|
reply_to: Option<EventId>,
|
||||||
|
) -> Result<Event, Error>
|
||||||
|
where
|
||||||
|
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
||||||
|
{
|
||||||
|
let mut root: Option<Event> = None;
|
||||||
|
let mut previous = reply_to;
|
||||||
|
|
||||||
|
for (ix, part) in series.parts.iter().enumerate() {
|
||||||
|
let Some(commit) = series.commit_of(ix) else {
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"patch {} of the series has no `From <commit-id>` header",
|
||||||
|
ix + 1
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut tags = vec![
|
||||||
|
Tag::coordinate(addr.clone().into(), None),
|
||||||
|
Tag::public_key(owner),
|
||||||
|
];
|
||||||
|
|
||||||
|
if ix == 0 {
|
||||||
|
if let Ok(tag) = Tag::parse(["t", first_marker]) {
|
||||||
|
tags.push(tag);
|
||||||
|
}
|
||||||
|
if let Some(root_id) = reply_to
|
||||||
|
&& let Ok(tag) = Tag::parse(["e", &root_id.to_hex(), "", "reply"])
|
||||||
|
{
|
||||||
|
tags.push(tag);
|
||||||
|
}
|
||||||
|
} else if let Some(previous) = previous
|
||||||
|
&& let Ok(tag) = Tag::parse(["e", &previous.to_hex(), "", "reply"])
|
||||||
|
{
|
||||||
|
tags.push(tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(euc) = euc
|
||||||
|
&& let Ok(tag) = Tag::parse(["r", euc])
|
||||||
|
{
|
||||||
|
tags.push(tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(tag) = Tag::parse(["commit", commit]) {
|
||||||
|
tags.push(tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(tag) = Tag::parse(["r", commit]) {
|
||||||
|
tags.push(tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
let builder = EventBuilder::new(Kind::GitPatch)
|
||||||
|
.content(part.clone())
|
||||||
|
.tags(tags);
|
||||||
|
|
||||||
|
let event = builder.finalize_async(signer).await?;
|
||||||
|
let output = client.send_event(&event).broadcast().await?;
|
||||||
|
|
||||||
|
if output.success.is_empty() && !output.failed.is_empty() {
|
||||||
|
let reasons = output
|
||||||
|
.failed
|
||||||
|
.values()
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<String>>()
|
||||||
|
.join(", ");
|
||||||
|
bail!("event not accepted by any relay: {reasons}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if root.is_none() {
|
||||||
|
root = Some(event.clone());
|
||||||
|
}
|
||||||
|
previous = Some(event.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
root.ok_or_else(|| anyhow::anyhow!("patch series is empty"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn comment_builder(
|
||||||
|
root: &Event,
|
||||||
|
parent: Option<&Event>,
|
||||||
|
relay_hint: Option<&RelayUrl>,
|
||||||
|
addr: &RepoAddr,
|
||||||
|
content: String,
|
||||||
|
) -> EventBuilder {
|
||||||
|
let target = |event: &Event| {
|
||||||
|
CommentTarget::event(
|
||||||
|
event.id,
|
||||||
|
event.kind,
|
||||||
|
Some(event.pubkey),
|
||||||
|
relay_hint.cloned().map(Cow::Owned),
|
||||||
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut tags = vec![
|
let root_target = target(root);
|
||||||
Tag::coordinate(addr.clone().into(), None),
|
let parent_target = parent.map(target).unwrap_or_else(|| root_target.clone());
|
||||||
Tag::public_key(owner),
|
|
||||||
];
|
|
||||||
|
|
||||||
if ix == 0 {
|
CommentBuilder::new(content, parent_target)
|
||||||
if let Ok(tag) = Tag::parse(["t", first_marker]) {
|
.root(root_target)
|
||||||
tags.push(tag);
|
.into_event_builder()
|
||||||
}
|
.tags([Tag::coordinate(addr.clone().into(), None)])
|
||||||
if let Some(root_id) = reply_to
|
|
||||||
&& let Ok(tag) = Tag::parse(["e", &root_id.to_hex(), "", "reply"])
|
|
||||||
{
|
|
||||||
tags.push(tag);
|
|
||||||
}
|
|
||||||
} else if let Some(previous) = previous
|
|
||||||
&& let Ok(tag) = Tag::parse(["e", &previous.to_hex(), "", "reply"])
|
|
||||||
{
|
|
||||||
tags.push(tag);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(euc) = euc
|
|
||||||
&& let Ok(tag) = Tag::parse(["r", euc])
|
|
||||||
{
|
|
||||||
tags.push(tag);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(tag) = Tag::parse(["commit", commit]) {
|
|
||||||
tags.push(tag);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(tag) = Tag::parse(["r", commit]) {
|
|
||||||
tags.push(tag);
|
|
||||||
}
|
|
||||||
|
|
||||||
let builder = EventBuilder::new(Kind::GitPatch)
|
|
||||||
.content(part.clone())
|
|
||||||
.tags(tags);
|
|
||||||
|
|
||||||
let event = builder.finalize_async(signer).await?;
|
|
||||||
let output = client.send_event(&event).broadcast().await?;
|
|
||||||
|
|
||||||
if output.success.is_empty() && !output.failed.is_empty() {
|
|
||||||
let reasons = output
|
|
||||||
.failed
|
|
||||||
.values()
|
|
||||||
.cloned()
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ");
|
|
||||||
bail!("event not accepted by any relay: {reasons}");
|
|
||||||
}
|
|
||||||
|
|
||||||
if root.is_none() {
|
|
||||||
root = Some(event.clone());
|
|
||||||
}
|
|
||||||
previous = Some(event.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
root.ok_or_else(|| anyhow::anyhow!("patch series is empty"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn comment_builder(
|
|
||||||
root: &Event,
|
|
||||||
parent: Option<&Event>,
|
|
||||||
relay_hint: Option<&RelayUrl>,
|
|
||||||
addr: &RepoAddr,
|
|
||||||
content: String,
|
|
||||||
) -> EventBuilder {
|
|
||||||
let target = |event: &Event| {
|
|
||||||
CommentTarget::event(
|
|
||||||
event.id,
|
|
||||||
event.kind,
|
|
||||||
Some(event.pubkey),
|
|
||||||
relay_hint.cloned().map(Cow::Owned),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
let root_target = target(root);
|
|
||||||
let parent_target = parent.map(target).unwrap_or_else(|| root_target.clone());
|
|
||||||
|
|
||||||
CommentBuilder::new(content, parent_target)
|
|
||||||
.root(root_target)
|
|
||||||
.into_event_builder()
|
|
||||||
.tags([Tag::coordinate(addr.clone().into(), None)])
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use anyhow::anyhow;
|
|
||||||
use gpui::{AppContext as _, Task, TestAppContext};
|
|
||||||
|
|
||||||
use super::RepoStore;
|
|
||||||
|
|
||||||
#[gpui::test]
|
|
||||||
fn a_finished_push_releases_the_busy_flag(cx: &mut TestAppContext) {
|
|
||||||
let store = cx.new(|_| RepoStore::new_local(PathBuf::from("repo"), None));
|
|
||||||
|
|
||||||
let push = store.update(cx, |store, cx| {
|
|
||||||
store.run_push(Task::ready(Err(anyhow!("push refused"))), None, cx)
|
|
||||||
});
|
|
||||||
cx.run_until_parked();
|
|
||||||
|
|
||||||
assert!(push.is_ready());
|
|
||||||
assert!(!cx.update(|app| store.read(app).pushing));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,25 +11,6 @@ use signed_git::Repo;
|
|||||||
|
|
||||||
use crate::push::{GraspServer, PushOutcome, grasp_base_url};
|
use crate::push::{GraspServer, PushOutcome, grasp_base_url};
|
||||||
|
|
||||||
/// A git ref with the commit it points at.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct GitRef {
|
|
||||||
/// Full ref name, like `refs/heads/main` or `refs/tags/v1.0`.
|
|
||||||
pub name: String,
|
|
||||||
pub commit: Sha1Hash,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GitRef {
|
|
||||||
pub fn new(name: impl Into<String>, commit: &str) -> Result<Self, Error> {
|
|
||||||
let commit = Sha1Hash::from_str(commit).map_err(|_| anyhow!("invalid commit: {commit}"))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
name: name.into(),
|
|
||||||
commit,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How much to push to the grasp servers.
|
/// How much to push to the grasp servers.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
pub enum GitPushMode {
|
pub enum GitPushMode {
|
||||||
@@ -52,16 +33,6 @@ pub enum GitPushPolicy {
|
|||||||
ResetRemote,
|
ResetRemote,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct SyncState {
|
|
||||||
pub refs: Vec<GitRef>,
|
|
||||||
pub head: Option<String>,
|
|
||||||
/// Local repository to push from; `None` for states parsed from events.
|
|
||||||
pub path: Option<PathBuf>,
|
|
||||||
pub mode: GitPushMode,
|
|
||||||
pub policy: GitPushPolicy,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum PushStep {
|
pub enum PushStep {
|
||||||
AnnounceRepository,
|
AnnounceRepository,
|
||||||
@@ -102,6 +73,35 @@ impl PushStepStatus {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A git ref with the commit it points at.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct GitRef {
|
||||||
|
/// Full ref name, like `refs/heads/main` or `refs/tags/v1.0`.
|
||||||
|
pub name: String,
|
||||||
|
pub commit: Sha1Hash,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GitRef {
|
||||||
|
pub fn new(name: impl Into<String>, commit: &str) -> Result<Self, Error> {
|
||||||
|
let commit = Sha1Hash::from_str(commit).map_err(|_| anyhow!("invalid commit: {commit}"))?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
name: name.into(),
|
||||||
|
commit,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct SyncState {
|
||||||
|
pub refs: Vec<GitRef>,
|
||||||
|
pub head: Option<String>,
|
||||||
|
/// Local repository to push from; `None` for states parsed from events.
|
||||||
|
pub path: Option<PathBuf>,
|
||||||
|
pub mode: GitPushMode,
|
||||||
|
pub policy: GitPushPolicy,
|
||||||
|
}
|
||||||
|
|
||||||
impl SyncState {
|
impl SyncState {
|
||||||
pub fn build(id: &str, refs: &[GitRef], head: Option<&str>) -> EventBuilder {
|
pub fn build(id: &str, refs: &[GitRef], head: Option<&str>) -> EventBuilder {
|
||||||
let mut tags: Vec<Tag> = vec![Tag::identifier(id.to_owned())];
|
let mut tags: Vec<Tag> = vec![Tag::identifier(id.to_owned())];
|
||||||
@@ -397,11 +397,11 @@ impl SyncState {
|
|||||||
repo.push_refspecs(&base, &owner, &repo_id, &[refspec.as_str()])
|
repo.push_refspecs(&base, &owner, &repo_id, &[refspec.as_str()])
|
||||||
}
|
}
|
||||||
GitPushMode::All => {
|
GitPushMode::All => {
|
||||||
let mut refspecs = force_refspecs();
|
let mut refspecs = Self::force_refspecs();
|
||||||
if policy == GitPushPolicy::ResetRemote {
|
if policy == GitPushPolicy::ResetRemote {
|
||||||
let url = format!("{base}/{owner}/{repo_id}.git");
|
let url = format!("{base}/{owner}/{repo_id}.git");
|
||||||
let server_refs = repo.ls_remote(&url)?;
|
let server_refs = repo.ls_remote(&url)?;
|
||||||
refspecs.extend(deletion_refspecs(&declared, &server_refs));
|
refspecs.extend(Self::deletion_refspecs(&declared, &server_refs));
|
||||||
}
|
}
|
||||||
|
|
||||||
let refspecs = refspecs.iter().map(String::as_str).collect::<Vec<_>>();
|
let refspecs = refspecs.iter().map(String::as_str).collect::<Vec<_>>();
|
||||||
@@ -526,21 +526,21 @@ impl SyncState {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Refspecs to force push all heads and tags to the grasp servers.
|
/// Refspecs to force push all heads and tags to the grasp servers.
|
||||||
fn force_refspecs() -> Vec<String> {
|
fn force_refspecs() -> Vec<String> {
|
||||||
vec![
|
vec![
|
||||||
"+refs/heads/*:refs/heads/*".to_owned(),
|
"+refs/heads/*:refs/heads/*".to_owned(),
|
||||||
"+refs/tags/*:refs/tags/*".to_owned(),
|
"+refs/tags/*:refs/tags/*".to_owned(),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Refspecs to delete server-only refs from the grasp servers.
|
/// Refspecs to delete server-only refs from the grasp servers.
|
||||||
fn deletion_refspecs(declared: &[String], server_refs: &[(String, String)]) -> Vec<String> {
|
fn deletion_refspecs(declared: &[String], server_refs: &[(String, String)]) -> Vec<String> {
|
||||||
server_refs
|
server_refs
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(name, _)| !declared.contains(name))
|
.filter(|(name, _)| !declared.contains(name))
|
||||||
.map(|(name, _)| format!(":{name}"))
|
.map(|(name, _)| format!(":{name}"))
|
||||||
.collect()
|
.collect()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
use std::cell::RefCell;
|
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -16,6 +15,12 @@ use crate::state::SyncState;
|
|||||||
const SYNC_POLL: Duration = Duration::from_secs(180);
|
const SYNC_POLL: Duration = Duration::from_secs(180);
|
||||||
const MAX_SYNC_CHECKOUTS: usize = 8;
|
const MAX_SYNC_CHECKOUTS: usize = 8;
|
||||||
|
|
||||||
|
/// Statuses for these repositories may have changed; empty on signer change.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum SyncEvent {
|
||||||
|
Updated(Vec<(RepoAddr, Vec<CheckoutSyncStatus>)>),
|
||||||
|
}
|
||||||
|
|
||||||
struct GlobalSyncStatusStore(Entity<SyncStatusStore>);
|
struct GlobalSyncStatusStore(Entity<SyncStatusStore>);
|
||||||
|
|
||||||
impl Global for GlobalSyncStatusStore {}
|
impl Global for GlobalSyncStatusStore {}
|
||||||
@@ -27,15 +32,12 @@ pub struct CheckoutSyncStatus {
|
|||||||
pub status: RepoSyncStatus,
|
pub status: RepoSyncStatus,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Statuses for these repositories may have changed; empty on signer change.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum SyncEvent {
|
|
||||||
Updated(Vec<(RepoAddr, Vec<CheckoutSyncStatus>)>),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Probes tracked repositories and broadcasts results. Holds no statuses.
|
/// Probes tracked repositories and broadcasts results. Holds no statuses.
|
||||||
pub struct SyncStatusStore {
|
pub struct SyncStatusStore {
|
||||||
active: RefCell<HashSet<RepoAddr>>,
|
// Addresses a live directory still renders, with one count per directory.
|
||||||
|
active: HashMap<RepoAddr, usize>,
|
||||||
|
// One-shot probes that should not keep the repository on the poll.
|
||||||
|
requested: HashSet<RepoAddr>,
|
||||||
in_flight: bool,
|
in_flight: bool,
|
||||||
pass_pending: bool,
|
pass_pending: bool,
|
||||||
poll_pending: bool,
|
poll_pending: bool,
|
||||||
@@ -93,7 +95,8 @@ impl SyncStatusStore {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
active: RefCell::new(HashSet::new()),
|
active: HashMap::new(),
|
||||||
|
requested: HashSet::new(),
|
||||||
sender,
|
sender,
|
||||||
in_flight: false,
|
in_flight: false,
|
||||||
pass_pending: false,
|
pass_pending: false,
|
||||||
@@ -105,10 +108,37 @@ impl SyncStatusStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Queue a probe pass; folded into any pass already in flight.
|
/// Requests a one-shot probe pass; folded into any pass already in flight.
|
||||||
pub fn probe(&self, addrs: impl IntoIterator<Item = RepoAddr>) {
|
pub fn probe(&mut self, addrs: impl IntoIterator<Item = RepoAddr>) {
|
||||||
self.active.borrow_mut().extend(addrs);
|
self.requested.extend(addrs);
|
||||||
|
self.wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps these addresses on the periodic poll until released.
|
||||||
|
pub fn track(&mut self, addrs: impl IntoIterator<Item = RepoAddr>) {
|
||||||
|
for addr in addrs {
|
||||||
|
*self.active.entry(addr).or_default() += 1;
|
||||||
|
}
|
||||||
|
self.wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops one directory's interest in these addresses.
|
||||||
|
pub fn untrack(&mut self, addrs: impl IntoIterator<Item = RepoAddr>) {
|
||||||
|
for addr in addrs {
|
||||||
|
let remove = match self.active.get_mut(&addr) {
|
||||||
|
Some(count) => {
|
||||||
|
*count = count.saturating_sub(1);
|
||||||
|
*count == 0
|
||||||
|
}
|
||||||
|
None => false,
|
||||||
|
};
|
||||||
|
if remove {
|
||||||
|
self.active.remove(&addr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wake(&self) {
|
||||||
if let Err(e) = self.sender.send(()) {
|
if let Err(e) = self.sender.send(()) {
|
||||||
log::warn!("failed to queue sync status probe: {e}");
|
log::warn!("failed to queue sync status probe: {e}");
|
||||||
}
|
}
|
||||||
@@ -116,8 +146,8 @@ impl SyncStatusStore {
|
|||||||
|
|
||||||
// Keeps the in-flight pass so its completion releases the slot exactly once.
|
// Keeps the in-flight pass so its completion releases the slot exactly once.
|
||||||
fn clear(&mut self, cx: &mut Context<Self>) {
|
fn clear(&mut self, cx: &mut Context<Self>) {
|
||||||
let had_addrs = !self.active.borrow().is_empty();
|
let had_addrs = !self.active.is_empty() || !self.requested.is_empty();
|
||||||
self.active.borrow_mut().clear();
|
self.requested.clear();
|
||||||
self.pass_pending = false;
|
self.pass_pending = false;
|
||||||
|
|
||||||
if had_addrs {
|
if had_addrs {
|
||||||
@@ -136,29 +166,36 @@ impl SyncStatusStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let backend = Backend::global(cx);
|
let backend = Backend::global(cx);
|
||||||
let client = backend.read(cx).client();
|
|
||||||
|
|
||||||
if backend.read(cx).current_user().is_none() {
|
if backend.read(cx).current_user().is_none() {
|
||||||
self.clear(cx);
|
self.clear(cx);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.active.borrow().is_empty() {
|
if self.active.is_empty() && self.requested.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.in_flight = true;
|
self.in_flight = true;
|
||||||
self.schedule_poll(cx);
|
let poll = !self.active.is_empty();
|
||||||
|
if poll {
|
||||||
|
self.schedule_poll(cx);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut targets: Vec<RepoAddr> = self.active.keys().cloned().collect();
|
||||||
|
targets.extend(self.requested.drain());
|
||||||
|
targets.sort();
|
||||||
|
targets.dedup();
|
||||||
|
|
||||||
|
let client = backend.read(cx).client();
|
||||||
let targets: Vec<(RepoAddr, Vec<PathBuf>)> = {
|
let targets: Vec<(RepoAddr, Vec<PathBuf>)> = {
|
||||||
let active = self.active.borrow();
|
|
||||||
let checkouts = CheckoutsStore::global(cx);
|
let checkouts = CheckoutsStore::global(cx);
|
||||||
|
|
||||||
active
|
targets
|
||||||
.iter()
|
.into_iter()
|
||||||
.map(|addr| {
|
.map(|addr| {
|
||||||
let paths = checkouts.read(cx).associations_of(addr);
|
let paths = checkouts.read(cx).associations_of(&addr);
|
||||||
(addr.clone(), paths)
|
(addr, paths)
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
};
|
};
|
||||||
@@ -260,7 +297,8 @@ impl SyncStatusStore {
|
|||||||
/// Sync status cache bound to one panel or screen.
|
/// Sync status cache bound to one panel or screen.
|
||||||
pub struct SyncStatusDirectory {
|
pub struct SyncStatusDirectory {
|
||||||
statuses: HashMap<RepoAddr, Vec<CheckoutSyncStatus>>,
|
statuses: HashMap<RepoAddr, Vec<CheckoutSyncStatus>>,
|
||||||
pending: RefCell<HashSet<RepoAddr>>,
|
pending: HashSet<RepoAddr>,
|
||||||
|
tracked: HashSet<RepoAddr>,
|
||||||
_subscriptions: Vec<Subscription>,
|
_subscriptions: Vec<Subscription>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,10 +313,20 @@ impl SyncStatusDirectory {
|
|||||||
SyncEvent::Updated(updates) => this.apply(updates.clone(), cx),
|
SyncEvent::Updated(updates) => this.apply(updates.clone(), cx),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let release = cx.on_release(|this: &mut Self, cx| {
|
||||||
|
let tracked = std::mem::take(&mut this.tracked);
|
||||||
|
if tracked.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let store = SyncStatusStore::global(cx);
|
||||||
|
store.update(cx, |store, _| store.untrack(tracked));
|
||||||
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
statuses: HashMap::new(),
|
statuses: HashMap::new(),
|
||||||
pending: RefCell::new(HashSet::new()),
|
pending: HashSet::new(),
|
||||||
_subscriptions: vec![subscription],
|
tracked: HashSet::new(),
|
||||||
|
_subscriptions: vec![subscription, release],
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -289,7 +337,8 @@ impl SyncStatusDirectory {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|addr| {
|
.filter(|addr| {
|
||||||
!self.statuses.contains_key(addr)
|
!self.statuses.contains_key(addr)
|
||||||
&& !self.with_pending(|pending| pending.contains(addr))
|
&& !self.pending.contains(addr)
|
||||||
|
&& !self.tracked.contains(addr)
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
@@ -297,30 +346,18 @@ impl SyncStatusDirectory {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.with_pending(|pending| pending.extend(missing.iter().cloned()));
|
self.pending.extend(missing.iter().cloned());
|
||||||
|
self.tracked.extend(missing.iter().cloned());
|
||||||
|
|
||||||
let store = SyncStatusStore::global(cx);
|
let store = SyncStatusStore::global(cx);
|
||||||
store.read(cx).probe(missing);
|
store.update(cx, |store, _| {
|
||||||
|
store.track(missing);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Statuses for a repo, or empty; a miss queues a probe.
|
/// Statuses for a repo, or empty.
|
||||||
pub fn statuses_of(&self, addr: &RepoAddr, cx: &App) -> Vec<CheckoutSyncStatus> {
|
pub fn statuses_of(&self, addr: &RepoAddr) -> &[CheckoutSyncStatus] {
|
||||||
self.queue(addr, cx);
|
self.statuses.get(addr).map(Vec::as_slice).unwrap_or(&[])
|
||||||
self.statuses.get(addr).cloned().unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Commits available locally but missing on Nostr.
|
|
||||||
pub fn unsynced(&self, addr: &RepoAddr, cx: &App) -> usize {
|
|
||||||
self.queue(addr, cx);
|
|
||||||
|
|
||||||
self.statuses
|
|
||||||
.get(addr)
|
|
||||||
.map(|list| {
|
|
||||||
list.iter()
|
|
||||||
.map(|checkout| checkout.status.ahead_total)
|
|
||||||
.sum()
|
|
||||||
})
|
|
||||||
.unwrap_or(0)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Commit ids missing on Nostr, mapped to their checkout; restricted to `checkout` if tracked.
|
/// Commit ids missing on Nostr, mapped to their checkout; restricted to `checkout` if tracked.
|
||||||
@@ -328,10 +365,7 @@ impl SyncStatusDirectory {
|
|||||||
&self,
|
&self,
|
||||||
addr: &RepoAddr,
|
addr: &RepoAddr,
|
||||||
checkout: Option<&Path>,
|
checkout: Option<&Path>,
|
||||||
cx: &App,
|
|
||||||
) -> HashMap<String, PathBuf> {
|
) -> HashMap<String, PathBuf> {
|
||||||
self.queue(addr, cx);
|
|
||||||
|
|
||||||
let Some(statuses) = self.statuses.get(addr) else {
|
let Some(statuses) = self.statuses.get(addr) else {
|
||||||
return HashMap::new();
|
return HashMap::new();
|
||||||
};
|
};
|
||||||
@@ -359,22 +393,11 @@ impl SyncStatusDirectory {
|
|||||||
commits
|
commits
|
||||||
}
|
}
|
||||||
|
|
||||||
fn queue(&self, addr: &RepoAddr, cx: &App) {
|
|
||||||
if self.statuses.contains_key(addr) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.with_pending(|pending| pending.insert(addr.clone())) {
|
|
||||||
let store = SyncStatusStore::global(cx);
|
|
||||||
store.read(cx).probe([addr.clone()]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply(&mut self, updates: Vec<(RepoAddr, Vec<CheckoutSyncStatus>)>, cx: &mut Context<Self>) {
|
fn apply(&mut self, updates: Vec<(RepoAddr, Vec<CheckoutSyncStatus>)>, cx: &mut Context<Self>) {
|
||||||
if updates.is_empty() {
|
if updates.is_empty() {
|
||||||
let changed = !self.statuses.is_empty();
|
let changed = !self.statuses.is_empty();
|
||||||
self.statuses.clear();
|
self.statuses.clear();
|
||||||
self.with_pending(|pending| pending.clear());
|
self.pending.clear();
|
||||||
|
|
||||||
if changed {
|
if changed {
|
||||||
cx.notify();
|
cx.notify();
|
||||||
@@ -387,7 +410,8 @@ impl SyncStatusDirectory {
|
|||||||
|
|
||||||
for (addr, list) in updates {
|
for (addr, list) in updates {
|
||||||
let relevant = self.statuses.contains_key(&addr)
|
let relevant = self.statuses.contains_key(&addr)
|
||||||
|| self.with_pending(|pending| pending.remove(&addr));
|
|| self.pending.remove(&addr)
|
||||||
|
|| self.tracked.contains(&addr);
|
||||||
|
|
||||||
if !relevant {
|
if !relevant {
|
||||||
continue;
|
continue;
|
||||||
@@ -403,9 +427,4 @@ impl SyncStatusDirectory {
|
|||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_pending<R>(&self, then: impl FnOnce(&mut HashSet<RepoAddr>) -> R) -> R {
|
|
||||||
let mut pending = self.pending.borrow_mut();
|
|
||||||
then(&mut pending)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user