pub mod cli;
pub mod sync;
use std::path::{Path, PathBuf};
use sapphire_sync_core::CTX;
use sapphire_sync_core::framework::server::FrameworkCommand;
use sapphire_sync_core::framework::workspace::AppKind;
use sapphire_sync_server as server;
pub use sapphire_sync_server::Edition;
use crate::cli::AppCommand;
pub fn run(command: AppCommand, edition: Edition) -> anyhow::Result<()> {
CTX.init(match command {
AppCommand::Framework(FrameworkCommand::Serve) => AppKind::Server,
_ => AppKind::Cli,
});
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
runtime.block_on(dispatch(command, edition))
}
pub fn exit_with(err: anyhow::Error) -> ! {
eprintln!("sapphire-sync: {err}");
std::process::exit(1);
}
async fn dispatch(command: AppCommand, edition: Edition) -> anyhow::Result<()> {
match command {
AppCommand::Sync(command) => {
let code = sync::dispatch(command).await?;
std::process::exit(code);
}
AppCommand::Framework(FrameworkCommand::Serve) => {
let exe = std::env::current_exe()?;
let code = FrameworkCommand::Serve
.dispatch(
&CTX,
(),
|settings| server::build_serve(settings, &exe, edition),
server::VERSION,
)
.await?;
std::process::exit(code);
}
AppCommand::Framework(FrameworkCommand::Status) => {
warn_if_shadowed();
oneshot(FrameworkCommand::Status, edition).await
}
AppCommand::Framework(command) => oneshot(command, edition).await,
}
}
async fn oneshot(command: FrameworkCommand, edition: Edition) -> anyhow::Result<()> {
let code = command
.dispatch(
&CTX,
(),
|settings| server::build_oneshot(settings, edition),
server::VERSION,
)
.await?;
std::process::exit(code);
}
const COMMAND: &str = "sapphire-sync";
fn warn_if_shadowed() {
let Ok(this) = std::env::current_exe().and_then(std::fs::canonicalize) else {
return;
};
let Some(on_path) = std::env::var_os("PATH").and_then(|path| find_on_path(&path)) else {
return;
};
if std::fs::canonicalize(&on_path).is_ok_and(|found| found != this) {
eprintln!(
"warning: `{COMMAND}` on PATH is {}, not this executable ({}); \
keep only one of the headless edition and the desktop app installed",
on_path.display(),
this.display(),
);
}
}
fn find_on_path(path: &std::ffi::OsStr) -> Option<PathBuf> {
let file = format!("{COMMAND}{}", std::env::consts::EXE_SUFFIX);
std::env::split_paths(path)
.map(|dir| dir.join(&file))
.find(|candidate| Path::is_file(candidate))
}