feat: detect local grasp repositories (#21)
Reviewed-on: #21
This commit was merged in pull request #21.
This commit is contained in:
@@ -8,6 +8,8 @@ publish.workspace = true
|
||||
signed_core = { path = "../signed_core" }
|
||||
|
||||
nostr.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
gix = { workspace = true, features = ["revision", "blob-diff"] }
|
||||
gix-worktree = "0.56"
|
||||
gix-worktree-state = "0.34"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod cache;
|
||||
mod diff;
|
||||
mod history;
|
||||
mod nip34;
|
||||
mod patch;
|
||||
mod remote;
|
||||
mod repo;
|
||||
@@ -19,6 +20,9 @@ pub use history::{
|
||||
CommitList, FileCommit, MAX_LISTED_COMMITS, all_commits, head_commit, worktree_all_commits,
|
||||
worktree_commit, worktree_commit_range_commits, worktree_last_commits,
|
||||
};
|
||||
pub use nip34::{
|
||||
GraspSignals, Nip34Binding, Nip34Kind, detect_nip34, is_grasp_url, set_nostr_repo,
|
||||
};
|
||||
pub use patch::{
|
||||
apply_patch, format_patch_between, patch_commits, patch_diffs, split_patch_series,
|
||||
};
|
||||
@@ -32,7 +36,7 @@ pub use repo::{
|
||||
repo_tags, root_commit, worktree_branches, worktree_current_branch, worktree_ref_exists,
|
||||
worktree_ref_state,
|
||||
};
|
||||
pub use scan::find_git_repos;
|
||||
pub use scan::{LocalRepo, find_git_repos};
|
||||
pub use worktree::{
|
||||
WorktreeSnapshot, find_readme, worktree_checkout_branch, worktree_checkout_tag,
|
||||
worktree_commits_ahead, worktree_dirty, worktree_entries, worktree_read, worktree_snapshot,
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use gix::bstr::ByteSlice;
|
||||
use nostr::prelude::*;
|
||||
|
||||
/// The kind of NIP-34 relationship a local repository has on disk.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Nip34Kind {
|
||||
/// Bound to a NIP-34 coordinate, by `nak`'s `nip34.json` or `ngit`'s `nostr.repo`.
|
||||
Initialized,
|
||||
/// Cloned from a `nostr://` remote but never initialized locally.
|
||||
Cloned,
|
||||
/// Nostr tooling touched the repository but no binding is recoverable.
|
||||
ToolingOnly,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct GraspSignals {
|
||||
pub nip34_json: bool,
|
||||
pub nip34_excluded: bool,
|
||||
pub nostr_repo_config: bool,
|
||||
pub nostr_remote: bool,
|
||||
pub grasp_remote: bool,
|
||||
/// `nip34_grasp_remote` is the `nak`-specific `nip34/grasp/<host>` remote name.
|
||||
pub nip34_grasp_remote: bool,
|
||||
pub nip34_state_refs: bool,
|
||||
pub nostr_cache: bool,
|
||||
pub nostr_aux_config: bool,
|
||||
pub maintainers_yaml: bool,
|
||||
}
|
||||
|
||||
impl GraspSignals {
|
||||
pub fn any(&self) -> bool {
|
||||
*self != Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a local repository's on-disk state says about its NIP-34 binding.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Nip34Binding {
|
||||
pub kind: Nip34Kind,
|
||||
pub signals: GraspSignals,
|
||||
/// Coordinate owner and identifier, from `nip34.json` or `nostr.repo`.
|
||||
pub owner: Option<PublicKey>,
|
||||
pub identifier: Option<String>,
|
||||
pub grasp_urls: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Nip34Json {
|
||||
identifier: Option<String>,
|
||||
owner: Option<String>,
|
||||
}
|
||||
|
||||
pub fn detect_nip34(repo_path: &Path) -> Option<Nip34Binding> {
|
||||
let repo = gix::open(repo_path).ok()?;
|
||||
let common_dir = repo.common_dir().to_path_buf();
|
||||
let workdir = repo.workdir().map(Path::to_path_buf);
|
||||
|
||||
let mut signals = GraspSignals::default();
|
||||
let mut owner: Option<PublicKey> = None;
|
||||
let mut identifier: Option<String> = None;
|
||||
let mut grasp_urls: Vec<String> = Vec::new();
|
||||
|
||||
if let Some(workdir) = &workdir {
|
||||
if let Ok(bytes) = std::fs::read(workdir.join("nip34.json"))
|
||||
&& let Ok(config) = serde_json::from_slice::<Nip34Json>(&bytes)
|
||||
{
|
||||
signals.nip34_json = true;
|
||||
identifier = config.identifier.and_then(non_empty);
|
||||
owner = config
|
||||
.owner
|
||||
.as_deref()
|
||||
.and_then(|value| PublicKey::parse(value).ok());
|
||||
}
|
||||
|
||||
if workdir.join("maintainers.yaml").is_file() {
|
||||
signals.maintainers_yaml = true;
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(exclude) = std::fs::read_to_string(common_dir.join("info/exclude"))
|
||||
&& exclude.contains("nip34.json")
|
||||
{
|
||||
signals.nip34_excluded = true;
|
||||
}
|
||||
|
||||
// `ngit` keeps its repository event cache in the Git common directory.
|
||||
if common_dir.join("nostr-cache.lmdb").is_file() {
|
||||
signals.nostr_cache = true;
|
||||
}
|
||||
|
||||
// `ngit` reads and writes `nostr.repo` at repository-local scope only.
|
||||
if let Ok(config) = gix::config::File::from_path_no_includes(
|
||||
common_dir.join("config"),
|
||||
gix::config::Source::Local,
|
||||
) {
|
||||
if let Some(value) = config.string("nostr.repo")
|
||||
&& let Some((key, id)) = coordinate_from_naddr(&value.to_str_lossy())
|
||||
{
|
||||
signals.nostr_repo_config = true;
|
||||
owner = Some(key);
|
||||
identifier = Some(id);
|
||||
}
|
||||
|
||||
for key in ["nostr.repo-relay-only", "nostr.nostate", "nostr.private"] {
|
||||
if config.string(key).is_some() {
|
||||
signals.nostr_aux_config = true;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(sections) = config.sections_by_name("remote") {
|
||||
for section in sections {
|
||||
let Some(name) = section.header().subsection_name() else {
|
||||
continue;
|
||||
};
|
||||
let nak_grasp_remote = name.to_str_lossy().starts_with("nip34/grasp/");
|
||||
|
||||
for url in section.values("url") {
|
||||
let url = url.to_str_lossy();
|
||||
|
||||
if url.starts_with("nostr://") {
|
||||
signals.nostr_remote = true;
|
||||
// Strong markers win; only fill an empty binding.
|
||||
if owner.is_none()
|
||||
&& identifier.is_none()
|
||||
&& let Some((key, id)) = parse_nostr_url(&url)
|
||||
{
|
||||
owner = Some(key);
|
||||
identifier = Some(id);
|
||||
}
|
||||
}
|
||||
|
||||
if is_grasp_url(&url) {
|
||||
signals.grasp_remote = true;
|
||||
signals.nip34_grasp_remote |= nak_grasp_remote;
|
||||
grasp_urls.push(url.to_string());
|
||||
|
||||
if owner.is_none()
|
||||
&& identifier.is_none()
|
||||
&& let Some((key, id)) = grasp_parts(&url)
|
||||
{
|
||||
owner = Some(key);
|
||||
identifier = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `nak` materializes a kind-30618 state as `refs/heads/nip34/state/*`.
|
||||
if let Ok(platform) = repo.references()
|
||||
&& let Ok(mut refs) = platform.prefixed(b"refs/heads/nip34/state/")
|
||||
&& refs.next().is_some()
|
||||
{
|
||||
signals.nip34_state_refs = true;
|
||||
}
|
||||
|
||||
if !signals.any() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let kind = if signals.nip34_json
|
||||
|| signals.nostr_repo_config
|
||||
|| signals.nip34_grasp_remote
|
||||
|| signals.nip34_state_refs
|
||||
{
|
||||
Nip34Kind::Initialized
|
||||
} else if signals.nostr_remote {
|
||||
Nip34Kind::Cloned
|
||||
} else {
|
||||
Nip34Kind::ToolingOnly
|
||||
};
|
||||
|
||||
Some(Nip34Binding {
|
||||
kind,
|
||||
signals,
|
||||
owner,
|
||||
identifier,
|
||||
grasp_urls,
|
||||
})
|
||||
}
|
||||
|
||||
/// Record a repository's NIP-34 coordinate in its local `nostr.repo` config.
|
||||
pub fn set_nostr_repo(repo_path: &Path, naddr: &str) -> Result<()> {
|
||||
let repo = gix::open(repo_path)?;
|
||||
|
||||
crate::remote::edit_local_config(&repo, |config| {
|
||||
config.set_raw_value("nostr.repo", naddr)?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Mirrors `nak`'s `IsGraspURL`: two path segments, a path of at least 65 bytes,
|
||||
/// and a first segment that decodes as an `npub`.
|
||||
pub fn is_grasp_url(url: &str) -> bool {
|
||||
let Ok(parsed) = Url::parse(url) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if !matches!(parsed.scheme(), "http" | "https" | "grasp") {
|
||||
return false;
|
||||
}
|
||||
|
||||
let path = parsed.path();
|
||||
if path.matches('/').count() != 2 || path.len() < 65 {
|
||||
return false;
|
||||
}
|
||||
|
||||
grasp_parts(url).is_some()
|
||||
}
|
||||
|
||||
fn grasp_parts(url: &str) -> Option<(PublicKey, String)> {
|
||||
let parsed = Url::parse(url).ok()?;
|
||||
let mut segments = parsed.path_segments()?.filter(|part| !part.is_empty());
|
||||
|
||||
let owner = PublicKey::parse(segments.next()?).ok()?;
|
||||
let identifier = non_empty(segments.next()?.trim_end_matches(".git"))?;
|
||||
|
||||
Some((owner, identifier))
|
||||
}
|
||||
|
||||
fn coordinate_from_naddr(value: &str) -> Option<(PublicKey, String)> {
|
||||
let coordinate = Nip19Coordinate::from_bech32(value).ok()?;
|
||||
if coordinate.kind != Kind::GitRepoAnnouncement {
|
||||
return None;
|
||||
}
|
||||
|
||||
let identifier = non_empty(coordinate.identifier.clone())?;
|
||||
Some((coordinate.public_key, identifier))
|
||||
}
|
||||
|
||||
/// Handles a bare `naddr`, an `npub`, and the optional `[ssh-key-file@]`,
|
||||
/// `[protocol/]` and `[relay/]` components. An `nip05` owner yields no binding.
|
||||
fn parse_nostr_url(url: &str) -> Option<(PublicKey, String)> {
|
||||
let rest = url.strip_prefix("nostr://")?;
|
||||
|
||||
if rest.starts_with("naddr1") {
|
||||
return coordinate_from_naddr(rest);
|
||||
}
|
||||
|
||||
let rest = rest.rsplit_once('@').map_or(rest, |(_, after)| after);
|
||||
let mut parts: Vec<&str> = rest.split('/').filter(|part| !part.is_empty()).collect();
|
||||
|
||||
if parts
|
||||
.first()
|
||||
.is_some_and(|first| matches!(*first, "ssh" | "https" | "http"))
|
||||
{
|
||||
parts.remove(0);
|
||||
}
|
||||
|
||||
// `[owner, (relay), identifier]`.
|
||||
if parts.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let owner = PublicKey::parse(parts[0]).ok()?;
|
||||
let identifier = non_empty(parts.last()?.trim_end_matches(".git"))?;
|
||||
|
||||
Some((owner, identifier))
|
||||
}
|
||||
|
||||
fn non_empty(value: impl Into<String>) -> Option<String> {
|
||||
let value = value.into();
|
||||
(!value.is_empty()).then_some(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::process::Command;
|
||||
|
||||
use super::*;
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
fn key() -> PublicKey {
|
||||
Keys::generate().public_key()
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_repository_has_no_binding() {
|
||||
let (_dir, path) = init_repo();
|
||||
assert!(detect_nip34(&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 = detect_nip34(&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!(detect_nip34(&path).is_none());
|
||||
}
|
||||
|
||||
#[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 = detect_nip34(&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 = detect_nip34(&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");
|
||||
|
||||
set_nostr_repo(&path, &naddr).expect("write marker");
|
||||
|
||||
let binding = detect_nip34(&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 = detect_nip34(&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 = detect_nip34(&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 = detect_nip34(&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!(is_grasp_url(&format!(
|
||||
"https://gitnostr.com/{npub}/my-repo.git"
|
||||
)));
|
||||
assert!(is_grasp_url(&format!(
|
||||
"grasp://gitnostr.com/{npub}/my-repo.git"
|
||||
)));
|
||||
|
||||
assert!(!is_grasp_url("https://gitnostr.com/my-repo.git"));
|
||||
assert!(!is_grasp_url(
|
||||
"https://gitnostr.com/not-a-pubkey/my-repo.git"
|
||||
));
|
||||
assert!(!is_grasp_url(&format!(
|
||||
"ssh://gitnostr.com/{npub}/my-repo.git"
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -252,10 +252,7 @@ pub fn set_origin(repo_path: &Path, url: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
/// Apply `edit` to the repository-local configuration and persist it.
|
||||
///
|
||||
/// The config file is locked while it is read, edited and written back,
|
||||
/// like git would when running `git config` or `git remote`.
|
||||
fn edit_local_config(
|
||||
pub(crate) fn edit_local_config(
|
||||
repo: &gix::Repository,
|
||||
edit: impl FnOnce(&mut gix::config::File) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
|
||||
@@ -2,12 +2,21 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use ignore::WalkBuilder;
|
||||
|
||||
use crate::nip34::{Nip34Binding, detect_nip34};
|
||||
|
||||
/// Caps nesting so pathological trees can't stall the scan.
|
||||
const SCAN_MAX_DEPTH: usize = 12;
|
||||
|
||||
/// Walk `root` recursively and collect the paths of git repositories below it.
|
||||
/// `.gitignore` and `.ignore` files are honoured.
|
||||
pub fn find_git_repos(root: &Path) -> Vec<PathBuf> {
|
||||
/// A git repository discovered under a scan root.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LocalRepo {
|
||||
pub path: PathBuf,
|
||||
/// `None` for a plain repository.
|
||||
pub nip34: Option<Nip34Binding>,
|
||||
}
|
||||
|
||||
/// Walk `root` recursively and collect the git repositories below it.
|
||||
pub fn find_git_repos(root: &Path) -> Vec<LocalRepo> {
|
||||
if !root.is_dir() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -38,4 +47,10 @@ pub fn find_git_repos(root: &Path) -> Vec<PathBuf> {
|
||||
}
|
||||
|
||||
roots
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
let nip34 = detect_nip34(&path);
|
||||
LocalRepo { path, nip34 }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -42,7 +42,10 @@ fn find_git_repos_discovers_repositories_recursively() {
|
||||
std::fs::create_dir_all(outer.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(outer.join("sub/other/.git")).unwrap();
|
||||
|
||||
let mut found = find_git_repos(root);
|
||||
let mut found: Vec<PathBuf> = find_git_repos(root)
|
||||
.into_iter()
|
||||
.map(|repo| repo.path)
|
||||
.collect();
|
||||
found.sort();
|
||||
|
||||
let mut expected = vec![
|
||||
|
||||
@@ -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"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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"))]
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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,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);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use gpui::prelude::*;
|
||||
use gpui::{App, Pixels, StyleRefinement, Window, div, px};
|
||||
use gpui_base::StyledExt;
|
||||
use gpui_component::{ActiveTheme, Colorize};
|
||||
use gpui_component::{ActiveTheme, Colorize, Sizable, Size};
|
||||
|
||||
/// Number of rows and columns in the pixel grid.
|
||||
const GRID_SIZE: usize = 8;
|
||||
@@ -10,34 +10,36 @@ const FILL_PROBABILITY: f32 = 0.42;
|
||||
/// Probability that a filled cell uses the accent shade instead of the main color.
|
||||
const ACCENT_PROBABILITY: f32 = 0.25;
|
||||
/// Minimum number of filled left-half cells.
|
||||
/// A sparse roll still yields a recognizable shape.
|
||||
/// Each left-half cell is mirrored to a right-half one.
|
||||
const MIN_FILLED: usize = 5;
|
||||
|
||||
/// Side length of the avatar in pixels, no setter.
|
||||
const AVATAR_SIZE: Pixels = px(16.);
|
||||
|
||||
/// A deterministic, offline pixel-art avatar.
|
||||
/// An 8×8 grid with horizontal mirror symmetry.
|
||||
/// Seeded from a stable string such as the repository id and owner public key.
|
||||
/// The same seed always renders the same avatar.
|
||||
#[derive(IntoElement)]
|
||||
pub struct PixelAvatar {
|
||||
seed: u64,
|
||||
size: Size,
|
||||
style: StyleRefinement,
|
||||
}
|
||||
|
||||
impl PixelAvatar {
|
||||
/// Create an avatar seeded from `seed`.
|
||||
///
|
||||
/// The seed should be a stable string unique to the entity the avatar represents.
|
||||
pub fn new(seed: impl AsRef<str>) -> Self {
|
||||
Self {
|
||||
seed: fnv1a(seed.as_ref().as_bytes()),
|
||||
size: Size::XSmall,
|
||||
style: StyleRefinement::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sizable for PixelAvatar {
|
||||
fn with_size(mut self, size: impl Into<Size>) -> Self {
|
||||
self.size = size.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Styled for PixelAvatar {
|
||||
fn style(&mut self) -> &mut StyleRefinement {
|
||||
&mut self.style
|
||||
@@ -48,16 +50,17 @@ impl RenderOnce for PixelAvatar {
|
||||
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let theme = cx.theme();
|
||||
let pattern = pattern(self.seed);
|
||||
let mut cells = Vec::new();
|
||||
|
||||
let hue = self.seed as f32 / u64::MAX as f32;
|
||||
let main = theme.blue.hue(hue);
|
||||
|
||||
let shade = if theme.is_dark() {
|
||||
main.lightness((main.l * 1.6).min(0.95))
|
||||
} else {
|
||||
main.lightness((main.l * 0.45).max(0.18))
|
||||
};
|
||||
|
||||
let mut cells = Vec::new();
|
||||
for row in 0..GRID_SIZE {
|
||||
for col in 0..GRID_SIZE {
|
||||
let value = pattern[row * GRID_SIZE + col];
|
||||
@@ -80,7 +83,7 @@ impl RenderOnce for PixelAvatar {
|
||||
.grid()
|
||||
.grid_cols(GRID_SIZE as u16)
|
||||
.grid_rows(GRID_SIZE as u16)
|
||||
.size(AVATAR_SIZE)
|
||||
.size(side_length(self.size))
|
||||
.flex_shrink_0()
|
||||
.overflow_hidden()
|
||||
.bg(main.opacity(0.16))
|
||||
@@ -88,9 +91,16 @@ impl RenderOnce for PixelAvatar {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate the 8×8 cell pattern for `seed`.
|
||||
/// Cells are `0` for empty, `1` for main color and `2` for accent shade.
|
||||
/// The right half mirrors the left half.
|
||||
fn side_length(size: Size) -> Pixels {
|
||||
match size {
|
||||
Size::XSmall => px(16.),
|
||||
Size::Small => px(24.),
|
||||
Size::Medium => px(48.),
|
||||
Size::Large => px(80.),
|
||||
Size::Size(size) => size,
|
||||
}
|
||||
}
|
||||
|
||||
fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
|
||||
let mut rng = PixelRng::new(seed);
|
||||
let mut pattern = [0u8; GRID_SIZE * GRID_SIZE];
|
||||
@@ -106,18 +116,19 @@ fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
|
||||
}
|
||||
}
|
||||
|
||||
// Sparse rolls can come out nearly empty.
|
||||
// Top the pattern up to the minimum fill, scanning from a seeded starting cell.
|
||||
if filled < MIN_FILLED {
|
||||
let half = GRID_SIZE * GRID_SIZE / 2;
|
||||
let start = (rng.next() % half as u64) as usize;
|
||||
|
||||
for offset in 0..half {
|
||||
if filled >= MIN_FILLED {
|
||||
break;
|
||||
}
|
||||
|
||||
let ix = (start + offset) % half;
|
||||
let row = ix / (GRID_SIZE / 2);
|
||||
let col = ix % (GRID_SIZE / 2);
|
||||
|
||||
if pattern[row * GRID_SIZE + col] == 0 {
|
||||
set_cell(&mut pattern, row, col, 1);
|
||||
filled += 1;
|
||||
|
||||
@@ -26,8 +26,9 @@ use nostr::prelude::{RelayUrl, ToBech32, Url};
|
||||
use signed_core::{Announcement, RepoAddr, RepoStatus};
|
||||
use signed_git::FileCommit;
|
||||
use signed_state::{
|
||||
Backend, CheckoutStatus, CheckoutsStore, LocalReposStore, ProfileStore, RepoListStore,
|
||||
RepoStore, ensure_repo_mirror, open_repo_mirror, pr_proposes_checkout,
|
||||
Backend, CheckoutStatus, CheckoutsStore, LocalReposStore, Nip34Binding, Nip34Kind,
|
||||
ProfileStore, RepoListStore, RepoStore, ensure_repo_mirror, open_repo_mirror,
|
||||
pr_proposes_checkout,
|
||||
};
|
||||
use signed_ui::{
|
||||
CountBadge, DropdownButton, PixelAvatar, UserAvatar, copy_row, menu_copy_row, middle_truncate,
|
||||
@@ -123,10 +124,26 @@ impl RepoDetailView {
|
||||
pub fn new_local(
|
||||
dock_area: WeakEntity<DockArea>,
|
||||
local_path: PathBuf,
|
||||
nip34: Option<Nip34Binding>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let store = cx.new(move |_cx| RepoStore::new_local(local_path));
|
||||
let store = cx.new(move |_cx| RepoStore::new_local(local_path, nip34));
|
||||
Self::new_common(dock_area, store, window, cx)
|
||||
}
|
||||
|
||||
/// A local repository whose detected binding matches an announcement.
|
||||
///
|
||||
/// Opens as the announced repository with the local worktree attached.
|
||||
pub fn new_local_announced(
|
||||
dock_area: WeakEntity<DockArea>,
|
||||
announcement: Announcement,
|
||||
local_path: PathBuf,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let addr = announcement.addr();
|
||||
let store = cx.new(move |cx| RepoStore::from_worktree(addr, announcement, local_path, cx));
|
||||
Self::new_common(dock_area, store, window, cx)
|
||||
}
|
||||
|
||||
@@ -294,24 +311,17 @@ impl RepoDetailView {
|
||||
self.error = None;
|
||||
cx.notify();
|
||||
|
||||
let (addr, announcement, local_path) = {
|
||||
let (announcement, local_path) = {
|
||||
let store = self.store.read(cx);
|
||||
(
|
||||
store.addr().cloned(),
|
||||
store.announcement.clone(),
|
||||
store.path.clone(),
|
||||
)
|
||||
(store.announcement.clone(), store.path.clone())
|
||||
};
|
||||
|
||||
// Local repositories live on disk at their scan path.
|
||||
// No clone step or network refresh applies here.
|
||||
if addr.is_none() {
|
||||
// A repository with a local worktree shows it directly. An announced one
|
||||
// still loads its announcement and activity from the store, which is
|
||||
// subscribed to the relays independently.
|
||||
if let Some(local_path) = local_path {
|
||||
self.repo_started = true;
|
||||
|
||||
let Some(local_path) = local_path else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: gpui::Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||
let data = cx
|
||||
.background_spawn(async move {
|
||||
@@ -1254,6 +1264,24 @@ impl RepoDetailView {
|
||||
.unwrap_or_default();
|
||||
let avatar = PixelAvatar::new(path.clone());
|
||||
|
||||
// A repository already bound to a coordinate is not offered for publishing again.
|
||||
let bound = self.store.read(cx).nip34.clone();
|
||||
let action = match bound
|
||||
.as_ref()
|
||||
.filter(|binding| binding.kind == Nip34Kind::Initialized)
|
||||
{
|
||||
Some(binding) => bound_repo_label(binding, cx),
|
||||
None => Button::new("init")
|
||||
.icon(CustomIconName::Init)
|
||||
.label("Initialize on Nostr")
|
||||
.primary()
|
||||
.tooltip("Publish this repository to Nostr")
|
||||
.on_click(cx.listener(|this, _event, window, cx| {
|
||||
this.open_init_dialog(window, cx);
|
||||
}))
|
||||
.into_any_element(),
|
||||
};
|
||||
|
||||
v_flex()
|
||||
.px_4()
|
||||
.pb_4()
|
||||
@@ -1291,16 +1319,7 @@ impl RepoDetailView {
|
||||
.child(path),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
Button::new("init")
|
||||
.icon(CustomIconName::Init)
|
||||
.label("Initialize on Nostr")
|
||||
.primary()
|
||||
.tooltip("Publish this repository to Nostr")
|
||||
.on_click(cx.listener(|this, _event, window, cx| {
|
||||
this.open_init_dialog(window, cx);
|
||||
})),
|
||||
),
|
||||
.child(action),
|
||||
)
|
||||
.child(self.render_header_tabs(cx))
|
||||
.into_any_element()
|
||||
@@ -1996,6 +2015,37 @@ pub(super) fn repo_display_name(store: &RepoStore) -> SharedString {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The owner and identifier a local repository is already bound to.
|
||||
fn bound_repo_label(binding: &Nip34Binding, cx: &App) -> AnyElement {
|
||||
let store = ProfileStore::global(cx);
|
||||
let profile = binding.owner.map(|pk| store.read(cx).get(&pk));
|
||||
|
||||
h_flex()
|
||||
.flex_shrink_0()
|
||||
.gap_2()
|
||||
.text_sm()
|
||||
.child("Initialized by")
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.when_some(profile, |this, profile| {
|
||||
this.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.text_color(cx.theme().foreground)
|
||||
.child(UserAvatar::new(profile.name()).picture(profile.picture()))
|
||||
.child(profile.name()),
|
||||
)
|
||||
})
|
||||
.when_some(binding.identifier.as_deref(), |this, ident| {
|
||||
this.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.font_semibold()
|
||||
.child(SharedString::from(format!("/{ident}"))),
|
||||
)
|
||||
})
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
impl BasePanel for RepoDetailView {
|
||||
fn panel_name(&self) -> &'static str {
|
||||
"repo"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -10,7 +10,7 @@ use dock::{
|
||||
};
|
||||
use gpui::prelude::*;
|
||||
use gpui::{
|
||||
AnyElement, App, Context, Div, EventEmitter, FocusHandle, Focusable, ObjectFit, Render,
|
||||
AnyElement, App, Context, Div, Entity, EventEmitter, FocusHandle, Focusable, ObjectFit, Render,
|
||||
SharedString, Subscription, WeakEntity, Window, div, img, px, relative, uniform_list, white,
|
||||
};
|
||||
use gpui_base::Button as BaseButton;
|
||||
@@ -18,9 +18,10 @@ use gpui_component::button::{Button, ButtonVariants};
|
||||
use gpui_component::input::InputState;
|
||||
use gpui_component::{ActiveTheme, Icon, IconName, Sizable, StyledExt, h_flex, v_flex};
|
||||
use nostr::prelude::RelayUrl;
|
||||
use signed_core::{Announcement, RepoAddr, identifier_from_name};
|
||||
use signed_core::{Announcement, RepoAddr};
|
||||
use signed_state::{
|
||||
Backend, BackendEvent, CheckoutsStore, LocalReposStore, Profile, ProfileStore, RepoListStore,
|
||||
Backend, BackendEvent, CheckoutsStore, LocalReposStore, Nip34Binding, Nip34Kind, Profile,
|
||||
ProfileStore, RepoListStore, ResolvedLocalRepo, resolve_local_repos,
|
||||
};
|
||||
use signed_ui::{NavItem, PixelAvatar, UserAvatar, title_bar_drag_handlers};
|
||||
|
||||
@@ -35,18 +36,31 @@ mod settings_dialog;
|
||||
|
||||
use self::onboarding_dialog::OnboardingState;
|
||||
|
||||
/// The platform that bound a repository, `"nak"` or `"ngit"`.
|
||||
fn local_platform(binding: &Nip34Binding) -> Option<&'static str> {
|
||||
let signals = &binding.signals;
|
||||
|
||||
if signals.nip34_json || signals.nip34_grasp_remote || signals.nip34_state_refs {
|
||||
Some("nak")
|
||||
} else if signals.nostr_repo_config {
|
||||
Some("ngit")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SidebarPanel {
|
||||
focus_handle: FocusHandle,
|
||||
dock_area: WeakEntity<DockArea>,
|
||||
inbox: Option<WeakEntity<InboxView>>,
|
||||
explore: Option<WeakEntity<RepoListView>>,
|
||||
banner: SharedString,
|
||||
/// The signed-in user's announced repositories, newest first.
|
||||
/// User's announced repositories.
|
||||
announcements: Arc<Vec<Announcement>>,
|
||||
/// Local repositories found by the scan that are not announced yet.
|
||||
local_repos: Arc<Vec<PathBuf>>,
|
||||
local_repos: Arc<Vec<ResolvedLocalRepo>>,
|
||||
scanning: bool,
|
||||
/// Unpushed commit counts per announced repository, shown as row badges.
|
||||
/// Unpushed commit counts per announced repository.
|
||||
unpushed: HashMap<RepoAddr, usize>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
@@ -116,30 +130,21 @@ impl SidebarPanel {
|
||||
let backend = Backend::global(cx);
|
||||
let user = backend.read(cx).current_user();
|
||||
|
||||
let repo_list = RepoListStore::global(cx);
|
||||
let announcements = user
|
||||
.as_ref()
|
||||
.map(|user| repo_list.read(cx).announcements_of(user))
|
||||
.unwrap_or_default();
|
||||
let (announcements, local_repos, scanning) = {
|
||||
let repo_list = RepoListStore::global(cx);
|
||||
let repo_list = repo_list.read(cx);
|
||||
|
||||
// Drop a scanned repository once the user announces it, so it is not listed twice.
|
||||
let local = LocalReposStore::global(cx);
|
||||
let scanning = local.read(cx).scanning;
|
||||
let announcements = user
|
||||
.as_ref()
|
||||
.map(|user| repo_list.announcements_of(user))
|
||||
.unwrap_or_default();
|
||||
|
||||
let local_repos = {
|
||||
let ids: HashSet<String> = announcements.iter().map(|a| a.id.clone()).collect();
|
||||
local
|
||||
.read(cx)
|
||||
.repos
|
||||
.iter()
|
||||
.filter(|path| {
|
||||
let Some(name) = path.file_name() else {
|
||||
return true;
|
||||
};
|
||||
!ids.contains(&identifier_from_name(&name.to_string_lossy()))
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
let local = LocalReposStore::global(cx);
|
||||
let local = local.read(cx);
|
||||
let local_repos =
|
||||
resolve_local_repos(&local.repos, &repo_list.announcements, &announcements);
|
||||
|
||||
(announcements, local_repos, local.scanning)
|
||||
};
|
||||
|
||||
let announcements_changed = *self.announcements != announcements;
|
||||
@@ -259,10 +264,66 @@ impl SidebarPanel {
|
||||
}
|
||||
|
||||
/// The detail view offers to publish it to NIP-34.
|
||||
fn open_local_repo(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
|
||||
fn open_local_repo(
|
||||
&mut self,
|
||||
path: PathBuf,
|
||||
nip34: Option<Nip34Binding>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let detail =
|
||||
cx.new(|cx| RepoDetailView::new_local(self.dock_area.clone(), path, window, cx));
|
||||
cx.new(|cx| RepoDetailView::new_local(self.dock_area.clone(), path, nip34, window, cx));
|
||||
self.add_detail_panel(detail, window, cx);
|
||||
}
|
||||
|
||||
/// A local repository whose binding matches an announcement opens as the announced repository.
|
||||
fn open_local_announced(
|
||||
&mut self,
|
||||
announcement: Announcement,
|
||||
path: PathBuf,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let detail = cx.new(|cx| {
|
||||
RepoDetailView::new_local_announced(
|
||||
self.dock_area.clone(),
|
||||
announcement,
|
||||
path,
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
self.add_detail_panel(detail, window, cx);
|
||||
}
|
||||
|
||||
/// A local repository opens as the announced repository
|
||||
/// when its binding matches one, and as a local-only repository otherwise.
|
||||
fn open_local_entry(
|
||||
&mut self,
|
||||
entry: ResolvedLocalRepo,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let ResolvedLocalRepo {
|
||||
path,
|
||||
nip34,
|
||||
announcement,
|
||||
} = entry;
|
||||
|
||||
if let Some(announcement) = announcement {
|
||||
self.open_local_announced(announcement, path, window, cx);
|
||||
return;
|
||||
}
|
||||
|
||||
self.open_local_repo(path, nip34, window, cx);
|
||||
}
|
||||
|
||||
fn add_detail_panel(
|
||||
&mut self,
|
||||
detail: Entity<RepoDetailView>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.dock_area
|
||||
.update(cx, |dock_area, cx| {
|
||||
add_center_panel(dock_area, panel_handle(detail), window, cx);
|
||||
@@ -361,11 +422,10 @@ impl SidebarPanel {
|
||||
})
|
||||
}
|
||||
|
||||
/// Renders row `ix` of the merged list: an announced repository or a local one.
|
||||
fn render_repo_at(
|
||||
&self,
|
||||
announcements: &[Announcement],
|
||||
local_repos: &[PathBuf],
|
||||
local_repos: &[ResolvedLocalRepo],
|
||||
ix: usize,
|
||||
cx: &mut Context<Self>,
|
||||
) -> AnyElement {
|
||||
@@ -376,9 +436,9 @@ impl SidebarPanel {
|
||||
}
|
||||
|
||||
let local_ix = ix - announcements.len();
|
||||
let path = &local_repos[local_ix];
|
||||
let entry = &local_repos[local_ix];
|
||||
|
||||
self.render_local_row(path, cx).into_any_element()
|
||||
self.render_local_row(entry, cx).into_any_element()
|
||||
}
|
||||
|
||||
fn render_repo_row(
|
||||
@@ -419,23 +479,52 @@ impl SidebarPanel {
|
||||
)
|
||||
}
|
||||
|
||||
/// A local repository that is not yet set up for NIP-34, marked with a warning.
|
||||
fn render_local_row(&self, path: &Path, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or("Untitled".into());
|
||||
let path = path.to_path_buf();
|
||||
let avatar = PixelAvatar::new(path.to_string_lossy());
|
||||
fn render_local_row(
|
||||
&self,
|
||||
entry: &ResolvedLocalRepo,
|
||||
cx: &mut Context<Self>,
|
||||
) -> impl IntoElement {
|
||||
let name = entry.name();
|
||||
let avatar = local_avatar(entry, cx);
|
||||
|
||||
NavItem::new(format!("local-repo:{}", path.display()), name, avatar)
|
||||
.suffix(
|
||||
Icon::new(IconName::TriangleAlert)
|
||||
.small()
|
||||
.text_color(cx.theme().warning),
|
||||
)
|
||||
let id = format!("local-repo:{}", entry.path.display());
|
||||
let entry = entry.clone();
|
||||
|
||||
let suffix: AnyElement = match entry.nip34.as_ref() {
|
||||
Some(binding) => {
|
||||
let (label, tooltip) = match binding.kind {
|
||||
Nip34Kind::Initialized => {
|
||||
let platform = local_platform(binding).unwrap_or("Grasp");
|
||||
let tooltip = match platform {
|
||||
"nak" => "Initialized with nak",
|
||||
"ngit" => "Initialized with ngit",
|
||||
_ => "Initialized for NIP-34",
|
||||
};
|
||||
(platform, tooltip)
|
||||
}
|
||||
Nip34Kind::Cloned => ("Cloned", "Cloned buts not initialized"),
|
||||
Nip34Kind::ToolingOnly => ("Tooling", "Grasp tooling only"),
|
||||
};
|
||||
|
||||
Button::new(id.clone())
|
||||
.xsmall()
|
||||
.child(div().text_size(px(10.)).child(label))
|
||||
.tooltip(tooltip)
|
||||
.secondary()
|
||||
.into_any_element()
|
||||
}
|
||||
None => Button::new(id.clone())
|
||||
.xsmall()
|
||||
.icon(IconName::TriangleAlert)
|
||||
.tooltip("Not published yet")
|
||||
.ghost()
|
||||
.into_any_element(),
|
||||
};
|
||||
|
||||
NavItem::new(id, name, avatar)
|
||||
.suffix(suffix)
|
||||
.on_click(cx.listener(move |this, _ev, window, cx| {
|
||||
this.open_local_repo(path.clone(), window, cx);
|
||||
this.open_local_entry(entry.clone(), window, cx);
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -563,6 +652,30 @@ pub(super) fn server_host(relay: &RelayUrl) -> SharedString {
|
||||
.unwrap_or_else(|| SharedString::from(relay.to_string()))
|
||||
}
|
||||
|
||||
/// The repository's pixel avatar, with the bound owner's avatar at its bottom right.
|
||||
fn local_avatar(entry: &ResolvedLocalRepo, cx: &App) -> AnyElement {
|
||||
let avatar = PixelAvatar::new(entry.path.to_string_lossy());
|
||||
|
||||
let Some(owner) = entry.nip34.as_ref().and_then(|binding| binding.owner) else {
|
||||
return avatar.into_any_element();
|
||||
};
|
||||
|
||||
let store = ProfileStore::global(cx);
|
||||
let profile = store.read(cx).get(&owner);
|
||||
|
||||
div()
|
||||
.relative()
|
||||
.child(avatar)
|
||||
.child(
|
||||
div().absolute().bottom_neg_0p5().right_neg_0p5().child(
|
||||
UserAvatar::new(profile.name())
|
||||
.picture(profile.picture())
|
||||
.size(px(14.)),
|
||||
),
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn pick_banner() -> SharedString {
|
||||
let num = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
|
||||
Reference in New Issue
Block a user