Skip to main content

sapphire_sync_cli/
lib.rs

1//! `sapphire-sync`: the app's command line, Syncthing-style.
2//!
3//! As `serve`, it is the embedded server (`sapphire-sync-server`); every other
4//! subcommand is a one-shot invocation that talks to that server over the
5//! local socket — the app's own `sync` verb and the framework's (`status`,
6//! `service`, `workspace`, `api-key`, `config`, …).
7//!
8//! The modules are a library so the integration tests can link them, and so
9//! both editions run the same commands ([`run`]): the headless one
10//! (`sapphire-sync-headless`) and the desktop app, which runs them when given
11//! a subcommand. Both put `sapphire-sync` on PATH.
12
13pub mod cli;
14pub mod sync;
15
16use std::path::{Path, PathBuf};
17
18use sapphire_sync_core::CTX;
19use sapphire_sync_core::framework::server::FrameworkCommand;
20use sapphire_sync_core::framework::workspace::AppKind;
21use sapphire_sync_server as server;
22
23pub use sapphire_sync_server::Edition;
24
25use crate::cli::AppCommand;
26
27/// Run one command as `edition`, exiting the process with its code.
28///
29/// An error is returned for the caller to print with [`exit_with`], in the
30/// app's own `sapphire-sync: {err}` shape.
31pub fn run(command: AppCommand, edition: Edition) -> anyhow::Result<()> {
32    // First statement after parsing: what this process is decides where its
33    // state lives (and the secrets migration it runs). `serve` is the server;
34    // every other verb is a one-shot CLI.
35    CTX.init(match command {
36        AppCommand::Framework(FrameworkCommand::Serve) => AppKind::Server,
37        _ => AppKind::Cli,
38    });
39
40    let runtime = tokio::runtime::Builder::new_multi_thread()
41        .enable_all()
42        .build()?;
43    runtime.block_on(dispatch(command, edition))
44}
45
46/// Print `err` the app's way — the program name, the message (Display, not the
47/// Debug dump) — and exit 1. A plain `Result` main would print
48/// `Error: {err:?}` instead.
49pub fn exit_with(err: anyhow::Error) -> ! {
50    eprintln!("sapphire-sync: {err}");
51    std::process::exit(1);
52}
53
54async fn dispatch(command: AppCommand, edition: Edition) -> anyhow::Result<()> {
55    match command {
56        // The app's own verbs come first.
57        AppCommand::Sync(command) => {
58            let code = sync::dispatch(command).await?;
59            std::process::exit(code);
60        }
61        // `serve` is the server the service manager starts (`service_spec` is
62        // `["serve"]`), so it must get the sync-mounted server, not the
63        // one-shot one. This is the only place the bridge is opened. The
64        // framework builds it again on every in-place restart.
65        AppCommand::Framework(FrameworkCommand::Serve) => {
66            let exe = std::env::current_exe()?;
67            let code = FrameworkCommand::Serve
68                .dispatch(
69                    &CTX,
70                    (),
71                    |settings| server::build_serve(settings, &exe, edition),
72                    server::VERSION,
73                )
74                .await?;
75            std::process::exit(code);
76        }
77        // Warned first: the exit code is the report's.
78        AppCommand::Framework(FrameworkCommand::Status) => {
79            warn_if_shadowed();
80            oneshot(FrameworkCommand::Status, edition).await
81        }
82        AppCommand::Framework(command) => oneshot(command, edition).await,
83    }
84}
85
86/// Every framework verb but `serve`. One-shots dispatch against a bridge-less
87/// server — `status` on a host without a running server must say the
88/// framework's "no … server is running", not a bridge error — and the exit
89/// code is the process's. The app has no settings of its own (`()`).
90async fn oneshot(command: FrameworkCommand, edition: Edition) -> anyhow::Result<()> {
91    let code = command
92        .dispatch(
93            &CTX,
94            (),
95            |settings| server::build_oneshot(settings, edition),
96            server::VERSION,
97        )
98        .await?;
99    std::process::exit(code);
100}
101
102/// The command both editions put on PATH.
103const COMMAND: &str = "sapphire-sync";
104
105/// Warn when the `sapphire-sync` on PATH is another executable than this one:
106/// with both the headless edition and the desktop app installed, the one a
107/// shell or an MCP client runs may not be the one the service was registered
108/// with.
109fn warn_if_shadowed() {
110    let Ok(this) = std::env::current_exe().and_then(std::fs::canonicalize) else {
111        return;
112    };
113    let Some(on_path) = std::env::var_os("PATH").and_then(|path| find_on_path(&path)) else {
114        return;
115    };
116    if std::fs::canonicalize(&on_path).is_ok_and(|found| found != this) {
117        eprintln!(
118            "warning: `{COMMAND}` on PATH is {}, not this executable ({}); \
119             keep only one of the headless edition and the desktop app installed",
120            on_path.display(),
121            this.display(),
122        );
123    }
124}
125
126/// The first `sapphire-sync` executable in `path`, a `PATH` value.
127fn find_on_path(path: &std::ffi::OsStr) -> Option<PathBuf> {
128    let file = format!("{COMMAND}{}", std::env::consts::EXE_SUFFIX);
129    std::env::split_paths(path)
130        .map(|dir| dir.join(&file))
131        .find(|candidate| Path::is_file(candidate))
132}