feat: out-of-box experience (#2)

Reviewed-on: https://git.reya.su/reya/signed/pulls/2
This commit was merged in pull request #2.
This commit is contained in:
2026-08-25 13:23:07 +00:00
parent 7249a323f8
commit dacfd49cdf
180 changed files with 16763 additions and 1042 deletions
+9 -40
View File
@@ -1,44 +1,13 @@
use std::fmt;
use std::str::FromStr;
use nostr::prelude::*;
/// Address of a NIP-34 repository announcement: `30617:<owner-pubkey>:<repo-id>`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RepoAddr {
pub owner: PublicKey,
pub id: String,
}
impl RepoAddr {
pub fn new(owner: PublicKey, id: impl Into<String>) -> Self {
Self {
owner,
id: id.into(),
}
}
/// The NIP-33 coordinate for the announcement event (`a` tag value).
pub fn coordinate(&self) -> Coordinate {
Coordinate::new(Kind::GitRepoAnnouncement, self.owner).identifier(self.id.clone())
}
}
impl fmt::Display for RepoAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.coordinate())
}
}
impl FromStr for RepoAddr {
type Err = nostr::error::Error;
/// Parse from `<kind>:<pubkey>:<d-tag>`, `naddr1...` bech32 or `nostr:naddr1...` URI.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let coordinate = Coordinate::parse(s)?;
Ok(Self {
owner: coordinate.public_key,
id: coordinate.identifier,
})
}
///
/// The Rust Nostr SDK's [`Coordinate`] already provides parsing, formatting
/// and hashing for this; the alias keeps the repository-specific vocabulary
/// while reusing the SDK type.
pub type RepoAddr = Coordinate;
/// Build the address of a NIP-34 repository announcement.
pub fn repo_addr(owner: PublicKey, id: impl Into<String>) -> RepoAddr {
Coordinate::new(Kind::GitRepoAnnouncement, owner).identifier(id)
}
+306
View File
@@ -0,0 +1,306 @@
use nostr::prelude::*;
/// ngit / GitWorkshop cover-note extension (kind 1624): a markdown note
/// attached to an issue, patch or PR by its author or a repository
/// maintainer. Not part of the NIP-34 draft; read support for interop.
pub const COVER_NOTE_KIND: Kind = Kind::Custom(1624);
/// Whether a kind-1985 label event is a valid annotation of `root`: it
/// references the root via a lowercase `e` tag and was authored by the root
/// author or a maintainer.
fn label_targets_root(event: &Event, root: &Event, maintainers: &[PublicKey]) -> bool {
if event.kind != Kind::Label {
return false;
}
if event.pubkey != root.pubkey && !maintainers.contains(&event.pubkey) {
return false;
}
let root_id = root.id.to_hex();
event
.tags
.iter()
.any(|tag| tag.kind() == "e" && tag.content().is_some_and(|content| content == root_id))
}
/// Whether a kind-1985 label event declares the `#t` namespace and carries at
/// least one `["l", "<value>", "#t"]` label.
fn has_hashtag_labels(event: &Event) -> bool {
event.tags.iter().any(|tag| tag.as_slice() == ["L", "#t"])
&& event.tags.iter().any(|tag| {
let slice = tag.as_slice();
slice.len() >= 3 && slice[0] == "l" && slice[2] == "#t" && !slice[1].is_empty()
})
}
/// The effective hashtag labels of `root`: the `t` tags on the event itself
/// (self-reported by its author) plus all labels attached via authorized
/// NIP-32 kind-1985 events in the `#t` namespace. Labels are additive — all
/// valid label events contribute (no latest-wins semantics).
pub fn labels(root: &Event, label_events: &[Event], maintainers: &[PublicKey]) -> Vec<String> {
let mut labels: Vec<String> = root
.tags
.hashtags()
.map(|hashtag| hashtag.to_string())
.collect();
for event in label_events {
if !label_targets_root(event, root, maintainers) || !has_hashtag_labels(event) {
continue;
}
for tag in event.tags.iter() {
let slice = tag.as_slice();
if slice.len() >= 3 && slice[0] == "l" && slice[2] == "#t" && !slice[1].is_empty() {
let label = &slice[1];
if !labels.contains(label) {
labels.push(label.clone());
}
}
}
}
labels
}
/// The effective subject/title override of `root`, from authorized kind-1985
/// label events in the `#subject` namespace. Only the latest event wins
/// (tiebreak: lexicographically larger event id, per NIP-01 replaceable
/// semantics). Returns `None` when no valid override exists.
pub fn subject_override(
root: &Event,
label_events: &[Event],
maintainers: &[PublicKey],
) -> Option<String> {
label_events
.iter()
.filter(|event| label_targets_root(event, root, maintainers))
.filter(|event| {
event
.tags
.iter()
.any(|tag| tag.as_slice() == ["L", "#subject"])
&& event.tags.iter().any(|tag| {
let slice = tag.as_slice();
slice.len() >= 3
&& slice[0] == "l"
&& slice[2] == "#subject"
&& !slice[1].is_empty()
})
})
.max_by(|a, b| {
a.created_at
.cmp(&b.created_at)
.then_with(|| a.id.to_string().cmp(&b.id.to_string()))
})
.and_then(|event| {
event.tags.iter().find_map(|tag| {
let slice = tag.as_slice();
(slice.len() >= 3
&& slice[0] == "l"
&& slice[2] == "#subject"
&& !slice[1].is_empty())
.then(|| slice[1].clone())
})
})
}
/// The effective hashtag labels and subject override of `root` in one pass
/// (mirrors ngit's `get_labels_and_subject`).
pub fn labels_and_subject(
root: &Event,
label_events: &[Event],
maintainers: &[PublicKey],
) -> (Vec<String>, Option<String>) {
(
labels(root, label_events, maintainers),
subject_override(root, label_events, maintainers),
)
}
/// The effective cover note of `root`: the latest authorized kind-1624 event
/// (tiebreak: lexicographically larger event id, per NIP-01 replaceable
/// semantics). Returns `None` when no valid cover note exists.
pub fn cover_note<'a>(
root: &Event,
cover_notes: &'a [Event],
maintainers: &[PublicKey],
) -> Option<&'a Event> {
let root_id = root.id.to_hex();
cover_notes
.iter()
.filter(|event| {
event.kind == COVER_NOTE_KIND
&& (event.pubkey == root.pubkey || maintainers.contains(&event.pubkey))
&& event.tags.iter().any(|tag| {
tag.kind() == "e" && tag.content().is_some_and(|content| content == root_id)
})
})
.max_by(|a, b| {
a.created_at
.cmp(&b.created_at)
.then_with(|| a.id.to_string().cmp(&b.id.to_string()))
})
}
#[cfg(test)]
mod tests {
use super::*;
fn keys_from_hex(hex: &str) -> Keys {
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(created_at))
.finalize(author)
.expect("signed event")
}
fn root_event() -> Event {
signed(
&keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001"),
Kind::GitIssue,
vec![Tag::hashtag("bug")],
100,
)
}
fn e_tag(event: &Event) -> Tag {
Tag::parse(["e", &event.id.to_hex()]).expect("valid e tag")
}
#[test]
fn labels_take_inline_hashtags_and_external_label_events() {
let root = root_event();
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let labels_event = signed(
&maintainer,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["L", "#t"]).expect("valid L tag"),
Tag::parse(["l", "help-wanted", "#t"]).expect("valid l tag"),
],
200,
);
let labels = labels(&root, &[labels_event], &[maintainer.public_key()]);
assert_eq!(labels, vec!["bug", "help-wanted"]);
}
#[test]
fn labels_ignore_unauthorized_and_misnamed_events() {
let root = root_event();
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let stranger =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000003");
// A stranger's label event is not authorized.
let stranger_labels = signed(
&stranger,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["L", "#t"]).expect("valid L tag"),
Tag::parse(["l", "nope", "#t"]).expect("valid l tag"),
],
200,
);
// A valid author referencing a different event.
let other_labels = signed(
&maintainer,
Kind::Label,
vec![
Tag::parse([
"e",
"2222222222222222222222222222222222222222222222222222222222222222",
])
.expect("valid e tag"),
Tag::parse(["L", "#t"]).expect("valid L tag"),
Tag::parse(["l", "nope", "#t"]).expect("valid l tag"),
],
200,
);
// A valid author without the namespace declaration.
let missing_namespace = signed(
&maintainer,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["l", "nope", "#t"]).expect("valid l tag"),
],
200,
);
assert_eq!(
labels(
&root,
&[stranger_labels, other_labels, missing_namespace],
&[maintainer.public_key()]
),
vec!["bug"]
);
}
#[test]
fn subject_override_latest_authorized_event_wins() {
let root = root_event();
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let older = signed(
&maintainer,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["L", "#subject"]).expect("valid L tag"),
Tag::parse(["l", "Old title", "#subject"]).expect("valid l tag"),
],
200,
);
let newer = signed(
&maintainer,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["L", "#subject"]).expect("valid L tag"),
Tag::parse(["l", "New title", "#subject"]).expect("valid l tag"),
],
300,
);
assert_eq!(
subject_override(&root, &[newer, older], &[maintainer.public_key()]),
Some("New title".to_owned())
);
}
#[test]
fn cover_note_latest_authorized_event_wins() {
let root = root_event();
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let stranger =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000003");
let older = signed(&maintainer, COVER_NOTE_KIND, vec![e_tag(&root)], 200);
let newer = signed(&maintainer, COVER_NOTE_KIND, vec![e_tag(&root)], 300);
let unauthorized = signed(&stranger, COVER_NOTE_KIND, vec![e_tag(&root)], 400);
let newer_id = newer.id;
let events = [older, unauthorized, newer];
let maintainers = [maintainer.public_key()];
let note = cover_note(&root, &events, &maintainers);
assert_eq!(note.map(|event| event.id), Some(newer_id));
}
#[test]
fn cover_note_none_without_valid_events() {
let root = root_event();
assert_eq!(cover_note(&root, &[], &[]), None);
}
}
+1 -4
View File
@@ -28,10 +28,7 @@ pub fn parse_clone_url(url: &str) -> Option<CloneTarget> {
if first.starts_with("naddr1") {
let coordinate = Nip19Coordinate::from_bech32(first).ok()?;
return Some(CloneTarget::Addr(RepoAddr::new(
coordinate.coordinate.public_key,
coordinate.coordinate.identifier,
)));
return Some(CloneTarget::Addr(coordinate.coordinate));
}
let (relay_hint, identifier) = match third {
+161
View File
@@ -0,0 +1,161 @@
use std::collections::{HashMap, HashSet};
use nostr::prelude::*;
/// A NIP-22 comment thread: a top-level comment on the root event and its
/// nested replies (oldest first at every level).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommentThread {
/// The thread's top-level comment.
pub comment: Event,
/// Replies to [`Self::comment`], nested recursively.
pub replies: Vec<CommentThread>,
}
/// The direct parent of a comment (NIP-22 lowercase `e` tag), or `None` for
/// comments without one.
fn comment_parent(event: &Event) -> Option<EventId> {
event
.tags
.iter()
.find(|tag| tag.kind() == "e")
.and_then(Tag::content)
.and_then(|id| EventId::parse(id).ok())
}
/// Group the comments on a root event (issue / patch / PR) into NIP-22
/// threads. A comment whose parent is the root itself starts a thread; other
/// comments nest under their parent comment. Threads and replies are ordered
/// oldest-first. Replies whose parent comment is missing (e.g. not fetched)
/// are placed as top-level threads so they are not dropped.
pub fn comment_threads(root: &Event, comments: &[Event]) -> Vec<CommentThread> {
// Index comments by their parent id. Comments without a parent tag are
// treated as replying to the root event itself.
let mut children: HashMap<EventId, Vec<&Event>> = HashMap::new();
for comment in comments {
let parent = comment_parent(comment).unwrap_or(root.id);
children.entry(parent).or_default().push(comment);
}
for list in children.values_mut() {
list.sort_by_key(|event| event.created_at);
}
let mut visited: HashSet<EventId> = HashSet::new();
fn build(
id: EventId,
children: &HashMap<EventId, Vec<&Event>>,
visited: &mut HashSet<EventId>,
) -> Vec<CommentThread> {
let Some(list) = children.get(&id) else {
return Vec::new();
};
let mut threads = Vec::new();
for event in list {
// Guards against malformed reply cycles.
if visited.insert(event.id) {
threads.push(CommentThread {
comment: (*event).clone(),
replies: build(event.id, children, visited),
});
}
}
threads
}
let mut threads = build(root.id, &children, &mut visited);
// Orphan replies: their parent comment is unknown, so they never appear
// in the tree rooted at the root event; surface them as top-level threads.
let mut orphans: Vec<&Event> = comments
.iter()
.filter(|event| !visited.contains(&event.id))
.collect();
orphans.sort_by_key(|event| event.created_at);
for comment in orphans {
if visited.insert(comment.id) {
threads.push(CommentThread {
comment: comment.clone(),
replies: build(comment.id, &children, &mut visited),
});
}
}
threads
}
#[cfg(test)]
mod tests {
use super::*;
fn comment(keys: &Keys, parent: Option<&Event>, content: &str, created_at: u64) -> Event {
let tags = parent
.map(|parent| vec![Tag::parse(["e", &parent.id.to_hex()]).expect("valid e tag")])
.unwrap_or_default();
EventBuilder::new(Kind::Comment, content)
.tags(tags)
.custom_created_at(Timestamp::from(created_at))
.finalize(keys)
.expect("signed event")
}
fn flatten(threads: &[CommentThread]) -> Vec<String> {
let mut out = Vec::new();
for thread in threads {
out.push(thread.comment.content.clone());
out.extend(flatten(&thread.replies));
}
out
}
#[test]
fn nests_replies_under_their_parents() {
let keys = Keys::generate();
let root = EventBuilder::new(Kind::GitIssue, "issue")
.finalize(&keys)
.expect("signed event");
let a = comment(&keys, Some(&root), "a", 100);
let a1 = comment(&keys, Some(&a), "a1", 200);
let a2 = comment(&keys, Some(&a), "a2", 300);
let b = comment(&keys, Some(&root), "b", 150);
let threads = comment_threads(&root, &[a2, b, a, a1]);
assert_eq!(flatten(&threads), vec!["a", "a1", "a2", "b"]);
}
#[test]
fn comments_without_a_parent_tag_attach_to_the_root() {
let keys = Keys::generate();
let root = EventBuilder::new(Kind::GitIssue, "issue")
.finalize(&keys)
.expect("signed event");
// Old-style comments carried no `e` tag at all.
let orphan = comment(&keys, None, "no parent", 100);
let threads = comment_threads(&root, &[orphan]);
assert_eq!(flatten(&threads), vec!["no parent"]);
}
#[test]
fn orphan_replies_are_surfaced_as_top_level_threads() {
let keys = Keys::generate();
let root = EventBuilder::new(Kind::GitIssue, "issue")
.finalize(&keys)
.expect("signed event");
let a = comment(&keys, Some(&root), "a", 100);
// `missing` is not in the comment set; its reply should still show up.
let missing = EventBuilder::new(Kind::Comment, "missing")
.finalize(&keys)
.expect("signed event");
let reply_to_missing = comment(&keys, Some(&missing), "reply to missing", 200);
let threads = comment_threads(&root, &[a, reply_to_missing]);
assert_eq!(flatten(&threads), vec!["a", "reply to missing"]);
}
}
+79
View File
@@ -0,0 +1,79 @@
use std::collections::HashSet;
use nostr::prelude::*;
/// NIP-09 deletion requests and NIP-62 vanish requests, used to hide
/// deleted events before they reach the UI.
///
/// Built from the kind-5 / kind-62 events stored in the local database;
/// pass any event through [`Deletions::is_deleted`] before displaying it.
pub struct Deletions {
/// `(deleted event id, expected author)` from `e` tags of kind-5 events.
ids: HashSet<(EventId, PublicKey)>,
/// `(coordinate, expected author, cutoff)` from `a` tags of kind-5 events.
/// All versions of the addressable event up to `cutoff` are deleted.
coords: Vec<(Coordinate, PublicKey, Timestamp)>,
/// `(author, cutoff)` from kind-62 vanish requests.
vanished: Vec<(PublicKey, Timestamp)>,
}
impl Deletions {
/// Build the deletion index from raw kind-5 and kind-62 events.
pub fn from_events(events: impl IntoIterator<Item = Event>) -> Self {
let mut ids = HashSet::new();
let mut coords = Vec::new();
let mut vanished = Vec::new();
for event in events {
if event.kind == Kind::EventDeletion {
ids.extend(event.tags.event_ids().map(|id| (id, event.pubkey)));
coords.extend(
event
.tags
.coordinates()
.map(|c| (c, event.pubkey, event.created_at)),
);
} else if event.kind == Kind::RequestToVanish {
// Client-side we can't verify which relay the request targeted,
// so any vanish request is honored for the author's events.
vanished.push((event.pubkey, event.created_at));
}
}
Self {
ids,
coords,
vanished,
}
}
/// Whether the event is covered by a valid deletion or vanish request.
///
/// A request is only valid when its author matches the deleted event's
/// author (NIP-09); addressable events are deleted up to the request's
/// `created_at`.
pub fn is_deleted(&self, event: &Event) -> bool {
if self
.vanished
.iter()
.any(|(pk, cutoff)| *pk == event.pubkey && event.created_at <= *cutoff)
{
return true;
}
if self.ids.contains(&(event.id, event.pubkey)) {
return true;
}
if event.kind.is_addressable()
&& let Some(identifier) = event.tags.identifier()
{
let coordinate = Coordinate::new(event.kind, event.pubkey).identifier(identifier);
return self.coords.iter().any(|(c, pk, cutoff)| {
*c == coordinate && *pk == event.pubkey && event.created_at <= *cutoff
});
}
false
}
}
+70 -14
View File
@@ -1,14 +1,14 @@
use nostr::filter::{Alphabet, SingleLetterTag};
use nostr::prelude::*;
use crate::RepoAddr;
/// Kinds that make up the activity of a repository.
pub const ACTIVITY_KINDS: [Kind; 8] = [
pub const ACTIVITY_KINDS: [Kind; 9] = [
Kind::GitPatch,
Kind::GitPullRequest,
Kind::GitPullRequestUpdate,
Kind::GitIssue,
Kind::Comment,
Kind::GitStatusOpen,
Kind::GitStatusApplied,
Kind::GitStatusClosed,
@@ -19,26 +19,25 @@ pub const ACTIVITY_KINDS: [Kind; 8] = [
pub fn announcement(addr: &RepoAddr) -> Filter {
Filter::new()
.kind(Kind::GitRepoAnnouncement)
.author(addr.owner)
.identifier(addr.id.clone())
.author(addr.public_key)
.identifier(addr.identifier.clone())
}
/// Latest state event (refs / HEAD) for a repository.
pub fn state(addr: &RepoAddr) -> Filter {
Filter::new()
.kind(Kind::RepoState)
.author(addr.owner)
.identifier(addr.id.clone())
.author(addr.public_key)
.identifier(addr.identifier.clone())
}
/// All NIP-34 activity addressed to a repository (`#a` tag).
/// All NIP-34 activity addressed to a repository (`#a` tag): issues, PRs,
/// patches, statuses and comments (kind 1111).
///
/// Note: the `a` tag on status events is optional per NIP-34, so statuses
/// published without it won't be matched here.
pub fn activity(addr: &RepoAddr) -> Filter {
Filter::new()
.kinds(ACTIVITY_KINDS)
.custom_tag(SingleLetterTag::lowercase(Alphabet::A), addr.to_string())
Filter::new().kinds(ACTIVITY_KINDS).coordinate(addr)
}
/// Status events (`1630..=1633`) referencing a specific root event (`#e` tag).
@@ -53,6 +52,15 @@ pub fn statuses_for(root: EventId) -> Filter {
.event(root)
}
/// Cover notes (kind 1624) and NIP-32 label events (kind 1985) referencing a
/// specific root event (`#e` tag), fetched per root like comments and
/// statuses because they carry no repository `a` tag.
pub fn annotations_for(root: EventId) -> Filter {
Filter::new()
.kinds([crate::COVER_NOTE_KIND, Kind::Label])
.event(root)
}
/// A user's grasp list (kind `10317`).
pub fn grasp_list(public_key: PublicKey) -> Filter {
Filter::new()
@@ -60,6 +68,32 @@ pub fn grasp_list(public_key: PublicKey) -> Filter {
.author(public_key)
}
/// NIP-22 comments (kind `1111`) referencing any of the given root events
/// (issues, patches, PRs).
///
/// Comments are not addressed to the repository — they carry no `a` tag with
/// the repo coordinate — so they must be fetched by their root reference
/// instead. NIP-22 defines the uppercase `E` tag as the root of the thread
/// (used by ngit) while some clients (including Signed itself) reference the
/// root with a lowercase `e` tag, so both are matched.
///
/// Returns two filters because `#E` and `#e` conditions would be ANDed if
/// combined into one.
pub fn comments_for(roots: impl IntoIterator<Item = EventId>) -> Vec<Filter> {
let roots: Vec<String> = roots.into_iter().map(|id| id.to_hex()).collect();
if roots.is_empty() {
return Vec::new();
}
vec![
Filter::new()
.kind(Kind::Comment)
.custom_tags(SingleLetterTag::UPPERCASE_E, roots.clone()),
Filter::new()
.kind(Kind::Comment)
.custom_tags(SingleLetterTag::LOWERCASE_E, roots),
]
}
/// All repositories announced by an author.
pub fn announcements_by(public_key: PublicKey) -> Filter {
Filter::new()
@@ -68,8 +102,30 @@ pub fn announcements_by(public_key: PublicKey) -> Filter {
}
/// All repository announcements (for global discovery).
pub fn all_announcements(limit: usize) -> Filter {
Filter::new()
.kind(Kind::GitRepoAnnouncement)
.limit(limit)
///
/// Unbounded: intended for negentropy sync, which reconciles sets
/// efficiently regardless of size. Local database queries with this
/// filter are served by LMDB, so they stay fast as the database grows.
pub fn all_announcements() -> Filter {
Filter::new().kind(Kind::GitRepoAnnouncement)
}
/// All deletion-related events (NIP-09 kind `5`, NIP-62 kind `62`).
///
/// Unbounded, like [`all_announcements`]: deletion requests must be known
/// before any other event can be shown.
pub fn deletions() -> Filter {
Filter::new().kinds([Kind::EventDeletion, Kind::RequestToVanish])
}
/// Deletion events relevant to a single repository: requests authored by
/// the repository owner and requests addressed to the repository
/// coordinate (`#a` tag).
pub fn deletions_for_repo(addr: &RepoAddr) -> Vec<Filter> {
vec![
Filter::new()
.kinds([Kind::EventDeletion, Kind::RequestToVanish])
.author(addr.public_key),
Filter::new().kind(Kind::EventDeletion).coordinate(addr),
]
}
+10 -2
View File
@@ -1,10 +1,18 @@
pub mod addr;
pub mod annotations;
pub mod clone_url;
pub mod comments;
pub mod deletions;
pub mod filters;
pub mod model;
pub mod state;
pub mod status;
pub use addr::RepoAddr;
pub use addr::{RepoAddr, repo_addr};
pub use annotations::{COVER_NOTE_KIND, cover_note, labels_and_subject, subject_override};
pub use clone_url::{CloneTarget, parse_clone_url};
pub use model::Announcement;
pub use comments::{CommentThread, comment_threads};
pub use deletions::Deletions;
pub use model::{Announcement, activity_subject, pull_request_patch};
pub use state::{build_state, parse_state};
pub use status::{RepoStatus, references_root, resolve_status};
+499 -36
View File
@@ -1,26 +1,173 @@
use gpui::SharedString;
use nostr::prelude::*;
/// Parsed NIP-34 repository announcement (plain data, ready for the UI).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Announcement {
/// Repository ID (`d` tag).
pub id: String,
/// Author of the announcement event.
pub owner: PublicKey,
/// When the announcement was published (for latest-wins resolution).
pub created_at: Timestamp,
/// Repository ID (`d` tag).
pub id: String,
pub name: Option<String>,
pub description: Option<String>,
pub name: Option<SharedString>,
pub description: Option<SharedString>,
/// Webpage URLs for browsing.
pub web: Vec<String>,
pub web: Vec<Url>,
/// URLs for `git clone`.
pub clone: Vec<String>,
pub clone: Vec<Url>,
/// Relays the repository monitors for patches and issues.
pub relays: Vec<String>,
pub relays: Vec<RelayUrl>,
/// Earliest unique commit ID (`r` tag with `euc` marker).
pub euc: Option<String>,
/// Other recognized maintainers.
pub maintainers: Vec<PublicKey>,
/// Value of a `u` tag, if any: this repository is a subordinate fork of
/// the referenced upstream (NIP-34).
pub upstream: Option<String>,
/// Hashtags labelling the repository (`t` tags).
pub hashtags: Vec<String>,
}
/// Subject of a NIP-34 issue or pull request event: the `subject` tag,
/// falling back to the first non-empty line of the content.
pub fn activity_subject(event: &Event) -> SharedString {
let subject = event
.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Subject(subject)) => Some(subject),
_ => None,
});
subject
.map(SharedString::from)
.or_else(|| {
event
.content
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.map(SharedString::from)
})
.unwrap_or(SharedString::from("Untitled"))
}
/// The patch set of a pull request: the root patch event (kind `1617`) the
/// PR references via its `e` tag, plus every patch of the set chained to it
/// with NIP-10 `e` reply tags, in series order (oldest first). When the PR
/// has no `e` tag, falls back to the patch producing the PR's tip commit
/// (its `commit`/`r` tag, per NIP-34) and walks the reply chain backward to
/// the root.
///
/// Returns an empty list when no patch event can be linked to the PR.
pub fn pull_request_patches<'a>(
pr: &Event,
patches: impl IntoIterator<Item = &'a Event>,
) -> Vec<&'a Event> {
let patches: Vec<&'a Event> = patches.into_iter().collect();
// The PR references its root patch via an `e` tag; follow the NIP-10
// reply chain forward from there (each patch of the set replies to the
// previous one). Among several replies (a revision), the newest wins.
if let Some(root_id) = pr.tags.event_ids().next()
&& let Some(root) = patches.iter().find(|patch| patch.id == root_id)
{
return forward_series(root, &patches);
}
// No `e` tag: the last patch of the set carries the PR's tip commit in
// its `commit`/`r` tag; walk the reply chain backward to the root.
let Some(tip) = current_commit_of(pr) else {
return Vec::new();
};
let Some(last) = patches
.iter()
.filter(|patch| patch_produces_commit(patch, &tip))
.max_by_key(|patch| patch.created_at)
.copied()
else {
return Vec::new();
};
let mut series = vec![last];
loop {
let Some(prev_id) = series.last().unwrap().tags.event_ids().next() else {
break;
};
let Some(prev) = patches
.iter()
.find(|patch| patch.id == prev_id && !series.contains(patch))
.copied()
else {
break;
};
series.push(prev);
}
series.reverse();
series
}
/// The patch content of a pull request: the contents of every patch event of
/// its patch set (see [`pull_request_patches`]) joined in series order,
/// falling back to the PR's own content for older PRs that carried the
/// patch inline.
pub fn pull_request_patch<'a>(pr: &Event, patches: impl IntoIterator<Item = &'a Event>) -> String {
let patches: Vec<&'a Event> = patches.into_iter().collect();
let series = pull_request_patches(pr, patches.iter().copied());
if series.is_empty() {
return pr.content.clone();
}
series
.iter()
.map(|patch| patch.content.as_str())
.collect::<Vec<_>>()
.join("\n")
}
/// The chain of patches replying to `root` (NIP-10 `e` tags), oldest first.
fn forward_series<'a>(root: &'a Event, patches: &[&'a Event]) -> Vec<&'a Event> {
let mut series = vec![root];
loop {
let next = patches
.iter()
.filter(|patch| !series.contains(patch))
.filter(|patch| {
patch
.tags
.event_ids()
.any(|id| id == series.last().unwrap().id)
})
.max_by_key(|patch| patch.created_at);
let Some(next) = next else {
break;
};
series.push(next);
}
series
}
/// The `c` tag of an event (tip of the proposed branch), as hex.
fn current_commit_of(event: &Event) -> Option<String> {
event
.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::CurrentCommit(commit)) => Some(commit.to_string()),
_ => None,
})
}
/// Whether `patch` produces `commit` (its `commit` or `r` tag), so clients
/// can find existing patches for a specific commit.
fn patch_produces_commit(patch: &Event, commit: &str) -> bool {
patch
.tags
.iter()
.any(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Commit(c) | Nip34Tag::Reference(c)) => c.to_string() == commit,
_ => false,
})
}
impl Announcement {
@@ -30,45 +177,43 @@ impl Announcement {
return None;
}
let mut id: Option<String> = None;
let mut name: Option<String> = None;
let mut description: Option<String> = None;
let mut web: Vec<String> = Vec::new();
let mut clone: Vec<String> = Vec::new();
let mut relays: Vec<String> = Vec::new();
let id = event.tags.identifier()?;
let mut hashtags: Vec<String> = Vec::new();
hashtags.extend(event.tags.hashtags().map(|t| t.to_string()));
let mut name: Option<SharedString> = None;
let mut description: Option<SharedString> = None;
let mut web: Vec<Url> = Vec::new();
let mut clone: Vec<Url> = Vec::new();
let mut relays: Vec<RelayUrl> = Vec::new();
let mut euc: Option<String> = None;
let mut maintainers: Vec<PublicKey> = Vec::new();
let mut upstream: Option<String> = None;
for tag in event.tags.iter() {
let values: &[String] = tag.as_slice();
match tag.kind() {
"d" => id = tag.content().map(str::to_owned),
"name" => name = tag.content().map(str::to_owned),
"description" => description = tag.content().map(str::to_owned),
"web" => web.extend(values.iter().skip(1).cloned()),
"clone" => clone.extend(values.iter().skip(1).cloned()),
"relays" => relays.extend(values.iter().skip(1).cloned()),
"r" => {
if values.get(2).map(String::as_str) == Some("euc") {
euc = tag.content().map(str::to_owned);
}
}
"maintainers" => {
maintainers.extend(
values
.iter()
.skip(1)
.filter_map(|v| PublicKey::from_hex(v).ok()),
);
}
match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Name(value)) => name = Some(value.into()),
Ok(Nip34Tag::Description(value)) => description = Some(value.into()),
Ok(Nip34Tag::Web(urls)) => web.extend(urls),
Ok(Nip34Tag::Clone(urls)) => clone.extend(urls),
Ok(Nip34Tag::Relays(urls)) => relays.extend(urls),
Ok(Nip34Tag::EarliestUniqueCommitId(commit)) => euc = Some(commit.to_string()),
Ok(Nip34Tag::Maintainers(keys)) => maintainers.extend(keys),
_ => {}
}
// The `u` tag is not modelled by the SDK's `Nip34Tag`; parse it
// manually (first value wins).
if upstream.is_none() && tag.kind() == "u" {
upstream = tag.content().map(str::to_owned);
}
}
Some(Self {
owner: event.pubkey,
created_at: event.created_at,
id: id?,
id,
name,
description,
web,
@@ -76,11 +221,329 @@ impl Announcement {
relays,
euc,
maintainers,
upstream,
hashtags,
})
}
/// The repository address of this announcement.
pub fn addr(&self) -> crate::RepoAddr {
crate::RepoAddr::new(self.owner, self.id.clone())
crate::repo_addr(self.owner, self.id.clone())
}
/// The description of the repository, or a default if none is provided.
pub fn description(&self) -> SharedString {
self.description
.clone()
.unwrap_or(SharedString::from("No description"))
}
/// The effective maintainers of this repository: the announced
/// `maintainers` plus the announcement author, who asserts themselves as
/// a maintainer of the primary project unless a `u` tag marks this
/// repository as a subordinate fork (NIP-34).
pub fn effective_maintainers(&self) -> Vec<PublicKey> {
let mut maintainers = self.maintainers.clone();
if self.upstream.is_none() && !maintainers.contains(&self.owner) {
maintainers.push(self.owner);
}
maintainers
}
}
#[cfg(test)]
mod tests {
use super::*;
const MAINTAINER_HEX: &str = "68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272";
fn keys() -> Keys {
Keys::new(
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
.expect("valid secret key"),
)
}
/// Build a signed kind `30617` event from raw tag values.
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 requires_d_tag() {
let event = announcement_event(&[&["name", "No id"]]);
assert!(Announcement::from_event(&event).is_none());
}
#[test]
fn ignores_other_kinds() {
let event = EventBuilder::new(Kind::GitIssue, "")
.finalize(&keys())
.expect("signed event");
assert!(Announcement::from_event(&event).is_none());
}
#[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");
// An invalid URL keeps the whole clone tag from being parsed.
assert!(announcement.clone.is_empty());
assert_eq!(
announcement.relays,
vec![RelayUrl::parse("wss://good.example.com").unwrap()]
);
assert!(announcement.maintainers.is_empty());
}
#[test]
fn ignores_unknown_tags() {
let event = announcement_event(&[&["d", "my-repo"], &["t", "label"], &["subject", "n/a"]]);
let announcement = Announcement::from_event(&event).expect("parses");
assert_eq!(announcement.id, "my-repo");
assert!(announcement.name.is_none());
assert!(announcement.web.is_empty());
}
#[test]
fn parses_upstream_tag() {
let event = announcement_event(&[
&["d", "my-fork"],
&["u", "30617:abc:upstream|https://example.com/upstream.git"],
]);
let announcement = Announcement::from_event(&event).expect("parses");
assert_eq!(
announcement.upstream.as_deref(),
Some("30617:abc:upstream|https://example.com/upstream.git")
);
}
#[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();
// The owner asserts themselves as a maintainer of the primary
// project (NIP-34), alongside the announced co-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();
// A `u` tag marks the repository as a subordinate fork: the author
// is not a maintainer of the primary project (NIP-34).
assert!(!maintainers.contains(&announcement.owner));
assert_eq!(
maintainers,
vec![PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")]
);
}
/// Build a signed PR event with the given tags and content.
fn pr_event(content: &str, tags: Vec<Tag>) -> Event {
EventBuilder::new(Kind::GitPullRequest, content)
.tags(tags)
.finalize(&keys())
.expect("signed event")
}
#[test]
fn pull_request_patch_prefers_linked_patch_event() {
let patch = EventBuilder::new(Kind::GitPatch, "patch-content")
.finalize(&keys())
.expect("signed event");
let pr = pr_event("description", vec![Tag::event(patch.id)]);
assert_eq!(pull_request_patch(&pr, [&patch]), "patch-content");
}
#[test]
fn pull_request_patch_falls_back_to_inline_content() {
// Older PRs carried the patch in the content; no linked patch event.
let pr = pr_event("patch-inline", vec![]);
assert_eq!(pull_request_patch(&pr, [] as [&Event; 0]), "patch-inline");
}
#[test]
fn pull_request_patch_ignores_unrelated_patch_events() {
let patch = EventBuilder::new(Kind::GitPatch, "patch-content")
.finalize(&keys())
.expect("signed event");
let pr = pr_event("description", vec![]);
assert_eq!(pull_request_patch(&pr, [&patch]), "description");
}
/// Build a signed patch event with a controlled `created_at`.
fn patch_event(content: &str, tags: Vec<Tag>, created_at: u64) -> Event {
EventBuilder::new(Kind::GitPatch, 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() {
// NIP-34: a PR references the root patch; later patches of the set
// reply to the previous one (NIP-10 `e` tags).
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!(
pull_request_patch(&pr, [&root, &second]),
"patch-one\npatch-two"
);
assert_eq!(
pull_request_patches(&pr, [&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 = pull_request_patches(&pr, [&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_ignores_unrelated_replies() {
let root = patch_event("patch-one", vec![], 100);
let other = patch_event("other-patch", vec![Tag::event(root.id)], 250);
// A patch replying to a different root is not part of the set.
let stranger = patch_event("stranger", vec![], 150);
let pr = pr_event("description", vec![Tag::event(root.id)]);
let series = pull_request_patches(&pr, [&root, &other, &stranger]);
assert_eq!(
series
.iter()
.map(|p| p.content.as_str())
.collect::<Vec<_>>(),
vec!["patch-one", "other-patch"]
);
}
#[test]
fn pull_request_patches_finds_the_set_via_the_tip_commit() {
// PRs without an `e` tag: the last patch of the set carries the tip
// commit in its `r` tag; walk the reply chain backward to the root.
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 = pull_request_patches(&pr, [&root, &last]);
assert_eq!(
series
.iter()
.map(|p| p.content.as_str())
.collect::<Vec<_>>(),
vec!["patch-one", "patch-two"]
);
}
}
+146
View File
@@ -0,0 +1,146 @@
use nostr::prelude::*;
/// Build a kind `30618` repository state event from refs and HEAD.
///
/// `refs` are `(refname, commit-id)` pairs (e.g. `refs/heads/main`); `head`
/// is the short branch name HEAD points to, published as
/// `ref: refs/heads/<branch>`. The `d` tag matches the repository id.
pub fn build_state(id: &str, refs: &[(String, String)], head: Option<&str>) -> EventBuilder {
let mut tags: Vec<Tag> = vec![Tag::identifier(id.to_owned())];
for (name, commit) in refs {
tags.push(Tag::parse([name.as_str(), commit.as_str()]).expect("valid ref tag"));
}
if let Some(head) = head {
tags.push(
Tag::parse(["HEAD", &format!("ref: refs/heads/{head}")]).expect("valid HEAD tag"),
);
}
EventBuilder::new(Kind::RepoState, "").tags(tags)
}
/// Parse a kind `30618` repository state event into refs and HEAD.
///
/// `refs` are `(refname, commit-id)` pairs; `head` is the branch pointed to
/// by the `HEAD` tag, if any.
pub fn parse_state(event: &Event) -> (Vec<(String, String)>, Option<String>) {
let mut refs = Vec::new();
let mut head = None;
for tag in event.tags.iter() {
match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Head(branch)) => head = Some(branch),
Ok(Nip34Tag::RefHead { branch, commit }) => {
refs.push((format!("refs/heads/{branch}"), commit.to_string()));
}
Ok(Nip34Tag::RefTag { name, commit }) => {
refs.push((format!("refs/tags/{name}"), commit.to_string()));
}
_ => {}
}
}
(refs, head)
}
#[cfg(test)]
mod tests {
use super::*;
const COMMIT_A: &str = "aa231c4c6a5777dc89b42207b499891a344add5c";
const COMMIT_B: &str = "59429cfc6cb35b0a1ddace73b5a5c5ed57b8f5ca";
fn keys() -> Keys {
Keys::new(
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
.expect("valid secret key"),
)
}
/// Build a signed kind `30618` event from raw tag values.
fn state_event(tags: &[&[&str]]) -> Event {
let tags: Vec<Tag> = tags
.iter()
.map(|t| Tag::parse(t.to_vec()).expect("valid tag"))
.collect();
EventBuilder::new(Kind::RepoState, "")
.tags(tags)
.finalize(&keys())
.expect("signed event")
}
#[test]
fn parses_heads_and_tags() {
let event = state_event(&[
&["HEAD", "ref: refs/heads/main"],
&["refs/heads/main", COMMIT_A],
&["refs/heads/dev", COMMIT_B],
&["refs/tags/v1.0", COMMIT_A],
]);
let (refs, head) = parse_state(&event);
assert_eq!(head.as_deref(), Some("main"));
assert_eq!(
refs,
vec![
("refs/heads/main".to_owned(), COMMIT_A.to_owned()),
("refs/heads/dev".to_owned(), COMMIT_B.to_owned()),
("refs/tags/v1.0".to_owned(), COMMIT_A.to_owned()),
]
);
}
#[test]
fn head_without_prefix_is_ignored() {
let event = state_event(&[&["HEAD", "main"]]);
let (refs, head) = parse_state(&event);
assert!(refs.is_empty());
assert!(head.is_none());
}
#[test]
fn ignores_non_state_tags() {
let event = state_event(&[&["d", "my-repo"], &["name", "ignored"]]);
let (refs, head) = parse_state(&event);
assert!(refs.is_empty());
assert!(head.is_none());
}
#[test]
fn build_state_round_trips_through_parse() {
let refs = [
("refs/heads/main".to_owned(), COMMIT_A.to_owned()),
("refs/heads/dev".to_owned(), COMMIT_B.to_owned()),
("refs/tags/v1.0".to_owned(), COMMIT_A.to_owned()),
];
let event = build_state("my-repo", &refs, Some("main"))
.finalize(&keys())
.expect("signed event");
assert_eq!(event.kind, Kind::RepoState);
assert_eq!(event.tags.identifier().as_deref(), Some("my-repo"));
let (parsed_refs, head) = parse_state(&event);
assert_eq!(parsed_refs, refs);
assert_eq!(head.as_deref(), Some("main"));
}
#[test]
fn build_state_omits_head_when_detached() {
let refs = [("refs/heads/main".to_owned(), COMMIT_A.to_owned())];
let event = build_state("my-repo", &refs, None)
.finalize(&keys())
.expect("signed event");
let (parsed_refs, head) = parse_state(&event);
assert_eq!(parsed_refs, refs);
assert!(head.is_none());
}
}
+156 -3
View File
@@ -30,13 +30,15 @@ impl RepoStatus {
}
}
/// Check whether a status event references the given root event via an `e` tag.
/// Check whether an event references the given root event via an `e` or `E`
/// tag. NIP-10 / NIP-34 use the lowercase `e` tag; NIP-22 comments (kind
/// `1111`) use the uppercase `E` tag for the root of the thread.
pub fn references_root(event: &Event, root: &EventId) -> bool {
let root_hex: String = root.to_hex();
let root = root.to_hex();
event
.tags
.iter()
.any(|t| t.kind() == "e" && t.content() == Some(root_hex.as_str()))
.any(|tag| matches!(tag.kind(), "e" | "E") && tag.content() == Some(root.as_str()))
}
/// Resolve the status of a root event per NIP-34:
@@ -58,3 +60,154 @@ where
.and_then(|e| RepoStatus::from_kind(e.kind))
.unwrap_or(RepoStatus::Open)
}
#[cfg(test)]
mod tests {
use super::*;
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")
}
/// Build a signed status event with a controlled `created_at`.
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!(references_root(&event, &root));
assert!(!references_root(
&event,
&EventId::from_hex(OTHER_ID_HEX).expect("valid id")
));
}
#[test]
fn references_root_matches_uppercase_e_tag() {
let root = root_event_id();
let event = EventBuilder::new(Kind::Comment, "")
.tags([Tag::parse(["E", ROOT_ID_HEX]).expect("valid E tag")])
.finalize(&keys_from_hex(
"0000000000000000000000000000000000000000000000000000000000000001",
))
.expect("signed event");
assert!(references_root(&event, &root));
assert!(!references_root(
&event,
&EventId::from_hex(OTHER_ID_HEX).expect("valid id")
));
}
#[test]
fn references_root_false_without_e_tags() {
let event = EventBuilder::new(Kind::GitStatusOpen, "")
.finalize(&keys_from_hex(
"0000000000000000000000000000000000000000000000000000000000000001",
))
.expect("signed event");
assert!(!references_root(&event, &root_event_id()));
}
#[test]
fn defaults_to_open_without_status_events() {
let owner =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let statuses: Vec<Event> = Vec::new();
assert_eq!(
resolve_status(
statuses.iter(),
&owner.public_key(),
&[maintainer.public_key()]
),
RepoStatus::Open
);
}
#[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!(
resolve_status(
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!(
resolve_status(
statuses.iter(),
&owner.public_key(),
&[maintainer.public_key()]
),
RepoStatus::Draft
);
}
#[test]
fn ignores_non_status_kinds() {
let owner =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
let root = root_event_id();
let statuses = [status_event(&owner, Kind::GitIssue, root, 100)];
assert_eq!(
resolve_status(statuses.iter(), &owner.public_key(), &[]),
RepoStatus::Open
);
}
}