feat: add si command line interface (#37)
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s

Reviewed-on: #37
This commit was merged in pull request #37.
This commit is contained in:
2026-11-30 00:34:44 +00:00
parent 6dfa3a2335
commit b7e1ca7c86
20 changed files with 1252 additions and 75 deletions
+31
View File
@@ -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
+603
View File
@@ -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: ")?),
}
}