feat: add si command line interface (#37)
Reviewed-on: #37
This commit was merged in pull request #37.
This commit is contained in:
@@ -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
|
||||
@@ -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<Command>,
|
||||
}
|
||||
|
||||
#[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:<pubkey>:<id>`.
|
||||
repo: String,
|
||||
/// Destination directory, the repository's name in the current directory when omitted.
|
||||
path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct PublishArgs {
|
||||
/// Repository folder, the current directory when omitted.
|
||||
path: Option<PathBuf>,
|
||||
/// Name of the repository, the folder's name when omitted.
|
||||
#[arg(long)]
|
||||
name: Option<String>,
|
||||
/// Description of the repository.
|
||||
#[arg(long)]
|
||||
description: Option<String>,
|
||||
/// Default branch, the checked out one when omitted.
|
||||
#[arg(long)]
|
||||
branch: Option<String>,
|
||||
/// Grasp server to publish to; the account's grasp list is used when omitted.
|
||||
#[arg(long = "grasp-server", value_name = "URL")]
|
||||
grasp_servers: Vec<String>,
|
||||
#[command(flatten)]
|
||||
signing: Signing,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct SyncArgs {
|
||||
/// Repository folder, the current directory when omitted.
|
||||
path: Option<PathBuf>,
|
||||
#[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<PathBuf>,
|
||||
}
|
||||
|
||||
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<Backend>, flume::Receiver<BackendEvent>, 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<BackendEvent>) -> anyhow::Result<BackendEvent> {
|
||||
Ok(receiver.recv_async().await?)
|
||||
}
|
||||
|
||||
/// The public key of the restored signer.
|
||||
fn current_user(backend: &Entity<Backend>, cx: &App) -> anyhow::Result<PublicKey> {
|
||||
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<Backend>,
|
||||
receiver: &flume::Receiver<BackendEvent>,
|
||||
cx: &AsyncApp,
|
||||
) -> anyhow::Result<Identity> {
|
||||
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<Backend>,
|
||||
receiver: &flume::Receiver<BackendEvent>,
|
||||
passphrase_file: Option<&Path>,
|
||||
cx: &mut AsyncApp,
|
||||
) -> anyhow::Result<PublicKey> {
|
||||
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<Backend>,
|
||||
addr: &RepoAddr,
|
||||
cx: &AsyncApp,
|
||||
) -> anyhow::Result<Option<(Announcement, Option<String>)>> {
|
||||
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::<RepoAddr>()
|
||||
.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::<anyhow::Result<Vec<_>>>()?;
|
||||
|
||||
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<Backend>,
|
||||
user: PublicKey,
|
||||
cx: &mut AsyncApp,
|
||||
) -> anyhow::Result<Vec<RelayUrl>> {
|
||||
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<RepoAddr> {
|
||||
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::<RepoAddr>() {
|
||||
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<bool> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
match path {
|
||||
Some(path) => read_line(path),
|
||||
None => Ok(rpassword::prompt_password("Passphrase: ")?),
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -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<PathBuf> {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -127,9 +127,11 @@ impl AppRoot {
|
||||
pub fn mount(window: &mut Window, cx: &mut App) -> Entity<Root> {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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<PathBuf> {
|
||||
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<PathBuf> {
|
||||
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<PathBuf> {
|
||||
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<SettingsDialog>, 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<SettingsDialog>, 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();
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -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<ServerRow>,
|
||||
/// Scan path rows, rebuilt when the settings change.
|
||||
scan_paths: Vec<PathRow>,
|
||||
/// Where the `si` command is installed.
|
||||
cli: CliInstall,
|
||||
/// Prompts this dialog started, cancelled when it drops.
|
||||
tasks: Vec<Task<()>>,
|
||||
/// 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<Self>| {
|
||||
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()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String>,
|
||||
#[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<Self> {
|
||||
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(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Result<(), Error>> = 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<Option<(Announcement, Option<String>)>, 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<Option<(Announcement, Option<String>)>, 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<Self>) {
|
||||
let client = self.client.clone();
|
||||
|
||||
@@ -1155,6 +1223,7 @@ impl Backend {
|
||||
|
||||
pub fn sign_out(&mut self, cx: &mut Context<Self>) {
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Path>,
|
||||
repos_root: impl Into<PathBuf>,
|
||||
scan_paths: Vec<PathBuf>,
|
||||
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);
|
||||
|
||||
Reference in New Issue
Block a user