feat: detect local grasp repositories (#21)
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s

Reviewed-on: #21
This commit was merged in pull request #21.
This commit is contained in:
2026-09-14 04:06:10 +00:00
parent a74c166391
commit 5e6156066a
16 changed files with 1174 additions and 281 deletions
+21 -1
View File
@@ -7,10 +7,11 @@ use anyhow::{Error, anyhow, bail};
use bitcoin_hashes::sha1::Hash as Sha1Hash;
use gpui::{App, AppContext, BackgroundExecutor, Context, Entity, EventEmitter, Global, Task};
use nostr::event::IntoEventBuilder;
use nostr::nips::nip19::Nip19Coordinate;
use nostr_connect::prelude::*;
use nostr_sdk::client::SyncSummary;
use nostr_sdk::prelude::*;
use signed_core::{Announcement, RepoAddr, build_state, filters, identifier_from_name};
use signed_core::{Announcement, RepoAddr, build_state, filters, identifier_from_name, repo_addr};
use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update};
use crate::git_store::repo_mirror_path;
@@ -743,6 +744,25 @@ impl Backend {
.await;
}
// Record the ngit-compatible `nostr.repo` marker,
// so the next scan detects the repository instead of offering to publish it again.
let coordinate = repo_addr(event.pubkey, repo_id.clone());
match Nip19Coordinate::new(coordinate, servers.clone()).to_bech32() {
Ok(naddr) => {
let path = path.clone();
cx.background_spawn(async move {
if let Err(error) = signed_git::set_nostr_repo(&path, &naddr) {
log::warn!(
"failed to record the NIP-34 marker for {}: {error}",
path.display()
);
}
})
.await;
}
Err(error) => log::warn!("failed to encode the repository coordinate: {error}"),
}
Announcement::from_event(&event).ok_or_else(|| anyhow!("failed to parse announcement"))
})
}
+5 -2
View File
@@ -10,8 +10,9 @@ use signed_core::{Announcement, RepoAddr};
use crate::backend::{Backend, BackendEvent};
use crate::git_store::repo_mirror_root;
use crate::local_repos::LocalReposStore;
use crate::refresh::{RefreshGate, RefreshRequest};
use crate::repos::{LocalReposStore, RepoListStore};
use crate::repos::RepoListStore;
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
@@ -349,7 +350,9 @@ impl CheckoutsStore {
//
// The facts are the origin URL and the root commit, both CLI reads.
let mut facts: Vec<(PathBuf, Option<String>, Option<String>)> = Vec::new();
for path in scanned.iter() {
for scanned in scanned.iter() {
let path = &scanned.path;
// The browser's mirror clones share the announce URLs and EUCs. They are not user checkouts.
if cache_root
.as_ref()
+4 -1
View File
@@ -2,6 +2,7 @@ mod backend;
mod checkouts;
mod git_store;
mod inbox;
mod local_repos;
mod profile;
mod refresh;
mod repo;
@@ -15,11 +16,13 @@ use git_store::set_git_cache;
pub use git_store::{ensure_repo_mirror, open_repo_mirror, repo_mirror_path};
use gpui::{App, AppContext};
pub use inbox::{Inbox, query_inbox};
pub use local_repos::{LocalReposStore, ResolvedLocalRepo, local_repo_addr, resolve_local_repos};
pub use nostr_sdk::prelude::Timestamp;
pub use profile::{Profile, ProfileStore};
pub use refresh::{RefreshGate, RefreshRequest};
pub use repo::RepoStore;
pub use repos::{LocalReposStore, RepoActivityCounts, RepoListStore};
pub use repos::{RepoActivityCounts, RepoListStore};
pub use signed_git::{GraspSignals, LocalRepo, Nip34Binding, Nip34Kind};
use signed_nostr::new_backend;
#[cfg(not(target_arch = "wasm32"))]
+290
View File
@@ -0,0 +1,290 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::Error;
use gpui::{App, AppContext, Context, Entity, Global, SharedString, Task};
use signed_core::{Announcement, RepoAddr, repo_addr};
use signed_git::{LocalRepo, Nip34Binding, find_git_repos};
struct GlobalLocalReposStore(Entity<LocalReposStore>);
impl Global for GlobalLocalReposStore {}
/// Store of the git repositories discovered under a set of scan paths.
pub struct LocalReposStore {
pub roots: Arc<Vec<PathBuf>>,
/// Git repositories discovered under [`Self::roots`], sorted by path.
pub repos: Arc<Vec<LocalRepo>>,
pub scanning: bool,
scan_dirty: bool,
}
impl LocalReposStore {
pub fn global(cx: &App) -> Entity<Self> {
cx.global::<GlobalLocalReposStore>().0.clone()
}
pub(crate) fn set_global(entity: Entity<Self>, cx: &mut App) {
cx.set_global(GlobalLocalReposStore(entity));
}
pub fn new(roots: Vec<PathBuf>, cx: &mut Context<Self>) -> Self {
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.rescan(cx)) {
log::warn!("local repos store dropped before initial scan could run: {error}");
}
});
Self {
roots: Arc::new(roots),
repos: Arc::new(Vec::new()),
scanning: false,
scan_dirty: false,
}
}
/// Forget a repository that has just been published to NIP-34.
pub fn remove(&mut self, path: &Path, cx: &mut Context<Self>) {
self.repos = Arc::new(
self.repos
.iter()
.filter(|repo| repo.path.as_path() != path)
.cloned()
.collect(),
);
cx.notify();
}
pub fn rescan(&mut self, cx: &mut Context<Self>) {
if self.scanning {
self.scan_dirty = true;
return;
}
if self.roots.is_empty() {
return;
}
self.scanning = true;
cx.notify();
let roots = self.roots.clone();
let work = cx.background_spawn(async move {
let mut repos = Vec::new();
for root in roots.iter() {
repos.extend(find_git_repos(root));
}
repos.sort_by(|a, b| a.path.cmp(&b.path));
repos.dedup_by(|a, b| a.path == b.path);
repos
});
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let repos = work.await;
let again = this.update(cx, |this, cx| {
this.repos = Arc::new(repos);
this.scanning = false;
cx.notify();
let dirty = this.scan_dirty;
this.scan_dirty = false;
dirty
})?;
// Scans requested while this one ran are coalesced into one follow-up scan.
if again {
this.update(cx, |this, cx| this.rescan(cx))?;
}
Ok(())
});
task.detach();
}
}
/// The NIP-34 coordinate a repository's detection resolved, when both the owner
/// and the identifier were recovered.
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(repo_addr(owner, identifier))
}
/// A scanned repository resolved against the known announcements.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedLocalRepo {
pub path: PathBuf,
/// `None` for a plain repository.
pub nip34: Option<Nip34Binding>,
/// The known announcement this repository is bound to, when one matched.
pub announcement: Option<Announcement>,
}
impl ResolvedLocalRepo {
/// The repository's directory name, or `Untitled` when the path has none.
pub fn name(&self) -> SharedString {
self.path
.file_name()
.map(|name| SharedString::from(name.to_string_lossy().into_owned()))
.unwrap_or_else(|| SharedString::from("Untitled"))
}
}
/// Resolve the scanned repositories against the known announcements.
pub fn resolve_local_repos(
repos: &[LocalRepo],
known: &[Announcement],
own: &[Announcement],
) -> Vec<ResolvedLocalRepo> {
let shown: HashSet<RepoAddr> = own.iter().map(Announcement::addr).collect();
repos
.iter()
.filter_map(|repo| {
let addr = local_repo_addr(repo);
if let Some(addr) = &addr
&& shown.contains(addr)
{
return None;
}
let announcement = addr
.as_ref()
.and_then(|addr| {
known
.iter()
.find(|announcement| announcement.addr() == *addr)
})
.cloned();
Some(ResolvedLocalRepo {
path: repo.path.clone(),
nip34: repo.nip34.clone(),
announcement,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use nostr::prelude::*;
use signed_git::{GraspSignals, Nip34Kind};
use super::*;
const KEY: &str = "0000000000000000000000000000000000000000000000000000000000000001";
const OTHER_KEY: &str = "0000000000000000000000000000000000000000000000000000000000000002";
fn announcement(secret: &str, id: &str) -> Announcement {
let keys = Keys::new(SecretKey::from_hex(secret).expect("secret"));
let tag = Tag::parse(vec!["d", id]).expect("tag");
let event = EventBuilder::new(Kind::GitRepoAnnouncement, "")
.tags(vec![tag])
.finalize(&keys)
.expect("signed");
Announcement::from_event(&event).expect("parsed")
}
fn owner(secret: &str) -> PublicKey {
Keys::new(SecretKey::from_hex(secret).expect("secret")).public_key()
}
fn bound(secret: &str, id: &str) -> LocalRepo {
let binding = Nip34Binding {
kind: Nip34Kind::Initialized,
signals: GraspSignals {
nip34_json: true,
..Default::default()
},
owner: Some(owner(secret)),
identifier: Some(id.to_owned()),
grasp_urls: Vec::new(),
};
LocalRepo {
path: PathBuf::from(id),
nip34: Some(binding),
}
}
#[test]
fn the_users_own_announcement_is_dropped() {
let own = announcement(KEY, "mine");
let repo = bound(KEY, "mine");
let own = std::slice::from_ref(&own);
assert!(resolve_local_repos(&[repo], own, own).is_empty());
}
#[test]
fn another_owners_announcement_is_linked_and_kept() {
let known = announcement(OTHER_KEY, "theirs");
let repo = bound(OTHER_KEY, "theirs");
let resolved = resolve_local_repos(&[repo], std::slice::from_ref(&known), &[]);
assert_eq!(resolved.len(), 1);
assert_eq!(resolved[0].announcement.as_ref(), Some(&known));
}
#[test]
fn an_unmatched_repository_keeps_its_binding() {
let repo = bound(KEY, "unlisted");
let resolved = resolve_local_repos(&[repo], &[], &[]);
assert_eq!(resolved.len(), 1);
assert!(resolved[0].announcement.is_none());
assert_eq!(
resolved[0].nip34.as_ref().map(|binding| binding.kind),
Some(Nip34Kind::Initialized)
);
}
#[test]
fn a_plain_repository_is_kept_without_a_binding() {
let repo = LocalRepo {
path: PathBuf::from("plain"),
nip34: None,
};
let resolved = resolve_local_repos(&[repo], &[], &[]);
assert_eq!(resolved.len(), 1);
assert!(resolved[0].nip34.is_none());
assert!(resolved[0].announcement.is_none());
}
#[test]
fn the_name_is_the_directory_name() {
let repo = LocalRepo {
path: PathBuf::from("/tmp/my-repo"),
nip34: None,
};
let resolved = resolve_local_repos(&[repo], &[], &[]);
assert_eq!(resolved[0].name(), SharedString::from("my-repo"));
}
#[test]
fn a_path_without_a_directory_name_is_untitled() {
let repo = LocalRepo {
path: PathBuf::from("/"),
nip34: None,
};
let resolved = resolve_local_repos(&[repo], &[], &[]);
assert_eq!(resolved[0].name(), SharedString::from("Untitled"));
}
}
+18 -1
View File
@@ -11,6 +11,7 @@ use signed_core::{
Announcement, Deletions, RepoAddr, RepoStatus, filters, parse_state, pull_request_patch,
pull_request_patches,
};
use signed_git::Nip34Binding;
use crate::backend::{
Backend, BackendEvent, grasp_base_url, grasp06_prs_url, pr_clone_urls, require_relay_accepted,
@@ -39,6 +40,8 @@ pub struct RepoStore {
/// Local working copy. The scan path for a local repository, kept when it is
/// later announced so the panel keeps its worktree.
pub path: Option<PathBuf>,
/// NIP-34 state detected on disk for a local repository, if any.
pub nip34: Option<Nip34Binding>,
/// The first local pass has been applied.
///
/// Views distinguish "no data yet" from a genuinely empty repository with it.
@@ -112,6 +115,7 @@ impl RepoStore {
addr: Some(addr),
announcement: hint,
path: None,
nip34: None,
loaded: false,
head: None,
issues: Vec::new(),
@@ -134,11 +138,12 @@ impl RepoStore {
}
/// Local repository discovered by the scan, not announced to NIP-34 yet.
pub fn new_local(path: PathBuf) -> Self {
pub fn new_local(path: PathBuf, nip34: Option<Nip34Binding>) -> Self {
Self {
addr: None,
announcement: None,
path: Some(path),
nip34,
loaded: true,
head: None,
issues: Vec::new(),
@@ -160,6 +165,18 @@ impl RepoStore {
}
}
/// An announced repository whose working copy is already on disk.
pub fn from_worktree(
addr: RepoAddr,
announcement: Announcement,
path: PathBuf,
cx: &mut Context<Self>,
) -> Self {
let mut store = Self::new(addr, Some(announcement), cx);
store.path = Some(path);
store
}
/// Switch a local repository to its NIP-34 mode, keeping its path.
pub fn announce(&mut self, announcement: Announcement, cx: &mut Context<Self>) {
self.addr = Some(announcement.addr());
+1 -102
View File
@@ -1,116 +1,15 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use anyhow::Error;
use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task};
use gpui::{App, AppContext, Context, Entity, Global, Subscription};
use nostr_sdk::prelude::*;
use signed_core::{Announcement, Deletions, RepoAddr, filters, repo_addr};
use signed_git::find_git_repos;
use crate::backend::{Backend, BackendEvent};
use crate::refresh::{RefreshGate, RefreshRequest};
struct GlobalLocalReposStore(Entity<LocalReposStore>);
impl Global for GlobalLocalReposStore {}
/// Store of the git repositories discovered under a set of scan paths.
pub struct LocalReposStore {
pub roots: Arc<Vec<PathBuf>>,
/// Git repositories discovered under [`Self::roots`], sorted by path.
pub repos: Arc<Vec<PathBuf>>,
pub scanning: bool,
scan_dirty: bool,
}
impl LocalReposStore {
pub fn global(cx: &App) -> Entity<Self> {
cx.global::<GlobalLocalReposStore>().0.clone()
}
pub(crate) fn set_global(entity: Entity<Self>, cx: &mut App) {
cx.set_global(GlobalLocalReposStore(entity));
}
pub fn new(roots: Vec<PathBuf>, cx: &mut Context<Self>) -> Self {
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.rescan(cx)) {
log::warn!("local repos store dropped before initial scan could run: {error}");
}
});
Self {
roots: Arc::new(roots),
repos: Arc::new(Vec::new()),
scanning: false,
scan_dirty: false,
}
}
/// Forget a repository that has just been published to NIP-34.
pub fn remove(&mut self, path: &Path, cx: &mut Context<Self>) {
self.repos = Arc::new(
self.repos
.iter()
.filter(|repo| repo.as_path() != path)
.cloned()
.collect(),
);
cx.notify();
}
pub fn rescan(&mut self, cx: &mut Context<Self>) {
if self.scanning {
self.scan_dirty = true;
return;
}
if self.roots.is_empty() {
return;
}
self.scanning = true;
cx.notify();
let roots = self.roots.clone();
let work = cx.background_spawn(async move {
let mut repos = Vec::new();
for root in roots.iter() {
repos.extend(find_git_repos(root));
}
repos.sort();
repos.dedup();
repos
});
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let repos = work.await;
let again = this.update(cx, |this, cx| {
this.repos = Arc::new(repos);
this.scanning = false;
cx.notify();
let dirty = this.scan_dirty;
this.scan_dirty = false;
dirty
})?;
// Scans requested while this one ran are coalesced into one follow-up scan.
if again {
this.update(cx, |this, cx| this.rescan(cx))?;
}
Ok(())
});
task.detach();
}
}
/// How far back activity events count toward a repository's last activity.
const ACTIVITY_WINDOW: Duration = Duration::from_secs(90 * 86_400);