feat: add repo commands to the si cli
This commit is contained in:
+1
-1
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- Add a `si` command line interface with `whoami`, `signup`, `login` and `logout` that uses the same identity, data and keychain as the app without the app running
|
- 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
|
||||||
- Add a confirmation dialog before deleting a repository
|
- 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
|
- 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
|
||||||
|
|
||||||
|
|||||||
Generated
+3
@@ -7244,6 +7244,9 @@ dependencies = [
|
|||||||
"gpui_platform",
|
"gpui_platform",
|
||||||
"nostr",
|
"nostr",
|
||||||
"rpassword",
|
"rpassword",
|
||||||
|
"settings",
|
||||||
|
"signed_core",
|
||||||
|
"signed_git",
|
||||||
"signed_state",
|
"signed_state",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
|
|||||||
@@ -9,7 +9,10 @@ name = "si"
|
|||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
signed_core = { path = "../signed_core" }
|
||||||
|
signed_git = { path = "../signed_git" }
|
||||||
signed_state = { path = "../signed_state" }
|
signed_state = { path = "../signed_state" }
|
||||||
|
settings = { path = "../settings" }
|
||||||
|
|
||||||
gpui.workspace = true
|
gpui.workspace = true
|
||||||
gpui_platform.workspace = true
|
gpui_platform.workspace = true
|
||||||
|
|||||||
+437
-148
@@ -1,11 +1,19 @@
|
|||||||
use std::io::Write as _;
|
use std::io::Write as _;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Stdio;
|
||||||
|
|
||||||
use anyhow::{Context as _, bail};
|
use anyhow::{Context as _, bail};
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Args, Parser, Subcommand};
|
||||||
use gpui::{App, AsyncApp, Entity, Subscription};
|
use gpui::{App, AsyncApp, Entity, Subscription};
|
||||||
use nostr::prelude::{PublicKey, ToBech32 as _};
|
use nostr::nips::nip19::Nip19Coordinate;
|
||||||
use signed_state::{Backend, BackendEvent};
|
use nostr::prelude::{PublicKey, RelayUrl, ToBech32 as _};
|
||||||
|
use settings::{DEFAULT_GRASP_SERVERS, SettingsStore};
|
||||||
|
use signed_core::{Announcement, RepoAddr};
|
||||||
|
use signed_git::{GitCache, Repo};
|
||||||
|
use signed_state::{Backend, BackendEvent, CheckoutsStore};
|
||||||
|
|
||||||
|
/// The desktop app's bundle identifier, the packager `identifier` in `desktop/Cargo.toml`.
|
||||||
|
const DESKTOP_BUNDLE_ID: &str = "info.reya.signed";
|
||||||
|
|
||||||
/// Command line interface for Signed.
|
/// Command line interface for Signed.
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
@@ -17,31 +25,71 @@ struct Cli {
|
|||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
enum Command {
|
enum Command {
|
||||||
/// Create a new identity and store it on this device.
|
/// Launch the desktop app.
|
||||||
Signup {
|
Desktop,
|
||||||
/// Name published in the profile.
|
/// Clone a published repository into the current directory or a custom path.
|
||||||
name: String,
|
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.
|
/// Read the passphrase from this file instead of prompting.
|
||||||
#[arg(long, value_name = "PATH")]
|
#[arg(long, value_name = "PATH")]
|
||||||
passphrase_file: Option<PathBuf>,
|
passphrase_file: Option<PathBuf>,
|
||||||
},
|
|
||||||
/// Store an existing identity on this device.
|
|
||||||
Login {
|
|
||||||
/// Read the credential (nsec, ncryptsec or bunker URI) from this file instead of prompting.
|
|
||||||
#[arg(long, value_name = "PATH")]
|
|
||||||
credential_file: Option<PathBuf>,
|
|
||||||
/// Read the passphrase from this file instead of prompting.
|
|
||||||
#[arg(long, value_name = "PATH")]
|
|
||||||
passphrase_file: Option<PathBuf>,
|
|
||||||
},
|
|
||||||
/// Print the identity stored on this device.
|
|
||||||
Whoami {
|
|
||||||
/// Read the passphrase from this file instead of prompting.
|
|
||||||
#[arg(long, value_name = "PATH")]
|
|
||||||
passphrase_file: Option<PathBuf>,
|
|
||||||
},
|
|
||||||
/// Remove the identity stored on this device.
|
|
||||||
Logout,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
@@ -76,26 +124,62 @@ fn main() {
|
|||||||
|
|
||||||
async fn run(command: Command, cx: &mut AsyncApp) -> anyhow::Result<()> {
|
async fn run(command: Command, cx: &mut AsyncApp) -> anyhow::Result<()> {
|
||||||
match command {
|
match command {
|
||||||
Command::Signup {
|
Command::Desktop => open_desktop(),
|
||||||
name,
|
Command::Clone(args) => clone(args, cx).await,
|
||||||
passphrase_file,
|
Command::Publish(args) => publish(args, cx).await,
|
||||||
} => signup(&name, passphrase_file.as_deref(), cx).await,
|
Command::Sync(args) => sync(args, cx).await,
|
||||||
Command::Login {
|
Command::Delete(args) => delete(args, cx).await,
|
||||||
credential_file,
|
|
||||||
passphrase_file,
|
|
||||||
} => login(credential_file.as_deref(), passphrase_file.as_deref(), cx).await,
|
|
||||||
Command::Whoami { passphrase_file } => whoami(passphrase_file.as_deref(), cx).await,
|
|
||||||
Command::Logout => logout(cx).await,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Launches the desktop app: the `signed` binary built next to this one, else the installed app.
|
||||||
|
fn open_desktop() -> anyhow::Result<()> {
|
||||||
|
let exe = std::env::current_exe().context("failed to locate this executable")?;
|
||||||
|
let extension = std::env::consts::EXE_EXTENSION;
|
||||||
|
|
||||||
|
let sibling = if extension.is_empty() {
|
||||||
|
exe.with_file_name("signed")
|
||||||
|
} else {
|
||||||
|
exe.with_file_name(format!("signed.{extension}"))
|
||||||
|
};
|
||||||
|
|
||||||
|
if sibling.is_file() {
|
||||||
|
std::process::Command::new(&sibling)
|
||||||
|
.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", DESKTOP_BUNDLE_ID])
|
||||||
|
.status()
|
||||||
|
.context("failed to launch the desktop app")?;
|
||||||
|
|
||||||
|
if !status.success() {
|
||||||
|
bail!("the desktop app is not installed");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
/// Opens the stores shared with the desktop app and starts forwarding the backend events.
|
||||||
fn open(
|
fn open(
|
||||||
cx: &mut AsyncApp,
|
cx: &mut AsyncApp,
|
||||||
) -> anyhow::Result<(Entity<Backend>, flume::Receiver<BackendEvent>, Subscription)> {
|
) -> anyhow::Result<(Entity<Backend>, flume::Receiver<BackendEvent>, Subscription)> {
|
||||||
cx.update(signed_state::init)?;
|
cx.update(signed_state::init)?;
|
||||||
let backend = cx.update(|cx| Backend::global(cx));
|
|
||||||
|
|
||||||
|
let backend = cx.update(|cx| Backend::global(cx));
|
||||||
let (sender, receiver) = flume::unbounded();
|
let (sender, receiver) = flume::unbounded();
|
||||||
// The returned subscription keeps the forwarding alive; dropping it ends it.
|
// The returned subscription keeps the forwarding alive; dropping it ends it.
|
||||||
let subscription = cx.subscribe(&backend, move |_, event: &BackendEvent, _| {
|
let subscription = cx.subscribe(&backend, move |_, event: &BackendEvent, _| {
|
||||||
@@ -156,116 +240,351 @@ async fn restore(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fails when the device already holds a credential, since a second one would shadow it on restore.
|
/// Unlocks the identity the desktop app stored on this device.
|
||||||
async fn require_signed_out(
|
async fn sign_in(
|
||||||
backend: &Entity<Backend>,
|
backend: &Entity<Backend>,
|
||||||
receiver: &flume::Receiver<BackendEvent>,
|
receiver: &flume::Receiver<BackendEvent>,
|
||||||
cx: &AsyncApp,
|
passphrase_file: Option<&Path>,
|
||||||
) -> anyhow::Result<()> {
|
cx: &mut AsyncApp,
|
||||||
|
) -> anyhow::Result<PublicKey> {
|
||||||
match restore(backend, receiver, cx).await? {
|
match restore(backend, receiver, cx).await? {
|
||||||
Identity::SignedOut => Ok(()),
|
Identity::SignedIn(public_key) => Ok(public_key),
|
||||||
Identity::SignedIn(public_key) => {
|
|
||||||
bail!("this device already holds an identity ({public_key}); run `si logout` first")
|
|
||||||
}
|
|
||||||
Identity::PassphraseRequired => {
|
|
||||||
bail!("this device already holds an encrypted identity; run `si logout` first")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn whoami(passphrase_file: Option<&Path>, cx: &mut AsyncApp) -> anyhow::Result<()> {
|
|
||||||
let (backend, receiver, _subscription) = open(cx)?;
|
|
||||||
|
|
||||||
let public_key = match restore(&backend, &receiver, cx).await? {
|
|
||||||
Identity::SignedIn(public_key) => public_key,
|
|
||||||
Identity::PassphraseRequired => {
|
Identity::PassphraseRequired => {
|
||||||
let passphrase = read_passphrase(passphrase_file)?;
|
let passphrase = read_passphrase(passphrase_file)?;
|
||||||
backend
|
backend
|
||||||
.update(cx, |backend, cx| {
|
.update(cx, |backend, cx| {
|
||||||
backend.restore_with_passphrase(&passphrase, cx)
|
backend.restore_with_passphrase(&passphrase, cx)
|
||||||
})
|
})
|
||||||
.await?
|
.await
|
||||||
}
|
}
|
||||||
Identity::SignedOut => {
|
Identity::SignedOut => {
|
||||||
bail!("no identity on this device; run `si signup` or `si login` first")
|
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?
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
print_identity(public_key)
|
let servers = if servers.is_empty() {
|
||||||
}
|
account_grasp_servers(&backend, user, cx).await?
|
||||||
|
} else {
|
||||||
|
servers
|
||||||
|
};
|
||||||
|
|
||||||
async fn signup(
|
let description = args.description.unwrap_or_default();
|
||||||
name: &str,
|
let announcement = backend
|
||||||
passphrase_file: Option<&Path>,
|
|
||||||
cx: &mut AsyncApp,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let (backend, receiver, _subscription) = open(cx)?;
|
|
||||||
|
|
||||||
require_signed_out(&backend, &receiver, cx).await?;
|
|
||||||
|
|
||||||
let passphrase = new_passphrase(passphrase_file)?;
|
|
||||||
let public_key = backend
|
|
||||||
.update(cx, |backend, cx| {
|
.update(cx, |backend, cx| {
|
||||||
backend.create_identity(name, &passphrase, cx)
|
backend.publish_local_repo(path, &name, &description, servers, branch, cx)
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
print_identity(public_key)?;
|
|
||||||
|
|
||||||
// The identity is stored already; wait so exiting does not drop the events still being sent.
|
let addr = announcement.addr();
|
||||||
loop {
|
let naddr =
|
||||||
match next_event(&receiver).await? {
|
Nip19Coordinate::new(addr.clone().into(), announcement.relays.clone()).to_bech32()?;
|
||||||
BackendEvent::IdentityPublished(Ok(())) => return Ok(()),
|
|
||||||
BackendEvent::IdentityPublished(Err(message)) => bail!("{message}"),
|
println!(
|
||||||
_ => {}
|
"published {}",
|
||||||
}
|
announcement.name.as_deref().unwrap_or(&announcement.id)
|
||||||
}
|
);
|
||||||
|
println!("address: {addr}");
|
||||||
|
println!("naddr: {naddr}");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn login(
|
/// The grasp servers the account published, or the configured defaults while it has none.
|
||||||
credential_file: Option<&Path>,
|
async fn account_grasp_servers(
|
||||||
passphrase_file: Option<&Path>,
|
backend: &Entity<Backend>,
|
||||||
|
user: PublicKey,
|
||||||
cx: &mut AsyncApp,
|
cx: &mut AsyncApp,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<Vec<RelayUrl>> {
|
||||||
let (backend, receiver, _subscription) = open(cx)?;
|
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;
|
||||||
|
|
||||||
require_signed_out(&backend, &receiver, cx).await?;
|
let mut urls = match published {
|
||||||
|
Ok(servers) if !servers.is_empty() => return Ok(servers),
|
||||||
let credential = read_credential(credential_file)?;
|
Ok(_) => Vec::new(),
|
||||||
let credential = credential.trim();
|
Err(error) => {
|
||||||
|
tracing::warn!("failed to load the account's grasp list: {error:#}");
|
||||||
let public_key = if credential.starts_with("nsec1") {
|
Vec::new()
|
||||||
let passphrase = new_passphrase(passphrase_file)?;
|
}
|
||||||
backend
|
|
||||||
.update(cx, |backend, cx| {
|
|
||||||
backend.import_nsec(credential, &passphrase, cx)
|
|
||||||
})
|
|
||||||
.await?
|
|
||||||
} else if credential.starts_with("ncryptsec1") {
|
|
||||||
let passphrase = read_passphrase(passphrase_file)?;
|
|
||||||
backend
|
|
||||||
.update(cx, |backend, cx| {
|
|
||||||
backend.import_ncryptsec(credential, &passphrase, cx)
|
|
||||||
})
|
|
||||||
.await?
|
|
||||||
} else if credential.starts_with("bunker://") {
|
|
||||||
backend
|
|
||||||
.update(cx, |backend, cx| backend.import_bunker(credential, cx))
|
|
||||||
.await?
|
|
||||||
} else {
|
|
||||||
bail!("the credential must be an nsec, ncryptsec or bunker:// URI");
|
|
||||||
};
|
};
|
||||||
|
|
||||||
print_identity(public_key)
|
if urls.is_empty() {
|
||||||
}
|
let defaults = cx.update(|cx| {
|
||||||
|
SettingsStore::global(cx)
|
||||||
|
.read(cx)
|
||||||
|
.settings()
|
||||||
|
.grasp_servers
|
||||||
|
.default_servers
|
||||||
|
.clone()
|
||||||
|
});
|
||||||
|
|
||||||
async fn logout(cx: &mut AsyncApp) -> anyhow::Result<()> {
|
urls = if defaults.is_empty() {
|
||||||
let (backend, receiver, _subscription) = open(cx)?;
|
DEFAULT_GRASP_SERVERS
|
||||||
|
.iter()
|
||||||
if let Identity::SignedOut = restore(&backend, &receiver, cx).await? {
|
.map(|url| (*url).to_owned())
|
||||||
bail!("no identity on this device");
|
.collect()
|
||||||
|
} else {
|
||||||
|
defaults
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
backend.update(cx, |backend, cx| backend.sign_out(cx)).await
|
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.
|
/// Reads one line from a file, without its line ending.
|
||||||
@@ -281,33 +600,3 @@ fn read_passphrase(path: Option<&Path>) -> anyhow::Result<String> {
|
|||||||
None => Ok(rpassword::prompt_password("Passphrase: ")?),
|
None => Ok(rpassword::prompt_password("Passphrase: ")?),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads the passphrase for a new key, confirming it when it is typed.
|
|
||||||
fn new_passphrase(path: Option<&Path>) -> anyhow::Result<String> {
|
|
||||||
let Some(path) = path else {
|
|
||||||
let passphrase = rpassword::prompt_password("Choose a passphrase: ")?;
|
|
||||||
if passphrase != rpassword::prompt_password("Confirm passphrase: ")? {
|
|
||||||
bail!("passphrases do not match");
|
|
||||||
}
|
|
||||||
|
|
||||||
return Ok(passphrase);
|
|
||||||
};
|
|
||||||
|
|
||||||
read_line(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads the credential from `path`, or from the terminal without echoing it.
|
|
||||||
fn read_credential(path: Option<&Path>) -> anyhow::Result<String> {
|
|
||||||
match path {
|
|
||||||
Some(path) => read_line(path),
|
|
||||||
None => Ok(rpassword::prompt_password(
|
|
||||||
"Credential (nsec, ncryptsec or bunker URI): ",
|
|
||||||
)?),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn print_identity(public_key: PublicKey) -> anyhow::Result<()> {
|
|
||||||
println!("npub: {}", public_key.to_bech32()?);
|
|
||||||
println!("hex: {public_key}");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -127,9 +127,11 @@ impl AppRoot {
|
|||||||
pub fn mount(window: &mut Window, cx: &mut App) -> Entity<Root> {
|
pub fn mount(window: &mut Window, cx: &mut App) -> Entity<Root> {
|
||||||
let root = cx.new(|cx| Root::new(window, cx));
|
let root = cx.new(|cx| Root::new(window, cx));
|
||||||
let content = cx.new(|cx| AppRoot::new(window, cx));
|
let content = cx.new(|cx| AppRoot::new(window, cx));
|
||||||
|
|
||||||
root.update(cx, |root, cx| {
|
root.update(cx, |root, cx| {
|
||||||
root.set_content(content, cx);
|
root.set_content(content, cx);
|
||||||
});
|
});
|
||||||
|
|
||||||
root
|
root
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ impl Render for ExitDialog {
|
|||||||
.label("Exit")
|
.label("Exit")
|
||||||
.variant(ButtonVariant::Destructive)
|
.variant(ButtonVariant::Destructive)
|
||||||
.on_click(move |_, _, cx| {
|
.on_click(move |_, _, cx| {
|
||||||
backend.update(cx, |backend, cx| backend.sign_out(cx)).detach();
|
backend.update(cx, |backend, cx| backend.sign_out(cx));
|
||||||
confirm_close.close(cx);
|
confirm_close.close(cx);
|
||||||
})
|
})
|
||||||
.into_any_element(),
|
.into_any_element(),
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use nostr::event::IntoEventBuilder;
|
|||||||
use nostr::nips::nip19::Nip19Coordinate;
|
use nostr::nips::nip19::Nip19Coordinate;
|
||||||
use nostr_connect::prelude::*;
|
use nostr_connect::prelude::*;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use signed_core::{Announcement, Filters, RepoAddr};
|
use signed_core::{Announcement, Deletions, Filters, RepoAddr};
|
||||||
use signed_git::{GitCache, Repo};
|
use signed_git::{GitCache, Repo};
|
||||||
use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update};
|
use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update};
|
||||||
|
|
||||||
@@ -41,8 +41,6 @@ pub enum BackendEvent {
|
|||||||
status: PushStepStatus,
|
status: PushStepStatus,
|
||||||
},
|
},
|
||||||
Error(String),
|
Error(String),
|
||||||
/// The relay list, profile and grasp list of a new identity were published; `Err` when no relay took them.
|
|
||||||
IdentityPublished(Result<(), String>),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BackendEvent {
|
impl BackendEvent {
|
||||||
@@ -231,7 +229,7 @@ impl Backend {
|
|||||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
let content = match user.await {
|
let content = match user.await {
|
||||||
Ok(Some((_username, secret))) => String::from_utf8(secret)?,
|
Ok(Some((_username, secret))) => String::from_utf8(secret)?,
|
||||||
_ => {
|
Ok(None) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
if this.session == session {
|
if this.session == session {
|
||||||
cx.emit(BackendEvent::SignerRequired);
|
cx.emit(BackendEvent::SignerRequired);
|
||||||
@@ -239,6 +237,17 @@ impl Backend {
|
|||||||
})?;
|
})?;
|
||||||
return Ok(());
|
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 {
|
let result = async {
|
||||||
@@ -552,19 +561,13 @@ impl Backend {
|
|||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
let published = futures::future::try_join_all(publishes)
|
if let Err(error) = futures::future::try_join_all(publishes).await {
|
||||||
.await
|
|
||||||
.map(|_| ())
|
|
||||||
.map_err(|error| {
|
|
||||||
format!("identity created, but publishing it failed: {error}")
|
|
||||||
});
|
|
||||||
|
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
if let Err(message) = &published {
|
cx.emit(BackendEvent::error(format!(
|
||||||
cx.emit(BackendEvent::error(message.clone()));
|
"identity created, but publishing it failed: {error}"
|
||||||
}
|
)));
|
||||||
cx.emit(BackendEvent::IdentityPublished(published));
|
|
||||||
})?;
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok::<(), anyhow::Error>(())
|
Ok::<(), anyhow::Error>(())
|
||||||
})
|
})
|
||||||
@@ -1086,6 +1089,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>) {
|
fn bootstrap_user(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
|
||||||
let client = self.client.clone();
|
let client = self.client.clone();
|
||||||
|
|
||||||
@@ -1161,8 +1203,9 @@ impl Backend {
|
|||||||
self.passphrase_required
|
self.passphrase_required
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sign_out(&mut self, cx: &mut Context<Self>) -> Task<Result<(), Error>> {
|
pub fn sign_out(&mut self, cx: &mut Context<Self>) {
|
||||||
self.supersede_session();
|
self.supersede_session();
|
||||||
|
|
||||||
// Nothing may be signed with the identity the user just left.
|
// Nothing may be signed with the identity the user just left.
|
||||||
self.signer.swap_inner(Keys::generate());
|
self.signer.swap_inner(Keys::generate());
|
||||||
self.current_user = None;
|
self.current_user = None;
|
||||||
@@ -1173,11 +1216,6 @@ impl Backend {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let delete = cx.delete_credentials(USER_KEYRING);
|
let delete = cx.delete_credentials(USER_KEYRING);
|
||||||
|
|
||||||
cx.emit(BackendEvent::SignerChanged);
|
|
||||||
cx.emit(BackendEvent::SignerRequired);
|
|
||||||
cx.notify();
|
|
||||||
|
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
if let Err(error) = delete.await {
|
if let Err(error) = delete.await {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
@@ -1189,6 +1227,12 @@ impl Backend {
|
|||||||
|
|
||||||
Ok::<(), Error>(())
|
Ok::<(), Error>(())
|
||||||
})
|
})
|
||||||
|
.detach();
|
||||||
|
|
||||||
|
cx.emit(BackendEvent::SignerChanged);
|
||||||
|
cx.emit(BackendEvent::SignerRequired);
|
||||||
|
|
||||||
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sync_inbox(&mut self, cx: &mut Context<Self>) {
|
fn sync_inbox(&mut self, cx: &mut Context<Self>) {
|
||||||
|
|||||||
@@ -34,12 +34,8 @@ pub use sync_status::{CheckoutSyncStatus, SyncEvent, SyncStatusDirectory, SyncSt
|
|||||||
pub fn init(cx: &mut App) -> anyhow::Result<()> {
|
pub fn init(cx: &mut App) -> anyhow::Result<()> {
|
||||||
SettingsStore::set_global(cx.new(|_| SettingsStore::new(paths::settings_file())), cx);
|
SettingsStore::set_global(cx.new(|_| SettingsStore::new(paths::settings_file())), cx);
|
||||||
|
|
||||||
let scan_paths = SettingsStore::global(cx)
|
let settings = SettingsStore::global(cx);
|
||||||
.read(cx)
|
let scan_paths = settings.read(cx).settings().local_repos.scan_paths.clone();
|
||||||
.settings()
|
|
||||||
.local_repos
|
|
||||||
.scan_paths
|
|
||||||
.clone();
|
|
||||||
|
|
||||||
for dir in [paths::nostr_dir(), paths::repos_dir()] {
|
for dir in [paths::nostr_dir(), paths::repos_dir()] {
|
||||||
if let Err(error) = std::fs::create_dir_all(dir) {
|
if let Err(error) = std::fs::create_dir_all(dir) {
|
||||||
|
|||||||
+8
-7
@@ -3,6 +3,7 @@ use std::sync::Arc;
|
|||||||
use gpui::*;
|
use gpui::*;
|
||||||
use gpui_platform::application;
|
use gpui_platform::application;
|
||||||
use settings::SettingsStore;
|
use settings::SettingsStore;
|
||||||
|
use signed_app::AppRoot;
|
||||||
use ui::theme::{ActiveTheme as _, Theme};
|
use ui::theme::{ActiveTheme as _, Theme};
|
||||||
|
|
||||||
actions!(signed, [Quit]);
|
actions!(signed, [Quit]);
|
||||||
@@ -44,8 +45,6 @@ fn main() {
|
|||||||
.with_assets(AppAssets)
|
.with_assets(AppAssets)
|
||||||
.with_http_client(Arc::new(reqwest_client::ReqwestClient::new()))
|
.with_http_client(Arc::new(reqwest_client::ReqwestClient::new()))
|
||||||
.run(move |cx| {
|
.run(move |cx| {
|
||||||
ui::init(cx);
|
|
||||||
|
|
||||||
cx.bind_keys([
|
cx.bind_keys([
|
||||||
KeyBinding::new("cmd-q", Quit, None),
|
KeyBinding::new("cmd-q", Quit, None),
|
||||||
KeyBinding::new("ctrl-q", Quit, None),
|
KeyBinding::new("ctrl-q", Quit, None),
|
||||||
@@ -54,16 +53,18 @@ fn main() {
|
|||||||
cx.on_action(|_: &Quit, cx| cx.quit());
|
cx.on_action(|_: &Quit, cx| cx.quit());
|
||||||
cx.set_app_identity("build.signed.signed", "Signed");
|
cx.set_app_identity("build.signed.signed", "Signed");
|
||||||
|
|
||||||
|
ui::init(cx);
|
||||||
|
metadata::init(cx);
|
||||||
|
|
||||||
if let Err(error) = signed_state::init(cx) {
|
if let Err(error) = signed_state::init(cx) {
|
||||||
tracing::error!("failed to initialize application state: {error:#}");
|
tracing::error!("failed to initialize application state: {error:#}");
|
||||||
cx.quit();
|
cx.quit();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let appearance = SettingsStore::global(cx).read(cx).settings().appearance;
|
let settings = SettingsStore::global(cx);
|
||||||
signed_app::AppRoot::apply_appearance_mode(appearance, cx);
|
let appearance = settings.read(cx).settings().appearance;
|
||||||
|
AppRoot::apply_appearance_mode(appearance, cx);
|
||||||
metadata::init(cx);
|
|
||||||
|
|
||||||
let theme = cx.theme();
|
let theme = cx.theme();
|
||||||
let bounds = Bounds::centered(None, size(px(1120.0), px(750.0)), cx);
|
let bounds = Bounds::centered(None, size(px(1120.0), px(750.0)), cx);
|
||||||
@@ -97,7 +98,7 @@ fn main() {
|
|||||||
})
|
})
|
||||||
.detach();
|
.detach();
|
||||||
|
|
||||||
signed_app::AppRoot::mount(window, cx)
|
AppRoot::mount(window, cx)
|
||||||
}) {
|
}) {
|
||||||
tracing::error!("failed to open window: {error}");
|
tracing::error!("failed to open window: {error}");
|
||||||
cx.quit();
|
cx.quit();
|
||||||
|
|||||||
Reference in New Issue
Block a user