From b7e1ca7c868a7ec46bbb1f4c6184987b71b81878 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 30 Nov 2026 00:34:44 +0000 Subject: [PATCH] feat: add `si` command line interface (#37) Reviewed-on: https://git.reya.info/reya/signed/pulls/37 --- CHANGELOG.md | 4 + Cargo.lock | 132 +++++ Cargo.toml | 5 - crates/cli/Cargo.toml | 31 ++ crates/cli/src/main.rs | 603 ++++++++++++++++++++++ crates/paths/src/lib.rs | 19 +- crates/signed_app/Cargo.toml | 3 +- crates/signed_app/src/app/mod.rs | 2 + crates/signed_app/src/profile/mod.rs | 13 +- crates/signed_app/src/settings/helpers.rs | 189 ++++++- crates/signed_app/src/settings/mod.rs | 38 +- crates/signed_git/src/lib.rs | 2 +- crates/signed_git/src/nip34.rs | 35 ++ crates/signed_git/src/repo.rs | 38 +- crates/signed_git/tests/repo.rs | 58 ++- crates/signed_state/Cargo.toml | 3 +- crates/signed_state/src/backend.rs | 85 ++- crates/signed_state/src/lib.rs | 30 +- desktop/Cargo.toml | 4 +- desktop/src/main.rs | 33 +- 20 files changed, 1252 insertions(+), 75 deletions(-) create mode 100644 crates/cli/Cargo.toml create mode 100644 crates/cli/src/main.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index f25e6ec..5029405 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,14 @@ ### Added +- Add a `si` command line interface that opens the desktop app and clones, publishes, syncs and deletes repositories with the app's identity, data and keychain, without the app running +- Install the `si` command from Settings, which links the binary built next to the app into a folder on your PATH - Add a confirmation dialog before deleting a repository - Browse the files of a commit as of that commit from the Commits list, the short id on a row shows the commit's files in place of the worktree and the branch selector shows the commit until a branch or tag is picked again ### 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 @@ -26,6 +29,7 @@ ### Fixed +- Fix a long description in Settings pushing its control past the dialog's edge, the description now wraps inside the row - Fix the status badge on issue and pull request rows sitting below the title instead of centered with it - Fix opening a local repository or switching its branch discarding uncommitted changes, a checkout now refuses to overwrite uncommitted edits or untracked files and leaves the branch untouched when it fails - Fix viewing a commit diff crashing when the repository configures an external diff driver diff --git a/Cargo.lock b/Cargo.lock index 184b470..87e452b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -166,12 +166,56 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + [[package]] name = "anstyle" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.105" @@ -998,6 +1042,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" dependencies = [ "clap_builder", + "clap_derive", ] [[package]] @@ -1006,8 +1051,22 @@ version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" dependencies = [ + "anstream", "anstyle", "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.10", ] [[package]] @@ -1067,6 +1126,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.9" @@ -4187,6 +4252,12 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.13.0" @@ -5487,6 +5558,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "oo7" version = "0.6.0" @@ -6570,6 +6647,27 @@ dependencies = [ "memchr", ] +[[package]] +name = "rpassword" +version = "7.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa2c5d9304b618df61ff17f3d3485c6e1854a3d94902a49abbb8d43dfbe0464" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "rust-embed" version = "8.14.0" @@ -7132,10 +7230,31 @@ dependencies = [ "signed_git", "signed_nostr", "signed_state", + "tempfile", "ui", "utils", ] +[[package]] +name = "signed_cli" +version = "0.2.0" +dependencies = [ + "anyhow", + "clap", + "flume 0.11.1", + "gpui", + "gpui_platform", + "nostr", + "paths", + "rpassword", + "settings", + "signed_core", + "signed_git", + "signed_state", + "tracing", + "tracing-subscriber", +] + [[package]] name = "signed_core" version = "0.2.0" @@ -7190,6 +7309,7 @@ dependencies = [ "nostr", "nostr-connect", "nostr-sdk", + "paths", "rustls", "serde_json", "settings", @@ -7380,6 +7500,12 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.28.0" @@ -8324,6 +8450,12 @@ dependencies = [ "bytes", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" diff --git a/Cargo.toml b/Cargo.toml index 35cb61f..329da6c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,6 @@ signed_app = { path = "crates/signed_app" } nostr = { git = "https://github.com/rust-nostr/nostr", features = ["nip59", "nip49", "nip44", "os-rng"] } nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" } -nostr-blossom = { git = "https://github.com/rust-nostr/nostr" } nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" } nostr-connect = { git = "https://github.com/rust-nostr/nostr" } nostr-sdk = { git = "https://github.com/rust-nostr/nostr" } @@ -27,20 +26,16 @@ gix = { version = "0.88", default-features = false, features = ["sha1", "blockin jiff = "0.2" -smol = "2" futures = "0.3" flume = { version = "0.11.1", default-features = false, features = ["async", "select"] } rust-embed = { version = "8.5", features = ["include-exclude"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -schemars = "1" log = "0.4" anyhow = "1.0.44" webbrowser = "1.0.4" tracing-subscriber = { version = "0.3.18", features = ["fmt"] } tracing = "0.1" -errno = { version = "0.3.14", default-features = false } -instant = "0.1" [profile.release] strip = true diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml new file mode 100644 index 0000000..1d324f1 --- /dev/null +++ b/crates/cli/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "signed_cli" +version.workspace = true +edition.workspace = true +publish.workspace = true + +[[bin]] +name = "si" +path = "src/main.rs" + +[dependencies] +signed_core = { path = "../signed_core" } +signed_git = { path = "../signed_git" } +signed_state = { path = "../signed_state" } +settings.workspace = true +paths = { path = "../paths" } + +rpassword = "7" +clap = { version = "4", features = ["derive"] } + +gpui.workspace = true +gpui_platform.workspace = true +anyhow.workspace = true +flume.workspace = true +nostr.workspace = true + +tracing.workspace = true +tracing-subscriber.workspace = true + +[lints] +workspace = true diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs new file mode 100644 index 0000000..502e04b --- /dev/null +++ b/crates/cli/src/main.rs @@ -0,0 +1,603 @@ +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::process::Stdio; + +use anyhow::{Context as _, bail}; +use clap::{Args, CommandFactory as _, Parser, Subcommand}; +use gpui::{App, AsyncApp, Entity, Subscription}; +use nostr::nips::nip19::Nip19Coordinate; +use nostr::prelude::{PublicKey, RelayUrl, ToBech32 as _}; +use paths::APP_ID; +use settings::{DEFAULT_GRASP_SERVERS, SettingsStore}; +use signed_core::{Announcement, RepoAddr}; +use signed_git::{GitCache, Repo}; +use signed_state::{Backend, BackendEvent, CheckoutsStore}; + +/// Command line interface for Signed. +#[derive(Parser)] +#[command(name = "si", version, about)] +struct Cli { + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Command { + /// Launch the desktop app. + Desktop, + /// Clone a published repository into the current directory or a custom path. + Clone(CloneArgs), + /// Publish a local repository to Nostr. + Publish(PublishArgs), + /// Push the current branch of a published local repository to its grasp servers. + Sync(SyncArgs), + /// Delete a published repository from Nostr. + Delete(DeleteArgs), +} + +#[derive(Args)] +struct CloneArgs { + /// Repository address: `naddr1...`, `nostr:naddr1...` or `30617::`. + repo: String, + /// Destination directory, the repository's name in the current directory when omitted. + path: Option, +} + +#[derive(Args)] +struct PublishArgs { + /// Repository folder, the current directory when omitted. + path: Option, + /// Name of the repository, the folder's name when omitted. + #[arg(long)] + name: Option, + /// Description of the repository. + #[arg(long)] + description: Option, + /// Default branch, the checked out one when omitted. + #[arg(long)] + branch: Option, + /// Grasp server to publish to; the account's grasp list is used when omitted. + #[arg(long = "grasp-server", value_name = "URL")] + grasp_servers: Vec, + #[command(flatten)] + signing: Signing, +} + +#[derive(Args)] +struct SyncArgs { + /// Repository folder, the current directory when omitted. + path: Option, + #[command(flatten)] + signing: Signing, +} + +#[derive(Args)] +struct DeleteArgs { + /// Repository address, or the folder of a published local repository. + repo: String, + /// Delete without asking for confirmation. + #[arg(short, long)] + yes: bool, + #[command(flatten)] + signing: Signing, +} + +/// Options of the commands that sign events with the stored identity. +#[derive(Args)] +struct Signing { + /// Read the passphrase from this file instead of prompting. + #[arg(long, value_name = "PATH")] + passphrase_file: Option, +} + +fn main() { + tracing_subscriber::fmt() + .with_writer(std::io::stderr) + .with_max_level(tracing::Level::WARN) + .init(); + + let cli = Cli::parse(); + + // A bare `si` lists the commands instead of failing. + let Some(command) = cli.command else { + if let Err(error) = Cli::command().print_help() { + eprintln!("error: failed to write help: {error}"); + std::process::exit(1); + } + + return; + }; + + gpui_platform::headless().run(move |cx| { + // The callback runs before the platform's run loop, so the command awaits inside a foreground task. + cx.spawn(async move |cx| { + let mut code = 0; + + if let Err(error) = run(command, cx).await { + eprintln!("error: {error:#}"); + code = 1; + } + + if let Err(error) = std::io::stdout().flush() { + eprintln!("error: failed to write output: {error}"); + code = 1; + } + + // Quitting the platform loop does not carry an exit code, so the process ends here. + std::process::exit(code); + }) + .detach(); + }); +} + +async fn run(command: Command, cx: &mut AsyncApp) -> anyhow::Result<()> { + match command { + Command::Desktop => open_desktop(), + Command::Clone(args) => clone(args, cx).await, + Command::Publish(args) => publish(args, cx).await, + Command::Sync(args) => sync(args, cx).await, + Command::Delete(args) => delete(args, cx).await, + } +} + +/// Launches the desktop app: the `signed` binary built next to this one, else the installed app. +fn open_desktop() -> anyhow::Result<()> { + if let Some(desktop) = paths::sibling_binary("signed") { + std::process::Command::new(desktop) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .context("failed to launch the desktop app")?; + return Ok(()); + } + + if cfg!(target_os = "macos") { + // Launch Services finds the app by its bundle identifier wherever it is installed. + let status = std::process::Command::new("open") + .args(["-b", APP_ID]) + .status() + .context("failed to launch the desktop app")?; + + if !status.success() { + bail!("the desktop app is not installed"); + } + + return Ok(()); + } + + let exe = std::env::current_exe().context("failed to locate this executable")?; + + bail!( + "the desktop app was not found next to {}; run `cargo run -p signed` instead", + exe.display() + ) +} + +/// Opens the stores shared with the desktop app and starts forwarding the backend events. +fn open( + cx: &mut AsyncApp, +) -> anyhow::Result<(Entity, flume::Receiver, Subscription)> { + cx.update(signed_state::init)?; + + let backend = cx.update(|cx| Backend::global(cx)); + let (sender, receiver) = flume::unbounded(); + // The returned subscription keeps the forwarding alive; dropping it ends it. + let subscription = cx.subscribe(&backend, move |_, event: &BackendEvent, _| { + // Sending fails only once the command stopped listening. + sender.send(event.clone()).ok(); + }); + + Ok((backend, receiver, subscription)) +} + +/// Waits for the next backend event. +async fn next_event(receiver: &flume::Receiver) -> anyhow::Result { + Ok(receiver.recv_async().await?) +} + +/// The public key of the restored signer. +fn current_user(backend: &Entity, cx: &App) -> anyhow::Result { + backend + .read(cx) + .current_user() + .context("the signer changed without an identity") +} + +/// How the device is signed in once its stored credential was read. +enum Identity { + SignedIn(PublicKey), + PassphraseRequired, + SignedOut, +} + +/// Waits for the stored credential to be read. +async fn restore( + backend: &Entity, + receiver: &flume::Receiver, + cx: &AsyncApp, +) -> anyhow::Result { + let mut failure = None; + + loop { + match next_event(receiver).await? { + BackendEvent::SignerChanged => { + return Ok(Identity::SignedIn( + cx.update(|cx| current_user(backend, cx))?, + )); + } + BackendEvent::PassphraseRequired => return Ok(Identity::PassphraseRequired), + BackendEvent::SignerRequired => { + // A failed read is reported first, then the signed-out state. + if let Some(message) = failure { + bail!("{message}"); + } + + return Ok(Identity::SignedOut); + } + BackendEvent::Error(message) => failure = Some(message), + _ => {} + } + } +} + +/// Unlocks the identity the desktop app stored on this device. +async fn sign_in( + backend: &Entity, + receiver: &flume::Receiver, + passphrase_file: Option<&Path>, + cx: &mut AsyncApp, +) -> anyhow::Result { + match restore(backend, receiver, cx).await? { + Identity::SignedIn(public_key) => Ok(public_key), + Identity::PassphraseRequired => { + let passphrase = read_passphrase(passphrase_file)?; + backend + .update(cx, |backend, cx| { + backend.restore_with_passphrase(&passphrase, cx) + }) + .await + } + Identity::SignedOut => { + bail!("no identity on this device; sign in with the desktop app first") + } + } +} + +/// Reads a repository's announcement and announced default branch, or `None` when no relay announces it. +async fn load_announcement( + backend: &Entity, + addr: &RepoAddr, + cx: &AsyncApp, +) -> anyhow::Result)>> { + let client = cx.update(|cx| backend.read(cx).client()); + let addr = addr.clone(); + + cx.background_executor() + .spawn(async move { Backend::load_announcement(&client, &addr).await }) + .await +} + +async fn clone(args: CloneArgs, cx: &mut AsyncApp) -> anyhow::Result<()> { + let repo = args.repo.trim(); + let addr = repo + .parse::() + .with_context(|| format!("`{repo}` is not a repository address"))?; + + let (backend, _receiver, _subscription) = open(cx)?; + + let (announcement, _head) = load_announcement(&backend, &addr, cx) + .await? + .with_context(|| format!("no announcement of {addr} was found"))?; + + let destination = match args.path { + Some(path) => path, + None => std::env::current_dir()?.join(folder_name(&announcement)), + }; + + let urls = announcement.clone.clone(); + let clone = { + let destination = destination.clone(); + cx.background_executor() + .spawn(async move { Repo::clone(&urls, &destination).map(|_| ()) }) + }; + clone.await?; + + let checkouts = cx.update(|cx| CheckoutsStore::global(cx)); + checkouts.update(cx, |checkouts, cx| { + checkouts.record(destination.clone(), addr.clone(), cx); + }); + + println!( + "cloned {} into {}", + announcement.name.as_deref().unwrap_or(&announcement.id), + destination.display() + ); + + Ok(()) +} + +/// The folder a repository is cloned into: its name or identifier, sanitized for the file system. +fn folder_name(announcement: &Announcement) -> String { + let name = announcement + .name + .as_deref() + .map(str::trim) + .filter(|name| !name.is_empty()) + .unwrap_or(&announcement.id); + + let name = GitCache::sanitize_path_component(name); + + if name.is_empty() { + "repository".to_owned() + } else { + name + } +} + +async fn publish(args: PublishArgs, cx: &mut AsyncApp) -> anyhow::Result<()> { + let servers = args + .grasp_servers + .iter() + .map(|url| { + RelayUrl::parse(url.as_str()).with_context(|| format!("`{url}` is not a relay URL")) + }) + .collect::>>()?; + + let path = args.path.unwrap_or_else(|| PathBuf::from(".")); + let path = path + .canonicalize() + .with_context(|| format!("cannot find the repository folder {}", path.display()))?; + + let name = match args.name { + Some(name) => name, + None => path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .context("the repository folder has no name")?, + }; + + let (backend, receiver, _subscription) = open(cx)?; + let user = sign_in( + &backend, + &receiver, + args.signing.passphrase_file.as_deref(), + cx, + ) + .await?; + + let branch = match args.branch { + Some(branch) => Some(branch), + None => { + let path = path.clone(); + cx.background_executor() + .spawn(async move { + let repo = Repo::open(&path)?; + Ok::<_, anyhow::Error>(repo.current_branch()) + }) + .await? + } + }; + + let servers = if servers.is_empty() { + account_grasp_servers(&backend, user, cx).await? + } else { + servers + }; + + let description = args.description.unwrap_or_default(); + let announcement = backend + .update(cx, |backend, cx| { + backend.publish_local_repo(path, &name, &description, servers, branch, cx) + }) + .await?; + + let addr = announcement.addr(); + let naddr = + Nip19Coordinate::new(addr.clone().into(), announcement.relays.clone()).to_bech32()?; + + println!( + "published {}", + announcement.name.as_deref().unwrap_or(&announcement.id) + ); + println!("address: {addr}"); + println!("naddr: {naddr}"); + + Ok(()) +} + +/// The grasp servers the account published, or the configured defaults while it has none. +async fn account_grasp_servers( + backend: &Entity, + user: PublicKey, + cx: &mut AsyncApp, +) -> anyhow::Result> { + let client = cx.update(|cx| backend.read(cx).client()); + let published = cx + .background_executor() + .spawn(async move { signed_state::user_grasp_list_servers(&client, user).await }) + .await; + + let mut urls = match published { + Ok(servers) if !servers.is_empty() => return Ok(servers), + Ok(_) => Vec::new(), + Err(error) => { + tracing::warn!("failed to load the account's grasp list: {error:#}"); + Vec::new() + } + }; + + if urls.is_empty() { + let defaults = cx.update(|cx| { + SettingsStore::global(cx) + .read(cx) + .settings() + .grasp_servers + .default_servers + .clone() + }); + + urls = if defaults.is_empty() { + DEFAULT_GRASP_SERVERS + .iter() + .map(|url| (*url).to_owned()) + .collect() + } else { + defaults + }; + } + + Ok(urls + .iter() + .filter_map(|url| RelayUrl::parse(url).ok()) + .collect()) +} + +async fn sync(args: SyncArgs, cx: &mut AsyncApp) -> anyhow::Result<()> { + let (backend, receiver, _subscription) = open(cx)?; + + let path = args.path.unwrap_or_else(|| PathBuf::from(".")); + let path = path + .canonicalize() + .with_context(|| format!("cannot find the repository folder {}", path.display()))?; + let addr = local_addr(&path, cx).await?; + + let (announcement, head) = load_announcement(&backend, &addr, cx) + .await? + .with_context(|| format!("no announcement of {addr} was found"))?; + + let user = sign_in( + &backend, + &receiver, + args.signing.passphrase_file.as_deref(), + cx, + ) + .await?; + + if addr.public_key() != user { + bail!("only the repository's owner can sync it"); + } + + let (branch, commit) = { + let path = path.clone(); + cx.background_executor() + .spawn(async move { + let repo = Repo::open(&path)?; + let branch = repo + .current_branch() + .context("the checkout has a detached HEAD")?; + let commit = repo.head().context("the checkout has no commits")?; + Ok::<_, anyhow::Error>((branch, commit)) + }) + .await? + }; + + let outcome = backend + .update(cx, |backend, cx| { + backend.push_checkout_commit(announcement, path, head, commit.clone(), cx) + }) + .await?; + + println!( + "synced {branch} up to {}", + commit.get(..8).unwrap_or(&commit) + ); + + if let Some(warning) = outcome.partial_warning() { + eprintln!("warning: {warning}"); + } + + Ok(()) +} + +/// The address a local repository was published under, from its NIP-34 markers. +async fn local_addr(path: &Path, cx: &AsyncApp) -> anyhow::Result { + let binding = { + let path = path.to_path_buf(); + cx.background_executor() + .spawn(async move { + let repo = Repo::open(&path)?; + Ok::<_, anyhow::Error>(repo.nip34_binding()) + }) + .await? + }; + + binding + .and_then(|binding| Some(RepoAddr::new(binding.owner?, binding.identifier?))) + .with_context(|| { + format!( + "{} is not published to Nostr yet; run `si publish` first", + path.display() + ) + }) +} + +async fn delete(args: DeleteArgs, cx: &mut AsyncApp) -> anyhow::Result<()> { + let (backend, receiver, _subscription) = open(cx)?; + + let repo = args.repo.trim(); + let addr = match repo.parse::() { + Ok(addr) => addr, + Err(_) => { + let path = Path::new(repo); + + if !path.is_dir() { + bail!("`{repo}` is neither a repository address nor a local repository folder"); + } + + local_addr(path, cx).await? + } + }; + + sign_in( + &backend, + &receiver, + args.signing.passphrase_file.as_deref(), + cx, + ) + .await?; + + let question = format!( + "Delete {addr}? This removes its announcement, state and activity from Nostr and cannot be \ + undone" + ); + + if !args.yes && !confirm(&question)? { + bail!("aborted; pass --yes to delete without a prompt"); + } + + backend + .update(cx, |backend, cx| { + backend.delete_repository(addr.clone(), cx) + }) + .await?; + + println!("deleted {addr}"); + + Ok(()) +} + +/// Asks a yes/no question on the terminal, answering no when stdin is closed. +fn confirm(question: &str) -> anyhow::Result { + eprint!("{question} [y/N]: "); + std::io::stderr().flush()?; + + let mut answer = String::new(); + std::io::stdin().read_line(&mut answer)?; + + Ok(matches!(answer.trim(), "y" | "Y" | "yes")) +} + +/// Reads one line from a file, without its line ending. +fn read_line(path: &Path) -> anyhow::Result { + let line = std::fs::read_to_string(path)?; + Ok(line.trim_end_matches(['\r', '\n']).to_owned()) +} + +/// Reads the passphrase from `path`, or from the terminal without echoing it. +fn read_passphrase(path: Option<&Path>) -> anyhow::Result { + match path { + Some(path) => read_line(path), + None => Ok(rpassword::prompt_password("Passphrase: ")?), + } +} diff --git a/crates/paths/src/lib.rs b/crates/paths/src/lib.rs index 5d58186..2c16d8e 100644 --- a/crates/paths/src/lib.rs +++ b/crates/paths/src/lib.rs @@ -3,7 +3,8 @@ use std::sync::LazyLock; /// The application name, which derives the platform-specific directory paths. pub const APP_NAME: &str = "Signed"; - +/// The application's platform identifier, the packager `identifier` in `desktop/Cargo.toml`. +pub const APP_ID: &str = "build.signed.signed"; /// Lowercased [`APP_NAME`], used in XDG paths and the macOS `~/.config` fallback. pub const APP_NAME_LOWERCASE: &str = "signed"; @@ -72,6 +73,22 @@ pub fn documents_dir() -> PathBuf { dirs::document_dir().unwrap_or_else(|| dirs::home_dir().unwrap_or_default()) } +/// The binary named `name` built next to the running executable, when it is there. +pub fn sibling_binary(name: &str) -> Option { + let name = if std::env::consts::EXE_EXTENSION.is_empty() { + name.to_owned() + } else { + format!("{name}.{}", std::env::consts::EXE_EXTENSION) + }; + let binary = std::env::current_exe().ok()?.with_file_name(name); + binary.is_file().then_some(binary) +} + +/// Returns the user's binary folder, `~/.local/bin`, which most shells put on the PATH. +pub fn user_bin_dir() -> PathBuf { + home_dir().join(".local").join("bin") +} + fn config_dir() -> &'static Path { CONFIG_DIR.as_path() } diff --git a/crates/signed_app/Cargo.toml b/crates/signed_app/Cargo.toml index 24d73b7..18a317d 100644 --- a/crates/signed_app/Cargo.toml +++ b/crates/signed_app/Cargo.toml @@ -7,7 +7,7 @@ publish.workspace = true [dependencies] metadata = { path = "../metadata" } paths = { path = "../paths" } -settings = { path = "../settings" } +settings.workspace = true signed_core = { path = "../signed_core" } signed_git = { path = "../signed_git" } signed_nostr = { path = "../signed_nostr" } @@ -23,6 +23,7 @@ log.workspace = true [dev-dependencies] gpui = { workspace = true, features = ["test-support"] } +tempfile = "3" [lints] workspace = true diff --git a/crates/signed_app/src/app/mod.rs b/crates/signed_app/src/app/mod.rs index 69d2835..00bb2c7 100644 --- a/crates/signed_app/src/app/mod.rs +++ b/crates/signed_app/src/app/mod.rs @@ -127,9 +127,11 @@ impl AppRoot { pub fn mount(window: &mut Window, cx: &mut App) -> Entity { let root = cx.new(|cx| Root::new(window, cx)); let content = cx.new(|cx| AppRoot::new(window, cx)); + root.update(cx, |root, cx| { root.set_content(content, cx); }); + root } diff --git a/crates/signed_app/src/profile/mod.rs b/crates/signed_app/src/profile/mod.rs index 9a3e142..b9e5103 100644 --- a/crates/signed_app/src/profile/mod.rs +++ b/crates/signed_app/src/profile/mod.rs @@ -2,9 +2,8 @@ use std::sync::Arc; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, - Render, ScrollHandle, SharedString, Styled as _, Subscription, Task, WeakEntity, Window, div, - px, + AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, + ScrollHandle, SharedString, Styled as _, Subscription, Task, WeakEntity, Window, div, px, }; use helpers::{ ActivityItem, ActivityRow, RepositoryItem, RepositoryRow, activity_items, repository_items, @@ -25,10 +24,6 @@ use crate::shared::log_dropped; mod helpers; -const AVATAR_SIDE: Pixels = px(96.); -/// The centered content width, so the profile does not stretch across a wide window. -const CONTENT_WIDTH: Pixels = px(720.); - /// A user's identity, announced repositories, and recent activity. pub struct ProfileView { scroll_handle: ScrollHandle, @@ -181,7 +176,7 @@ impl ProfileView { .name(name.clone()) .picture(profile.picture()) .fully_rounded(true) - .size(AVATAR_SIDE), + .size_24(), ) .child(div().text_xl().font_semibold().child(name)) .when_some(about, |this, about| { @@ -262,7 +257,7 @@ impl Render for ProfileView { .child( v_flex().w_full().py_12().items_center().child( v_flex() - .w(CONTENT_WIDTH) + .w(px(720.)) .px_6() .gap_10() .child(self.render_identity(cx)) diff --git a/crates/signed_app/src/settings/helpers.rs b/crates/signed_app/src/settings/helpers.rs index 965bddb..ff5ad4a 100644 --- a/crates/signed_app/src/settings/helpers.rs +++ b/crates/signed_app/src/settings/helpers.rs @@ -1,5 +1,7 @@ -use std::path::PathBuf; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; +use anyhow::Context as _; use gpui::{ AnyElement, App, AppContext as _, Div, ElementId, Entity, IntoElement, ParentElement as _, PathPromptOptions, SharedString, Styled as _, WeakEntity, Window, div, px, @@ -9,12 +11,18 @@ use ui::button::{Button, ButtonVariant}; use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; +use ui::layout::root::RootContext as _; use ui::select::{Select, SelectOption}; use ui::theme::ActiveTheme as _; +use ui::toast::Toast; use ui::tooltip::Tooltip; use crate::settings::{PathRow, ServerRow, SettingsDialog}; use crate::shared::labels::ServerInputExt as _; +use crate::shared::log_dropped; + +/// The name of the command line tool's binary. +const CLI_NAME: &str = "si"; /// The title and description a settings row or block opens with. fn setting_header( @@ -44,7 +52,7 @@ pub fn setting_row( .w_full() .justify_between() .gap_4() - .child(setting_header(cx, title, description)) + .child(setting_header(cx, title, description).flex_1().min_w_0()) .child(div().w(px(200.)).flex_shrink_0().child(control)) .into_any_element() } @@ -373,3 +381,180 @@ fn choose_default_folder( }) .ok(); } + +/// Where the `si` command is installed. +#[derive(Clone, PartialEq, Debug)] +pub(crate) enum CliInstall { + /// The app was built without the `si` binary next to it. + Missing, + NotInstalled, + Installed(PathBuf), +} + +/// The folders `si` is installed into in order of preference, the first one that accepts it. +fn cli_install_dirs() -> Vec { + if let Some(local) = std::env::var_os("LOCALAPPDATA") { + // Windows puts this per-user folder on the PATH. + return vec![PathBuf::from(local).join("Microsoft").join("WindowsApps")]; + } + + vec![PathBuf::from("/usr/local/bin"), paths::user_bin_dir()] +} + +/// Where the `si` command built with this app is installed. +pub(crate) fn current_cli_install() -> CliInstall { + cli_install( + paths::sibling_binary(CLI_NAME).as_deref(), + &cli_install_dirs(), + ) +} + +/// Whether `binary` is installed, given the folders it may live in. +pub(crate) fn cli_install(binary: Option<&Path>, dirs: &[PathBuf]) -> CliInstall { + let Some(binary) = binary else { + return CliInstall::Missing; + }; + + let Some(name) = binary.file_name() else { + return CliInstall::NotInstalled; + }; + + for dir in dirs { + let link = dir.join(name); + + if is_cli_link(&link, binary) { + return CliInstall::Installed(link); + } + } + + CliInstall::NotInstalled +} + +/// Whether `link` is this app's installed `binary`. +fn is_cli_link(link: &Path, binary: &Path) -> bool { + #[cfg(windows)] + { + link.is_file() + } + + #[cfg(not(windows))] + { + std::fs::read_link(link).is_ok_and(|target| target == binary) + } +} + +/// Installs `binary` into the first folder of `dirs` that accepts it, returning the installed path. +pub(crate) fn install_cli_binary(binary: &Path, dirs: &[PathBuf]) -> anyhow::Result { + let mut failure = None; + + for dir in dirs { + match install_into(binary, dir) { + Ok(link) => return Ok(link), + Err(error) if error.kind() == ErrorKind::AlreadyExists => return Err(error.into()), + Err(error) => failure = Some(error), + } + } + + let failure = + failure.unwrap_or_else(|| std::io::Error::other("there is no folder to install into")); + + Err(failure.into()) +} + +/// Links `binary` into `dir`, creating the folder when it does not exist yet. +fn install_into(binary: &Path, dir: &Path) -> std::io::Result { + let name = binary + .file_name() + .ok_or_else(|| std::io::Error::new(ErrorKind::InvalidInput, "the binary has no name"))?; + let link = dir.join(name); + + if let Err(error) = replace_link(binary, &link) { + if error.kind() != ErrorKind::NotFound { + return Err(error); + } + + std::fs::create_dir_all(dir)?; + replace_link(binary, &link)?; + } + + Ok(link) +} + +/// Points `link` at `binary`, replacing a previous install and leaving any other file untouched. +fn replace_link(binary: &Path, link: &Path) -> std::io::Result<()> { + if let Ok(metadata) = link.symlink_metadata() { + // A previous install is a symlink, or a copy on Windows. + if metadata.file_type().is_symlink() || cfg!(windows) { + std::fs::remove_file(link)?; + } else { + return Err(std::io::Error::new( + ErrorKind::AlreadyExists, + format!("{} already exists and was left untouched", link.display()), + )); + } + } + + #[cfg(windows)] + { + std::fs::copy(binary, link)?; + } + + #[cfg(not(windows))] + { + std::os::unix::fs::symlink(binary, link)?; + } + + Ok(()) +} + +/// The description of the command line tool row for the current install state. +pub(crate) fn cli_description(cli: &CliInstall) -> SharedString { + match cli { + CliInstall::Missing => { + "The `si` binary was not found next to the app, so there is nothing to install.".into() + } + CliInstall::NotInstalled => { + "Install the `si` command to manage repositories from a terminal.".into() + } + CliInstall::Installed(link) => format!( + "`si` is installed at {}. Its folder must be on your PATH.", + link.display() + ) + .into(), + } +} + +/// The button of the command line tool row. +pub(crate) fn install_cli_button(this: &WeakEntity, cli: &CliInstall) -> Button { + let label = match cli { + CliInstall::Installed(_) => "Reinstall", + _ => "Install", + }; + + Button::new("settings-install-cli") + .label(label) + .w_full() + .disabled(matches!(cli, CliInstall::Missing)) + .on_click({ + let this = this.clone(); + move |_, _, cx| install_cli(&this, cx) + }) +} + +fn install_cli(this: &WeakEntity, cx: &mut App) { + let installed = paths::sibling_binary(CLI_NAME) + .with_context(|| "the `si` binary was not found next to the app") + .and_then(|binary| install_cli_binary(&binary, &cli_install_dirs())); + + log_dropped(this.update(cx, |dialog, cx| { + dialog.refresh_cli(); + + if let Err(error) = &installed { + cx.toast( + Toast::new(format!("Failed to install `si`: {error:#}")).icon(IconRole::Warning), + ); + } + + cx.notify(); + })); +} diff --git a/crates/signed_app/src/settings/mod.rs b/crates/signed_app/src/settings/mod.rs index fba0dc6..075530e 100644 --- a/crates/signed_app/src/settings/mod.rs +++ b/crates/signed_app/src/settings/mod.rs @@ -8,8 +8,9 @@ use gpui::{ SharedString, Styled as _, Subscription, Task, Window, px, }; use helpers::{ - appearance_select, default_folder_selector, event_fetching_select, grasp_servers_editor, - scan_paths_editor, setting_block, setting_row, + CliInstall, appearance_select, cli_description, current_cli_install, default_folder_selector, + event_fetching_select, grasp_servers_editor, install_cli_button, scan_paths_editor, + setting_block, setting_row, }; use settings::SettingsStore; use ui::alert::{Alert, AlertSeverity}; @@ -19,6 +20,7 @@ use ui::input::InputState; use ui::separator::Separator; use crate::shared::labels::{RelayHostExt as _, ServerInputExt as _}; +use crate::shared::log_dropped; /// One grasp server row, with its display strings built when settings change. #[derive(Clone)] @@ -46,6 +48,8 @@ pub struct SettingsDialog { servers: Vec, /// Scan path rows, rebuilt when the settings change. scan_paths: Vec, + /// Where the `si` command is installed. + cli: CliInstall, /// Prompts this dialog started, cancelled when it drops. tasks: Vec>, /// Rebuilds the rows when the settings change. @@ -69,18 +73,25 @@ impl SettingsDialog { .read_only() .build(cx); - let dialog = cx.new(|cx| { - let mut dialog = Self { + let dialog = cx.new(|cx: &mut Context| { + let weak = cx.weak_entity(); + cx.defer(move |cx| { + log_dropped(weak.update(cx, |dialog, cx| { + dialog.rebuild_rows(cx); + dialog.refresh_cli(); + })); + }); + + Self { handle: DialogHandle::new(true), grasp_input, default_folder, servers: Vec::new(), scan_paths: Vec::new(), + cli: CliInstall::Missing, tasks: Vec::new(), _subscription: None, - }; - dialog.rebuild_rows(cx); - dialog + } }); dialog.update(cx, |dialog, cx| { @@ -129,6 +140,11 @@ impl SettingsDialog { }) .collect(); } + + /// Looks up where the `si` command is installed. + fn refresh_cli(&mut self) { + self.cli = current_cli_install(); + } } impl Render for SettingsDialog { @@ -145,6 +161,7 @@ impl Render for SettingsDialog { let default_folder = self.default_folder.clone(); let servers = self.servers.clone(); let scan_paths = self.scan_paths.clone(); + let cli = self.cli.clone(); let this = cx.weak_entity(); Dialog::new("settings-dialog") @@ -200,6 +217,13 @@ impl Render for SettingsDialog { FOLDER_DESC, default_folder_selector(&default_folder, &this), )) + .child(Separator::horizontal()) + .child(setting_row( + cx, + "Command Line Tool", + cli_description(&cli), + install_cli_button(&this, &cli), + )) .into_any_element() }) } 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/Cargo.toml b/crates/signed_state/Cargo.toml index 838143a..5aaf6f6 100644 --- a/crates/signed_state/Cargo.toml +++ b/crates/signed_state/Cargo.toml @@ -8,7 +8,8 @@ publish.workspace = true signed_core = { path = "../signed_core" } signed_git = { path = "../signed_git" } signed_nostr = { path = "../signed_nostr" } -settings = { path = "../settings" } +settings.workspace = true +paths = { path = "../paths" } utils = { path = "../utils" } nostr.workspace = true diff --git a/crates/signed_state/src/backend.rs b/crates/signed_state/src/backend.rs index 78ea32a..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}; @@ -11,8 +11,8 @@ use nostr::event::IntoEventBuilder; use nostr::nips::nip19::Nip19Coordinate; use nostr_connect::prelude::*; use nostr_sdk::prelude::*; -use signed_core::{Announcement, Filters, RepoAddr}; -use signed_git::{GitCache, Repo}; +use signed_core::{Announcement, Deletions, Filters, RepoAddr}; +use signed_git::{GitCache, Nip34Metadata, Repo}; use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update}; use crate::bootstrap::{ @@ -229,7 +229,7 @@ impl Backend { let task: Task> = cx.spawn(async move |this, cx| { let content = match user.await { Ok(Some((_username, secret))) => String::from_utf8(secret)?, - _ => { + Ok(None) => { this.update(cx, |this, cx| { if this.session == session { cx.emit(BackendEvent::SignerRequired); @@ -237,6 +237,17 @@ impl Backend { })?; return Ok(()); } + Err(error) => { + this.update(cx, |this, cx| { + if this.session == session { + cx.emit(BackendEvent::error(format!( + "failed to read the stored credential: {error}" + ))); + cx.emit(BackendEvent::SignerRequired); + } + })?; + return Ok(()); + } }; let result = async { @@ -798,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) => { @@ -814,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:#}"); + } }) } @@ -1078,6 +1107,45 @@ impl Backend { }) } + /// The latest announcement of `addr` and its latest state's `HEAD`, syncing the bootstrap relays when the database has neither. + pub async fn load_announcement( + client: &Client, + addr: &RepoAddr, + ) -> Result)>, Error> { + if let Some(found) = Self::stored_announcement(client, addr).await? { + return Ok(Some(found)); + } + + sync_bootstrap_only(client, addr.announcement_filter(), SyncOptions::default()).await?; + Self::stored_announcement(client, addr).await + } + + async fn stored_announcement( + client: &Client, + addr: &RepoAddr, + ) -> Result)>, Error> { + let db = client.database(); + let deletions = Deletions::from_events(db.query(Filters::deletions()).await?); + + let announcement = db + .query(addr.announcement_filter()) + .await? + .into_iter() + .filter(|event| !deletions.is_deleted(event)) + .max_by_key(|event| event.created_at) + .and_then(|event| Announcement::from_event(&event)); + + let head = db + .query(addr.state_filter()) + .await? + .into_iter() + .filter(|event| !deletions.is_deleted(event)) + .max_by_key(|event| event.created_at) + .and_then(|event| SyncState::parse(&event).head); + + Ok(announcement.map(|announcement| (announcement, head))) + } + fn bootstrap_user(&mut self, public_key: PublicKey, cx: &mut Context) { let client = self.client.clone(); @@ -1155,6 +1223,7 @@ impl Backend { pub fn sign_out(&mut self, cx: &mut Context) { self.supersede_session(); + // Nothing may be signed with the identity the user just left. self.signer.swap_inner(Keys::generate()); self.current_user = None; @@ -1177,8 +1246,10 @@ impl Backend { Ok::<(), Error>(()) }) .detach(); + cx.emit(BackendEvent::SignerChanged); cx.emit(BackendEvent::SignerRequired); + cx.notify(); } diff --git a/crates/signed_state/src/lib.rs b/crates/signed_state/src/lib.rs index 4b59d0b..1a7035d 100644 --- a/crates/signed_state/src/lib.rs +++ b/crates/signed_state/src/lib.rs @@ -12,8 +12,6 @@ mod repos; mod state; mod sync_status; -use std::path::{Path, PathBuf}; - pub use backend::{Backend, BackendEvent}; pub use bootstrap::{sync_bootstrap_only, user_grasp_list_servers}; pub use checkouts::CheckoutsStore; @@ -26,17 +24,25 @@ pub use push::{GraspServer, PushOutcome}; pub use refresh::{RefreshGate, RefreshRequest}; pub use repo::RepoStore; pub use repos::RepoListStore; +use settings::SettingsStore; pub use signed_git::{Nip34Binding, Nip34Kind}; use signed_nostr::NostrBackend; pub use state::{GitPushMode, GitPushPolicy, GitRef, PushStep, PushStepStatus, SyncState}; pub use sync_status::{CheckoutSyncStatus, SyncEvent, SyncStatusDirectory, SyncStatusStore}; -pub fn init( - db_path: impl AsRef, - repos_root: impl Into, - scan_paths: Vec, - cx: &mut App, -) -> anyhow::Result<()> { +/// Loads the settings, creates the data directories and installs the stores every frontend shares. +pub fn init(cx: &mut App) -> anyhow::Result<()> { + SettingsStore::set_global(cx.new(|_| SettingsStore::new(paths::settings_file())), cx); + + let settings = SettingsStore::global(cx); + let scan_paths = settings.read(cx).settings().local_repos.scan_paths.clone(); + + for dir in [paths::nostr_dir(), paths::repos_dir()] { + if let Err(error) = std::fs::create_dir_all(dir) { + log::warn!("failed to create {}: {error}", dir.display()); + } + } + // rustls uses the `aws_lc_rs` provider by default. if rustls::crypto::aws_lc_rs::default_provider() .install_default() @@ -45,7 +51,7 @@ pub fn init( log::debug!("a crypto provider is already installed"); } - let db_path = db_path.as_ref().to_path_buf(); + let db_path = paths::nostr_dir().to_path_buf(); let backend = match cx .foreground_executor() @@ -73,9 +79,9 @@ pub fn init( if backend.is_ok() { cx.show_system_notification(gpui::SystemNotification { tag: "signed-nostr-db".into(), - title: "Nostr cache unavailable".into(), + title: "Nostr Storage unavailable".into(), body: format!( - "{} could not be opened; this session uses a temporary cache", + "{} could not be opened, this session uses a temporary storage", db_path.display() ) .into(), @@ -89,7 +95,7 @@ pub fn init( let (client, signer) = (backend.client, backend.signer); - Mirrors::install(repos_root); + Mirrors::install(paths::repos_dir().to_path_buf()); Backend::set_global(cx.new(|cx| Backend::new(client, signer, cx)), cx); RepoListStore::set_global(cx.new(RepoListStore::new), cx); diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml index b6db5c3..14f8a8f 100644 --- a/desktop/Cargo.toml +++ b/desktop/Cargo.toml @@ -29,8 +29,8 @@ icons = [ [dependencies] metadata = { path = "../crates/metadata" } paths = { path = "../crates/paths" } -settings = { path = "../crates/settings" } -signed_app = { path = "../crates/signed_app" } +settings.workspace = true +signed_app.workspace = true signed_state = { path = "../crates/signed_state" } gpui.workspace = true diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 9be36c6..f4bd766 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use gpui::*; use gpui_platform::application; use settings::SettingsStore; +use signed_app::AppRoot; use ui::theme::{ActiveTheme as _, Theme}; actions!(signed, [Quit]); @@ -44,43 +45,27 @@ fn main() { .with_assets(AppAssets) .with_http_client(Arc::new(reqwest_client::ReqwestClient::new())) .run(move |cx| { - ui::init(cx); - cx.bind_keys([ KeyBinding::new("cmd-q", Quit, None), KeyBinding::new("ctrl-q", Quit, None), ]); cx.on_action(|_: &Quit, cx| cx.quit()); - cx.set_app_identity("build.signed.signed", "Signed"); + cx.set_app_identity(paths::APP_ID, paths::APP_NAME); - let store = cx.new(|_| SettingsStore::new(paths::settings_file())); - SettingsStore::set_global(store.clone(), cx); + ui::init(cx); - let settings = store.read(cx).settings().clone(); - signed_app::AppRoot::apply_appearance_mode(settings.appearance, cx); - - if let Err(error) = std::fs::create_dir_all(paths::nostr_dir()) { - tracing::warn!("failed to create nostr dir: {error}"); - } - - if let Err(error) = std::fs::create_dir_all(paths::repos_dir()) { - tracing::warn!("failed to create repos dir: {error}"); - } - - if let Err(error) = signed_state::init( - paths::nostr_dir(), - paths::repos_dir().to_path_buf(), - settings.local_repos.scan_paths.clone(), - cx, - ) { + if let Err(error) = signed_state::init(cx) { tracing::error!("failed to initialize application state: {error:#}"); cx.quit(); return; } - metadata::init(cx); + let settings = SettingsStore::global(cx); + let appearance = settings.read(cx).settings().appearance; + AppRoot::apply_appearance_mode(appearance, cx); + let theme = cx.theme(); let bounds = Bounds::centered(None, size(px(1120.0), px(750.0)), cx); @@ -113,7 +98,7 @@ fn main() { }) .detach(); - signed_app::AppRoot::mount(window, cx) + AppRoot::mount(window, cx) }) { tracing::error!("failed to open window: {error}"); cx.quit();