diff --git a/CHANGELOG.md b/CHANGELOG.md index 82208b8..3b37b07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Changed +- Publishing a local repository now also writes a `nak git` compatible `nip34.json` into it, kept out of the repository through `.git/info/exclude` - Show a pull request's description, commits and changes in one scrollable main panel, and its discussion with a pinned comment form in the split pane - Show the repository owner's avatar and the pull request title in a pull request's tab - Show each pull request commit's id, title and changed line counts on one row diff --git a/crates/signed_git/src/lib.rs b/crates/signed_git/src/lib.rs index e2face8..3cd8aa1 100644 --- a/crates/signed_git/src/lib.rs +++ b/crates/signed_git/src/lib.rs @@ -11,7 +11,7 @@ mod worktree; pub use cache::GitCache; pub use diff::{CommitDiff, DiffHunk, DiffLine, DiffLineKind, DiffStatus, FileDiff}; pub use history::{CommitList, FileCommit, MAX_LISTED_COMMITS}; -pub use nip34::{GraspSignals, Nip34Binding, Nip34Kind}; +pub use nip34::{GraspSignals, Nip34Binding, Nip34Kind, Nip34Metadata}; pub use patch::PatchParser; pub use repo::{Repo, RepoRefState}; pub use scan::LocalRepo; diff --git a/crates/signed_git/src/nip34.rs b/crates/signed_git/src/nip34.rs index 8106d71..a8768fd 100644 --- a/crates/signed_git/src/nip34.rs +++ b/crates/signed_git/src/nip34.rs @@ -1,4 +1,6 @@ +use anyhow::Result; use nostr::prelude::*; +use signed_core::Announcement; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Nip34Kind { @@ -61,3 +63,36 @@ impl Nip34Binding { } } } + +/// A repository's `nip34.json`, the local metadata `nak git` keeps. +#[derive(serde::Serialize)] +pub struct Nip34Metadata { + pub identifier: String, + pub name: String, + pub description: String, + /// The owner's public key, encoded as `npub`. + pub owner: String, + /// Grasp server hostnames. + #[serde(rename = "grasp-servers")] + pub grasp_servers: Vec, + #[serde(rename = "earliest-unique-commit")] + pub earliest_unique_commit: String, +} + +impl Nip34Metadata { + /// The metadata of an announced repository. + pub fn from_announcement(announcement: &Announcement) -> Result { + Ok(Self { + identifier: announcement.id.clone(), + name: announcement.name.clone().unwrap_or_default(), + description: announcement.description.clone().unwrap_or_default(), + owner: announcement.owner.to_bech32()?, + grasp_servers: announcement + .relays + .iter() + .filter_map(|relay| relay.domain().map(str::to_owned)) + .collect(), + earliest_unique_commit: announcement.euc.clone().unwrap_or_default(), + }) + } +} diff --git a/crates/signed_git/src/repo.rs b/crates/signed_git/src/repo.rs index 062b417..0f12686 100644 --- a/crates/signed_git/src/repo.rs +++ b/crates/signed_git/src/repo.rs @@ -12,7 +12,7 @@ use nostr::prelude::*; use crate::GixResultExt as _; use crate::diff::{CommitDiff, DiffStatus, FileDiff, HunkCollector, PatchCollector}; use crate::history::{CommitList, FileCommit, MAX_LISTED_COMMITS}; -use crate::nip34::{GraspSignals, Nip34Binding, Nip34Json, Nip34Kind}; +use crate::nip34::{GraspSignals, Nip34Binding, Nip34Json, Nip34Kind, Nip34Metadata}; use crate::sync::{RefSync, RepoSyncStatus}; use crate::worktree::WorktreeSnapshot; @@ -1846,6 +1846,42 @@ impl Repo { }) } + /// Writes `nak`'s `nip34.json` into the worktree and keeps the file out of the repository. + pub fn write_nip34_json(&self, metadata: &Nip34Metadata) -> Result<()> { + let workdir = self + .inner + .workdir() + .ok_or_else(|| anyhow::anyhow!("the repository has no worktree"))?; + + let json = serde_json::to_string_pretty(metadata)?; + std::fs::write(workdir.join("nip34.json"), json)?; + + let exclude = self.inner.common_dir().join("info").join("exclude"); + let mut content = match std::fs::read_to_string(&exclude) { + Ok(content) => content, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(), + Err(error) => return Err(error.into()), + }; + + if content.lines().any(|line| line.trim() == "nip34.json") { + return Ok(()); + } + + if !content.is_empty() && !content.ends_with('\n') { + content.push('\n'); + } + + content.push_str("nip34.json\n"); + std::fs::create_dir_all( + exclude + .parent() + .ok_or_else(|| anyhow::anyhow!("invalid exclude path"))?, + )?; + std::fs::write(&exclude, content)?; + + Ok(()) + } + /// Matches grasp URLs by shape: two path segments with an npub owner. /// /// Returns whether a URL has the grasp server clone shape. diff --git a/crates/signed_git/tests/repo.rs b/crates/signed_git/tests/repo.rs index 590318f..1dcbd66 100644 --- a/crates/signed_git/tests/repo.rs +++ b/crates/signed_git/tests/repo.rs @@ -2,8 +2,10 @@ use std::path::{Path, PathBuf}; use std::process::Command; use nostr::prelude::*; -use signed_core::RepoAddr; -use signed_git::{DiffStatus, GitCache, LocalRepo, Nip34Binding, Nip34Kind, PatchParser, Repo}; +use signed_core::{Announcement, RepoAddr}; +use signed_git::{ + DiffStatus, GitCache, LocalRepo, Nip34Binding, Nip34Kind, Nip34Metadata, PatchParser, Repo, +}; #[test] fn blocks_parent_components() { @@ -1234,6 +1236,58 @@ fn the_written_nostr_repo_marker_is_detected() { assert_eq!(binding.identifier.as_deref(), Some("my-repo")); } +#[test] +fn written_nip34_json_matches_nak_and_stays_out_of_git() { + let (_dir, path) = init_repo(); + let owner = key(); + let announcement = Announcement { + event_id: EventId::from_hex( + "0000000000000000000000000000000000000000000000000000000000000000", + ) + .expect("event id"), + id: "my-repo".to_owned(), + owner, + created_at: Timestamp::now(), + name: Some("My Repo".to_owned()), + description: None, + web: Vec::new(), + clone: Vec::new(), + relays: vec![RelayUrl::parse("wss://relay.ngit.dev/").expect("relay")], + euc: Some("0123456789abcdef0123456789abcdef01234567".to_owned()), + maintainers: Vec::new(), + upstream: None, + hashtags: Vec::new(), + }; + let metadata = Nip34Metadata::from_announcement(&announcement).expect("metadata"); + + Repo::open(&path) + .expect("open") + .write_nip34_json(&metadata) + .expect("write"); + + let json: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(path.join("nip34.json")).expect("read")) + .expect("json"); + + assert_eq!( + json, + serde_json::json!({ + "identifier": "my-repo", + "name": "My Repo", + "description": "", + "owner": owner.to_bech32().expect("npub"), + "grasp-servers": ["relay.ngit.dev"], + "earliest-unique-commit": "0123456789abcdef0123456789abcdef01234567", + }) + ); + + let exclude = std::fs::read_to_string(path.join(".git/info/exclude")).expect("exclude"); + assert!(exclude.lines().any(|line| line == "nip34.json")); + + let status = git_in(&path, &["status", "--porcelain"]).expect("status"); + assert!(status.is_empty(), "{status}"); +} + #[test] fn nostr_remote_is_a_nip34_clone() { let (_dir, path) = init_repo(); diff --git a/crates/signed_state/src/backend.rs b/crates/signed_state/src/backend.rs index 8ba8311..f30ee09 100644 --- a/crates/signed_state/src/backend.rs +++ b/crates/signed_state/src/backend.rs @@ -1,5 +1,5 @@ use std::collections::HashSet; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -12,7 +12,7 @@ use nostr::nips::nip19::Nip19Coordinate; use nostr_connect::prelude::*; use nostr_sdk::prelude::*; use signed_core::{Announcement, Deletions, Filters, RepoAddr}; -use signed_git::{GitCache, Repo}; +use signed_git::{GitCache, Nip34Metadata, Repo}; use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update}; use crate::bootstrap::{ @@ -809,8 +809,6 @@ impl Backend { .await; } - // The ngit-compatible `nostr.repo` marker makes the next scan - // detect the repository instead of offering to publish it again. let coordinate = RepoAddr::new(event.pubkey, repo_id.clone()); match Nip19Coordinate::new(coordinate.into(), servers.clone()).to_bech32() { Ok(naddr) => { @@ -825,7 +823,27 @@ impl Backend { Err(error) => log::warn!("failed to encode the repository coordinate: {error}"), } - Announcement::from_event(&event).ok_or_else(|| anyhow!("failed to parse announcement")) + let announcement = Announcement::from_event(&event) + .ok_or_else(|| anyhow!("failed to parse announcement"))?; + + Self::write_nip34_json(&path, &announcement, cx).await; + + Ok(announcement) + }) + } + + /// Records the announcement in `nak`'s `nip34.json`, which keeps itself out of the repository. + fn write_nip34_json(path: &Path, announcement: &Announcement, cx: &mut AsyncApp) -> Task<()> { + let metadata = Nip34Metadata::from_announcement(announcement); + let path = path.to_path_buf(); + + cx.background_spawn(async move { + let written = + metadata.and_then(|metadata| Repo::open(&path)?.write_nip34_json(&metadata)); + + if let Err(error) = written { + log::warn!("failed to write nip34.json: {error:#}"); + } }) }