1use std::fmt::Write as _;
4use std::path::PathBuf;
5use std::sync::Arc;
6
7use corundum_framework_service::{Environment, ServiceCommand, SystemManager};
8use sapphire_backend::protocol as proto;
9use sapphire_bridge_client::BridgeClient;
10use sapphire_ipc::{ClientInfo, Endpoint};
11
12use crate::AppServer;
13use crate::error::{Error, Result};
14use crate::selection::SelectionFile;
15use crate::settings::{AppSettings, Settings};
16use sapphire_workspace::AppContext;
17
18mod config;
19
20pub use config::{AppConfigCommand, AppScopeFlags};
21
22pub use sapphire_backend::protocol::{StatusReport, StatusRow};
23
24#[derive(Debug, clap::Subcommand)]
48pub enum FrameworkCommand {
49 Serve,
51 Status,
53 #[command(subcommand)]
55 Service(ServiceCommand),
56 Update(AppUpdateArgs),
60 #[command(subcommand)]
63 Workspace(WorkspaceCommand),
64 #[command(subcommand)]
68 ApiKey(corundum_framework_keys::KeyCommand),
69 #[command(hide = true)]
71 ExternalDevice(LegacyExternalDevice),
72 #[command(subcommand)]
75 Config(AppConfigCommand),
76 #[cfg(feature = "mcp")]
79 Mcp,
80}
81
82impl FrameworkCommand {
83 pub async fn dispatch<A, F>(
99 self,
100 ctx: &'static AppContext,
101 owner: A,
102 build: F,
103 version: &'static str,
104 ) -> Result<i32>
105 where
106 A: AppSettings + Clone,
107 F: Fn(&Settings) -> AppServer,
108 {
109 let app = ctx.app_name;
110 let server = |owner: A| -> Result<AppServer> {
114 Ok(build(&settings_or_defaults(ctx, Arc::new(owner))?))
115 };
116 match self {
117 FrameworkCommand::Serve => {
118 crate::serve_restarting(ctx, owner, build).await?;
119 Ok(0)
120 }
121 FrameworkCommand::Status => {
122 let endpoint = Endpoint::for_app(app)?;
123 run_status(&endpoint, app, version).await
124 }
125 FrameworkCommand::Service(command) => {
126 let spec = server(owner)?.service_spec();
127 command
128 .run(&spec, &Environment::detect(), &SystemManager)
129 .map_err(Error::from)
130 }
131 FrameworkCommand::Update(args) => {
132 let server = server(owner)?;
133 let own = match server.release_source() {
134 Some(source) => {
135 sapphire_framework_update::run(&args.update, source, app, version)
136 .await
137 .map_err(Error::from)
138 }
139 None => {
140 println!("{app} does not say where its releases are");
141 Ok(1)
142 }
143 };
144 let bridge = if args.no_bridge {
147 0
148 } else {
149 update_bridge(&args.update).await?
150 };
151 Ok(own?.max(bridge))
152 }
153 FrameworkCommand::Config(command) => config::config(ctx, owner, command, version).await,
154 FrameworkCommand::Workspace(command) => command.dispatch(app, version).await,
155 FrameworkCommand::ApiKey(command) => {
156 api_key(ctx, &server(owner)?.profiles().list(), command)
157 }
158 FrameworkCommand::ExternalDevice(legacy) => {
159 eprintln!("warning: `external-device` is renamed to `api-key`");
160 if !legacy.app.is_empty() {
161 eprintln!(
162 "API keys are per workspace now, not per application: `--app` is not taken"
163 );
164 return Ok(2);
165 }
166 api_key(ctx, &server(owner)?.profiles().list(), legacy.command)
167 }
168 #[cfg(feature = "mcp")]
169 FrameworkCommand::Mcp => {
170 server(owner)?.serve_mcp_stdio(version).await?;
171 Ok(0)
172 }
173 }
174 }
175}
176
177fn settings_or_defaults(ctx: &AppContext, owner: Arc<dyn AppSettings>) -> Result<Settings> {
183 match Settings::load(ctx, Arc::clone(&owner)) {
184 Ok(settings) => Ok(settings),
185 Err(err) => {
186 let file = Settings::device_file(ctx)
187 .map_or_else(|| "the settings".to_owned(), |f| f.display().to_string());
188 eprintln!("warning: could not read {file} ({err}); going on with the default settings");
189 Settings::defaults(ctx, owner)
190 }
191 }
192}
193
194#[derive(Clone, Debug, Default, clap::Args)]
196pub struct AppUpdateArgs {
197 #[command(flatten)]
199 pub update: sapphire_framework_update::UpdateArgs,
200 #[arg(long)]
202 pub no_bridge: bool,
203}
204
205const BRIDGE_BINARY: &str = "sapphire-bridge";
207
208const BRIDGE_RELEASES: &str = "https://github.com/sapphire-turtle/sapphire-framework/releases";
210
211fn find_on_path(name: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
213 let file = format!("{name}{}", std::env::consts::EXE_SUFFIX);
214 std::env::split_paths(path?)
215 .map(|dir| dir.join(&file))
216 .find(|candidate| candidate.is_file())
217}
218
219pub async fn update_bridge(args: &sapphire_framework_update::UpdateArgs) -> Result<i32> {
223 match find_on_path(BRIDGE_BINARY, std::env::var_os("PATH").as_deref()) {
224 Some(exe) => run_bridge_update(&exe, args).await,
225 None => {
226 println!("{BRIDGE_BINARY} is not on PATH; not updating it");
227 Ok(0)
228 }
229 }
230}
231
232async fn run_bridge_update(
238 exe: &std::path::Path,
239 args: &sapphire_framework_update::UpdateArgs,
240) -> Result<i32> {
241 let knows_update = tokio::process::Command::new(exe)
243 .args(["update", "--help"])
244 .stdout(std::process::Stdio::null())
245 .stderr(std::process::Stdio::null())
246 .status()
247 .await?
248 .success();
249 if !knows_update {
250 println!(
251 "{} cannot update itself; install the newest from {BRIDGE_RELEASES}",
252 exe.display()
253 );
254 return Ok(1);
255 }
256 let mut command = tokio::process::Command::new(exe);
257 command.arg("update");
258 if args.check {
259 command.arg("--check");
260 }
261 if args.yes {
262 command.arg("--yes");
263 }
264 let status = command.status().await?;
266 Ok(status.code().unwrap_or(1))
267}
268
269#[derive(Debug, clap::Subcommand)]
276pub enum WorkspaceCommand {
277 Init {
279 dir: Option<PathBuf>,
282 #[arg(long)]
284 sync: bool,
285 #[arg(long, value_name = "NAME|ID", requires = "sync")]
288 remote_workspace: Option<String>,
289 },
290 Select {
292 dir: Option<PathBuf>,
295 #[arg(long)]
298 sync: bool,
299 },
300 #[command(subcommand)]
302 Sync(WorkspaceSyncCommand),
303 Show,
305 Move {
307 dir: PathBuf,
309 },
310 Remove {
312 #[arg(long)]
314 delete: bool,
315 },
316}
317
318impl WorkspaceCommand {
319 pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
324 match self {
325 WorkspaceCommand::Init {
326 dir,
327 sync,
328 remote_workspace,
329 } => workspace_init(app, version, dir, sync, remote_workspace).await,
330 WorkspaceCommand::Select { dir, sync } => {
331 workspace_select(app, version, dir, sync).await
332 }
333 WorkspaceCommand::Sync(command) => workspace_sync(app, version, command).await,
334 WorkspaceCommand::Show => workspace_show(app, version).await,
335 WorkspaceCommand::Move { dir } => workspace_move(app, version, dir).await,
336 WorkspaceCommand::Remove { delete } => workspace_remove(app, version, delete).await,
337 }
338 }
339}
340
341#[derive(Debug, clap::Subcommand)]
343pub enum WorkspaceSyncCommand {
344 Enable,
346 Disable,
349 Status,
351}
352
353#[derive(Debug, clap::Args)]
355pub struct LegacyExternalDevice {
356 #[arg(long = "app", global = true, hide = true)]
358 app: Vec<String>,
359 #[command(subcommand)]
360 command: corundum_framework_keys::KeyCommand,
361}
362
363fn api_key(
367 ctx: &AppContext,
368 profiles: &[sapphire_framework_keys::Profile],
369 command: corundum_framework_keys::KeyCommand,
370) -> Result<i32> {
371 let Some(selection) = SelectionFile::for_app(ctx).load(ctx.app_name)? else {
372 eprintln!(
373 "{} serves no workspace yet: choose one with `{} workspace select <dir>`",
374 ctx.app_name, ctx.app_name
375 );
376 return Ok(1);
377 };
378 if !selection.root.join(format!(".{}", ctx.app_name)).is_dir() {
380 eprintln!(
381 "the workspace at {} is not reachable: bring it back, or choose another with `{} workspace select <dir>`",
382 selection.root.display(),
383 ctx.app_name
384 );
385 return Ok(1);
386 }
387 let run = sapphire_framework_keys::open_store(ctx.app_name, &selection.root)
388 .and_then(|mut store| command.run(&mut store, profiles));
389 match run {
390 Ok(code) => Ok(code),
391 Err(err) => {
392 eprintln!("{err}");
393 Ok(1)
394 }
395 }
396}
397
398async fn workspace_init(
411 app: &'static str,
412 version: &'static str,
413 dir: Option<PathBuf>,
414 sync: bool,
415 remote_workspace: Option<String>,
416) -> Result<i32> {
417 let endpoint = Endpoint::for_app(app)?;
418 let client_info = ClientInfo {
419 kind: "cli".to_owned(),
420 version: version.to_owned(),
421 api: proto::API_VERSION,
422 app_api: None,
423 pid: std::process::id(),
424 };
425 let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
426 else {
427 println!("no {app} server is running");
428 return Ok(1);
429 };
430
431 let dir = workspace_dir(app, dir)?;
432 if let Some(selector) = remote_workspace {
433 std::fs::create_dir_all(&dir)?;
435 let mapped: proto::SyncEnableResult = client
436 .call(
437 proto::SYNC_MAP,
438 proto::SyncMapParams {
439 workspace: selector.clone(),
440 dir: dir.clone(),
441 },
442 )
443 .await?;
444 println!(
445 "initialized {app} workspace in {} from {selector}",
446 dir.display()
447 );
448 println!(
449 "the {app} server now serves it, syncing as {}",
450 mapped.workspace_id
451 );
452 return Ok(0);
453 }
454 let result: proto::WorkspaceInitResult = client
455 .call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
456 .await?;
457 if result.created {
458 println!("initialized {app} workspace in {}", result.root.display());
459 } else {
460 println!(
461 "{} already exists (workspace {})",
462 result.root.display(),
463 result.workspace_id
464 );
465 }
466 println!("the {app} server now serves {}", result.root.display());
467
468 if sync {
469 enable_sync(&client).await?;
470 }
471 Ok(0)
472}
473
474async fn enable_sync(client: &sapphire_ipc::Client) -> Result<()> {
480 let enabled: proto::SyncEnableResult = client
481 .call(proto::SYNC_ENABLE, serde_json::json!({}))
482 .await?;
483 let status: proto::SyncStatusResult = client
486 .call(proto::SYNC_STATUS, serde_json::json!({}))
487 .await
488 .unwrap_or(proto::SyncStatusResult {
489 enabled: true,
490 workspace_id: Some(enabled.workspace_id),
491 ..proto::SyncStatusResult::not_synced()
492 });
493 println!(
494 "syncing as {} ({} peer{})",
495 enabled.workspace_id,
496 status.peers,
497 if status.peers == 1 { "" } else { "s" }
498 );
499 Ok(())
500}
501
502async fn workspace_sync(
504 app: &'static str,
505 version: &'static str,
506 command: WorkspaceSyncCommand,
507) -> Result<i32> {
508 let Some(client) = connect_app(app, version).await? else {
509 return Ok(1);
510 };
511 match command {
512 WorkspaceSyncCommand::Enable => enable_sync(&client).await?,
513 WorkspaceSyncCommand::Disable => {
514 let _: proto::Ack = client
515 .call(proto::SYNC_DISABLE, serde_json::json!({}))
516 .await?;
517 println!("sync is off for the {app} workspace on this host; it keeps its sync id");
518 }
519 WorkspaceSyncCommand::Status => {
520 let status: proto::SyncStatusResult = client
521 .call(proto::SYNC_STATUS, serde_json::json!({}))
522 .await?;
523 for line in describe_sync(&status) {
524 println!("{line}");
525 }
526 }
527 }
528 Ok(0)
529}
530
531fn describe_sync(status: &proto::SyncStatusResult) -> Vec<String> {
533 let mut lines = vec![format!(
534 "sync: {}",
535 if status.enabled { "on" } else { "off" }
536 )];
537 if let Some(id) = status.workspace_id {
538 lines.push(format!("workspace id: {id}"));
539 }
540 if status.enabled {
541 lines.push(format!(
542 "peers: {}{}",
543 status.peers,
544 if matches!(status.topology, proto::Topology::Star { .. }) {
545 " (star)"
546 } else {
547 ""
548 }
549 ));
550 lines.push(format!(
551 "bridge: {}",
552 if status.bridge_available {
553 "reachable"
554 } else {
555 "not reachable"
556 }
557 ));
558 }
559 if let Some(paused) = &status.paused {
560 lines.push(format!("paused: {paused}"));
561 }
562 if let Some(error) = &status.last_error {
563 lines.push(format!("last error: {error}"));
564 }
565 lines
566}
567
568pub async fn render_workspace(client: &sapphire_ipc::Client, out: &mut String) -> Result<i32> {
573 let current: proto::WorkspaceCurrentResult = client
574 .call(proto::WORKSPACE_CURRENT, serde_json::json!({}))
575 .await?;
576 let Some(ws) = current.workspace else {
577 writeln!(
578 out,
579 "no workspace yet; run `workspace init <dir>` or `workspace select <dir>`"
580 )
581 .expect("writing to a String cannot fail");
582 return Ok(1);
583 };
584 writeln!(out, "{} {}", ws.root.display(), describe_state(&ws))
585 .expect("writing to a String cannot fail");
586 Ok(0)
587}
588
589fn describe_state(ws: &proto::CurrentWorkspace) -> String {
591 let state = if !ws.reachable {
592 "unreachable"
593 } else if ws.sync.enabled {
594 "synced"
595 } else {
596 "not synced"
597 };
598 let star = if matches!(ws.sync.topology, proto::Topology::Star { .. }) {
599 " (star)"
600 } else {
601 ""
602 };
603 let pending = match &ws.sync.embedding {
604 Some(e) if e.pending > 0 => format!(", embedding {} pending", e.pending),
605 _ => String::new(),
606 };
607 format!("{state}{star}{pending}")
608}
609
610fn workspace_dir(app: &str, dir: Option<PathBuf>) -> std::io::Result<PathBuf> {
616 Ok(match dir {
617 Some(dir) => std::env::current_dir()?.join(dir),
618 None => sapphire_workspace::default_workspace_dir(app),
619 })
620}
621
622async fn connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
624 let client = try_connect_app(app, version).await?;
625 if client.is_none() {
626 println!("no {app} server is running");
627 }
628 Ok(client)
629}
630
631async fn try_connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
633 let endpoint = Endpoint::for_app(app)?;
634 let client_info = ClientInfo {
635 kind: "cli".to_owned(),
636 version: version.to_owned(),
637 api: proto::API_VERSION,
638 app_api: None,
639 pid: std::process::id(),
640 };
641 let client = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?;
642 Ok(client.map(|(c, _)| c))
643}
644
645async fn workspace_select(
647 app: &'static str,
648 version: &'static str,
649 dir: Option<PathBuf>,
650 sync: bool,
651) -> Result<i32> {
652 let Some(client) = connect_app(app, version).await? else {
653 return Ok(1);
654 };
655 let dir = workspace_dir(app, dir)?;
656 let ws: proto::CurrentWorkspace = client
657 .call(
658 proto::WORKSPACE_SELECT,
659 proto::WorkspaceSelectParams { dir },
660 )
661 .await?;
662 println!("{} {}", ws.root.display(), describe_state(&ws));
663 if sync && !ws.sync.enabled {
665 enable_sync(&client).await?;
666 }
667 Ok(0)
668}
669
670async fn workspace_move(app: &'static str, version: &'static str, dir: PathBuf) -> Result<i32> {
672 let Some(client) = connect_app(app, version).await? else {
673 return Ok(1);
674 };
675 let dir = std::env::current_dir()?.join(dir);
677 let ws: proto::CurrentWorkspace = client
678 .call(proto::WORKSPACE_MOVE, proto::WorkspaceMoveParams { dir })
679 .await?;
680 println!("{} {}", ws.root.display(), describe_state(&ws));
681 Ok(0)
682}
683
684async fn workspace_remove(app: &'static str, version: &'static str, delete: bool) -> Result<i32> {
686 let Some(client) = connect_app(app, version).await? else {
687 return Ok(1);
688 };
689 let _: proto::Ack = client
690 .call(
691 proto::WORKSPACE_REMOVE,
692 proto::WorkspaceRemoveParams { delete },
693 )
694 .await?;
695 println!(
696 "{}",
697 if delete {
698 "removed and deleted"
699 } else {
700 "removed; the files stay"
701 }
702 );
703 Ok(0)
704}
705
706async fn workspace_show(app: &'static str, version: &'static str) -> Result<i32> {
712 let Some(client) = connect_app(app, version).await? else {
713 return Ok(1);
714 };
715 let mut out = String::new();
716 let code = render_workspace_show(Arc::new(client), app, &mut out).await?;
717 for line in out.lines() {
718 println!("{line}");
719 }
720 Ok(code)
721}
722
723#[doc(hidden)]
728pub async fn render_workspace_show(
729 client: Arc<sapphire_ipc::Client>,
730 app: &str,
731 out: &mut String,
732) -> Result<i32> {
733 let code = render_workspace(&client, out).await?;
734 let bridge = BridgeClient::relayed(client, sapphire_ipc::runtime_dir()?);
735 let workspaces = match bridge.workspaces().await {
736 Ok(workspaces) => workspaces,
737 Err(sapphire_ipc::Error::NotRunning(_)) => {
738 writeln!(out, "no sapphire-bridge is running")
739 .expect("writing to a String cannot fail");
740 return Ok(code);
741 }
742 Err(error) => return Err(error.into()),
743 };
744 let mine: Vec<_> = workspaces
745 .workspaces
746 .into_iter()
747 .filter(|w| w.app_name == app)
748 .collect();
749 if !mine.is_empty() {
750 writeln!(out).expect("writing to a String cannot fail");
751 writeln!(out, "in the workgroup:").expect("writing to a String cannot fail");
752 for workspace in mine {
753 writeln!(out, "{} {}", workspace.name, workspace.workspace_id)
754 .expect("writing to a String cannot fail");
755 }
756 }
757 Ok(code)
758}
759
760async fn run_status(endpoint: &Endpoint, app: &str, version: &str) -> Result<i32> {
769 let mut out = String::new();
770 let code = run_status_into(endpoint, app, version, &mut out).await?;
771 for line in out.lines() {
772 println!("{line}");
773 }
774 Ok(code)
775}
776
777async fn run_status_into(
780 endpoint: &Endpoint,
781 app: &str,
782 version: &str,
783 out: &mut String,
784) -> Result<i32> {
785 let client_info = ClientInfo {
786 kind: "cli".to_owned(),
787 version: version.to_owned(),
788 api: proto::API_VERSION,
789 app_api: None,
790 pid: std::process::id(),
791 };
792 let Some((client, _)) = sapphire_ipc::connect_or_absent(endpoint, app, client_info).await?
793 else {
794 writeln!(out, "no {app} server is running").expect("writing to a String cannot fail");
797 return Ok(1);
798 };
799 let report: StatusReport = client
800 .call(
801 sapphire_backend::protocol::SERVER_INFO,
802 serde_json::json!({}),
803 )
804 .await?;
805 writeln!(out, "running: {}", report.running).expect("writing to a String cannot fail");
806 if let Some(version) = &report.version {
807 writeln!(out, "version: {version}").expect("writing to a String cannot fail");
808 }
809 if let Some(pid) = report.pid {
810 writeln!(out, "pid: {pid}").expect("writing to a String cannot fail");
811 }
812 if let Some(managed_by) = &report.managed_by {
813 writeln!(out, "managed_by: {managed_by:?}").expect("writing to a String cannot fail");
814 }
815 for row in &report.app {
816 writeln!(out, "{}: {}", row.name, row.value).expect("writing to a String cannot fail");
817 }
818 let update: Option<proto::UpdateStatus> = client
821 .call(proto::SERVER_UPDATE, serde_json::json!({}))
822 .await
823 .ok();
824 for line in describe_update(app, version, report.version.as_deref(), update.as_ref()) {
825 writeln!(out, "{line}").expect("writing to a String cannot fail");
826 }
827 Ok(0)
828}
829
830fn describe_update(
837 app: &str,
838 installed: &str,
839 running: Option<&str>,
840 update: Option<&proto::UpdateStatus>,
841) -> Vec<String> {
842 let parse = |v: &str| semver::Version::parse(v).ok();
843 let installed_v = parse(installed);
844 let mut lines = Vec::new();
845 if let Some(update) = update.filter(|u| u.enabled) {
846 match (&update.latest, &update.last_error) {
847 (Some(latest), _) => {
848 let newer = match (parse(&latest.version), &installed_v) {
849 (Some(latest), Some(installed)) => latest > *installed,
850 _ => update.update_available,
851 };
852 if newer {
853 lines.push(format!(
854 "update: {} is available ({})",
855 latest.version, latest.url
856 ));
857 } else {
858 lines.push(format!(
859 "update: up to date (latest release {})",
860 latest.version
861 ));
862 }
863 }
864 (None, Some(error)) => lines.push(format!("update: could not check: {error}")),
865 (None, None) => lines.push("update: not checked yet".to_owned()),
866 }
867 }
868 if let (Some(running), Some(installed)) = (running.and_then(parse), installed_v)
869 && installed > running
870 {
871 lines.push(format!(
872 "restart: needed: {installed} is installed but {running} is running; restart the {app} service"
873 ));
874 }
875 lines
876}
877#[cfg(test)]
878mod tests {
879 use super::*;
880 use clap::Parser;
881
882 #[derive(Parser)]
891 struct Probe {
892 #[command(subcommand)]
893 command: Command,
894 }
895
896 #[derive(Debug, clap::Subcommand)]
897 enum Command {
898 Greet,
900 #[command(flatten)]
901 Framework(FrameworkCommand),
902 }
903
904 #[derive(Parser)]
906 struct DesktopProbe {
907 #[command(subcommand)]
908 command: Option<Command>,
909 }
910
911 #[test]
912 fn a_desktop_binary_takes_the_same_verbs_or_none() {
913 let probe = DesktopProbe::try_parse_from(["app"]).unwrap();
914 assert!(probe.command.is_none());
915 let probe = DesktopProbe::try_parse_from(["app", "serve"]).unwrap();
916 assert!(matches!(
917 probe.command,
918 Some(Command::Framework(FrameworkCommand::Serve))
919 ));
920 let probe = DesktopProbe::try_parse_from(["app", "greet"]).unwrap();
921 assert!(matches!(probe.command, Some(Command::Greet)));
922 assert!(Probe::try_parse_from(["app"]).is_err());
924 }
925
926 #[test]
927 fn app_and_framework_commands_parse_side_by_side() {
928 let probe = Probe::try_parse_from(["app", "greet"]).unwrap();
929 assert!(matches!(probe.command, Command::Greet));
930 let probe = Probe::try_parse_from(["app", "serve"]).unwrap();
931 assert!(matches!(
932 probe.command,
933 Command::Framework(FrameworkCommand::Serve)
934 ));
935 let probe = Probe::try_parse_from(["app", "status"]).unwrap();
936 assert!(matches!(
937 probe.command,
938 Command::Framework(FrameworkCommand::Status)
939 ));
940 }
941
942 #[cfg(feature = "mcp")]
943 #[test]
944 fn the_mcp_command_parses_beside_the_apps() {
945 let probe = Probe::try_parse_from(["app", "mcp"]).unwrap();
946 assert!(matches!(
947 probe.command,
948 Command::Framework(FrameworkCommand::Mcp)
949 ));
950 }
951
952 #[test]
953 fn the_update_command_parses_with_and_without_the_bridge() {
954 let probe = Probe::try_parse_from(["app", "update", "--check", "-y"]).unwrap();
955 let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
956 panic!("not update");
957 };
958 assert!(args.update.check && args.update.yes && !args.no_bridge);
959 let probe = Probe::try_parse_from(["app", "update", "--no-bridge"]).unwrap();
960 let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
961 panic!("not update");
962 };
963 assert!(args.no_bridge);
964 }
965
966 #[test]
967 fn the_bridge_is_found_in_the_first_directory_of_path_that_has_it() {
968 let tmp = tempfile::tempdir().unwrap();
969 let (empty, first, second) = (
970 tmp.path().join("empty"),
971 tmp.path().join("first"),
972 tmp.path().join("second"),
973 );
974 let file = format!("sapphire-bridge{}", std::env::consts::EXE_SUFFIX);
975 for dir in [&empty, &first, &second] {
976 std::fs::create_dir(dir).unwrap();
977 }
978 std::fs::write(first.join(&file), b"").unwrap();
979 std::fs::write(second.join(&file), b"").unwrap();
980 let path = std::env::join_paths([&empty, &first, &second]).unwrap();
981 assert_eq!(
982 find_on_path("sapphire-bridge", Some(&path)),
983 Some(first.join(&file))
984 );
985 let path = std::env::join_paths([&empty]).unwrap();
986 assert_eq!(find_on_path("sapphire-bridge", Some(&path)), None);
987 assert_eq!(find_on_path("sapphire-bridge", None), None);
988 }
989
990 #[cfg(unix)]
992 fn script(dir: &std::path::Path, name: &str, body: &str) -> PathBuf {
993 use std::os::unix::fs::PermissionsExt;
994 let path = dir.join(name);
995 std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
996 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
997 path
998 }
999
1000 #[cfg(unix)]
1001 #[tokio::test]
1002 async fn the_bridge_runs_its_own_update_with_the_apps_flags() {
1003 let tmp = tempfile::tempdir().unwrap();
1004 let log = tmp.path().join("args");
1005 let exe = script(
1008 tmp.path(),
1009 "bridge",
1010 &format!(
1011 r#"case "$*" in *--help*) exit 0;; esac; echo "$@" > {}; exit 1"#,
1012 log.display()
1013 ),
1014 );
1015 let args = sapphire_framework_update::UpdateArgs {
1016 check: true,
1017 yes: true,
1018 };
1019 assert_eq!(run_bridge_update(&exe, &args).await.unwrap(), 1);
1020 assert_eq!(
1021 std::fs::read_to_string(&log).unwrap().trim(),
1022 "update --check --yes"
1023 );
1024 }
1025
1026 #[cfg(unix)]
1027 #[tokio::test]
1028 async fn a_bridge_without_update_is_not_run() {
1029 let tmp = tempfile::tempdir().unwrap();
1030 let runs = tmp.path().join("runs");
1031 let exe = script(
1033 tmp.path(),
1034 "bridge",
1035 &format!(r#"echo "$*" >> {}; exit 2"#, runs.display()),
1036 );
1037 let code = run_bridge_update(&exe, &Default::default()).await.unwrap();
1038 assert_eq!(code, 1);
1039 assert_eq!(
1040 std::fs::read_to_string(&runs).unwrap(),
1041 "update --help\n",
1042 "only the probe ran"
1043 );
1044 }
1045
1046 #[test]
1047 fn the_service_subcommands_parse() {
1048 for args in [
1049 vec!["app", "service", "install"],
1050 vec!["app", "service", "uninstall"],
1051 vec!["app", "service", "status"],
1052 ] {
1053 assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1054 }
1055 }
1056
1057 #[test]
1058 fn the_workspace_commands_parse() {
1059 for args in [
1060 vec!["app", "workspace", "init"],
1061 vec!["app", "workspace", "init", "papers"],
1062 vec!["app", "workspace", "init", "--sync"],
1063 vec!["app", "workspace", "show"],
1064 vec!["app", "workspace", "select", "papers"],
1065 vec!["app", "workspace", "select", "--sync"],
1066 vec!["app", "workspace", "select", "papers", "--sync"],
1067 vec!["app", "workspace", "sync", "enable"],
1068 vec!["app", "workspace", "sync", "disable"],
1069 vec!["app", "workspace", "sync", "status"],
1070 vec![
1071 "app",
1072 "workspace",
1073 "init",
1074 "--sync",
1075 "--remote-workspace=Ledger",
1076 ],
1077 vec![
1078 "app",
1079 "workspace",
1080 "init",
1081 "papers",
1082 "--sync",
1083 "--remote-workspace",
1084 "Ledger",
1085 ],
1086 vec!["app", "workspace", "move", "../papers"],
1087 vec!["app", "workspace", "remove"],
1088 vec!["app", "workspace", "remove", "--delete"],
1089 ] {
1090 assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1091 }
1092 }
1093
1094 #[test]
1095 fn a_remote_workspace_needs_sync() {
1096 let args = ["app", "workspace", "init", "--remote-workspace=Ledger"];
1097 assert!(Probe::try_parse_from(args).is_err());
1098 }
1099
1100 #[test]
1101 fn bare_invocation_prints_the_help() {
1102 #[derive(Parser)]
1106 #[command(arg_required_else_help = true)]
1107 struct Bare {
1108 #[command(subcommand)]
1109 command: Command,
1110 }
1111 let err = Bare::try_parse_from(["app"]).err().unwrap();
1112 assert_eq!(
1113 err.kind(),
1114 clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
1115 );
1116 }
1117}
1118
1119#[cfg(test)]
1120mod status_tests {
1121 use super::*;
1122 use sapphire_workspace::AppContext;
1123
1124 static CTX: AppContext = AppContext::new("sapphire-statustest");
1125
1126 async fn wait_until_listening(endpoint: &Endpoint) {
1132 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
1133 while !sapphire_ipc::probe(endpoint).await.unwrap() {
1134 assert!(
1135 tokio::time::Instant::now() < deadline,
1136 "the server never started listening"
1137 );
1138 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1139 }
1140 }
1141
1142 #[tokio::test]
1143 async fn status_reports_no_server_when_none_is_running() {
1144 let tmp = tempfile::tempdir().unwrap();
1145 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1146 let code = run_status(&endpoint, "status-test", "0.0.0").await.unwrap();
1147 assert_eq!(code, 1, "no server is a non-zero exit");
1148 }
1149
1150 fn update(latest: Option<&str>, error: Option<&str>) -> proto::UpdateStatus {
1151 proto::UpdateStatus {
1152 enabled: true,
1153 latest: latest.map(|version| proto::ReleaseInfo {
1154 version: version.to_owned(),
1155 url: format!("https://example.invalid/v{version}"),
1156 }),
1157 update_available: false,
1158 last_error: error.map(str::to_owned),
1159 }
1160 }
1161
1162 #[test]
1163 fn status_names_a_newer_release_and_nothing_when_up_to_date() {
1164 let lines = describe_update(
1165 "app",
1166 "0.19.0",
1167 Some("0.19.0"),
1168 Some(&update(Some("0.20.0"), None)),
1169 );
1170 assert_eq!(
1171 lines,
1172 vec!["update: 0.20.0 is available (https://example.invalid/v0.20.0)"]
1173 );
1174 let lines = describe_update(
1175 "app",
1176 "0.19.0",
1177 Some("0.19.0"),
1178 Some(&update(Some("0.19.0"), None)),
1179 );
1180 assert_eq!(lines, vec!["update: up to date (latest release 0.19.0)"]);
1181 }
1182
1183 #[test]
1184 fn status_asks_for_a_restart_when_the_installed_server_is_newer_than_the_running_one() {
1185 let lines = describe_update(
1188 "app",
1189 "0.20.0",
1190 Some("0.19.0"),
1191 Some(&update(Some("0.20.0"), None)),
1192 );
1193 assert_eq!(
1194 lines,
1195 vec![
1196 "update: up to date (latest release 0.20.0)",
1197 "restart: needed: 0.20.0 is installed but 0.19.0 is running; restart the app service",
1198 ]
1199 );
1200 let lines = describe_update("app", "0.20.0", Some("0.19.0"), None);
1202 assert_eq!(lines.len(), 1);
1203 assert!(lines[0].starts_with("restart: needed"));
1204 }
1205
1206 #[test]
1207 fn status_says_why_a_check_failed_and_nothing_when_checks_are_off() {
1208 let lines = describe_update(
1209 "app",
1210 "0.19.0",
1211 Some("0.19.0"),
1212 Some(&update(None, Some("offline"))),
1213 );
1214 assert_eq!(lines, vec!["update: could not check: offline"]);
1215 let off = proto::UpdateStatus::default();
1216 assert!(describe_update("app", "0.19.0", Some("0.19.0"), Some(&off)).is_empty());
1217 }
1218
1219 #[tokio::test(flavor = "multi_thread")]
1220 async fn status_shows_a_newer_release_the_server_found() {
1221 let tmp = tempfile::tempdir().unwrap();
1222 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1223 let api = crate::update::stub::one_response(
1224 "200 OK",
1225 r#"[{"tag_name":"v0.20.0","html_url":"https://example.invalid/v0.20.0"}]"#,
1226 )
1227 .await;
1228 let server = AppServer::new(&CTX, "0.19.0")
1229 .endpoint(endpoint.clone())
1230 .selection_file(tmp.path().join("workspace.toml"))
1231 .releases(crate::ReleaseSource::github("o", "r").api_base(api));
1232 let handle = tokio::spawn(async move { server.run().await });
1233 wait_until_listening(&endpoint).await;
1234
1235 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
1237 let out = loop {
1238 let mut out = String::new();
1239 run_status_into(&endpoint, CTX.app_name, "0.19.0", &mut out)
1240 .await
1241 .unwrap();
1242 if !out.contains("not checked yet") {
1243 break out;
1244 }
1245 assert!(
1246 tokio::time::Instant::now() < deadline,
1247 "never checked: {out}"
1248 );
1249 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1250 };
1251 assert!(
1252 out.contains("update: 0.20.0 is available (https://example.invalid/v0.20.0)"),
1253 "output was: {out}"
1254 );
1255 assert!(!out.contains("restart:"), "output was: {out}");
1256
1257 let (client, _) = sapphire_ipc::connect_or_absent(
1258 &endpoint,
1259 CTX.app_name,
1260 sapphire_ipc::ClientInfo {
1261 kind: "test".into(),
1262 version: "0.19.0".into(),
1263 api: sapphire_backend::protocol::API_VERSION,
1264 app_api: None,
1265 pid: std::process::id(),
1266 },
1267 )
1268 .await
1269 .unwrap()
1270 .expect("the server is listening");
1271 let _: serde_json::Value = client
1272 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1273 .await
1274 .unwrap();
1275 handle.await.unwrap().unwrap();
1276 }
1277
1278 #[tokio::test(flavor = "multi_thread")]
1279 async fn status_shows_the_extension_rows_of_a_running_server() {
1280 let tmp = tempfile::tempdir().unwrap();
1281 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1282 let server = AppServer::new(&CTX, "0.0.0")
1283 .endpoint(endpoint.clone())
1284 .selection_file(tmp.path().join("workspace.toml"))
1286 .status_rows(std::sync::Arc::new(|| {
1287 vec![StatusRow {
1288 name: "sync".into(),
1289 value: "on".into(),
1290 }]
1291 }));
1292 let handle = tokio::spawn(async move { server.run().await });
1293 wait_until_listening(&endpoint).await;
1294
1295 let mut out = String::new();
1298 let code = run_status_into(&endpoint, CTX.app_name, "0.0.0", &mut out)
1299 .await
1300 .unwrap();
1301 assert_eq!(code, 0);
1302 assert!(out.contains("running: true"), "output was: {out}");
1303 assert!(out.contains("sync: on"), "output was: {out}");
1304
1305 let (client, _) = sapphire_ipc::connect_or_absent(
1306 &endpoint,
1307 CTX.app_name,
1308 sapphire_ipc::ClientInfo {
1309 kind: "test".into(),
1310 version: "0.0.0".into(),
1311 api: sapphire_backend::protocol::API_VERSION,
1312 app_api: None,
1313 pid: std::process::id(),
1314 },
1315 )
1316 .await
1317 .unwrap()
1318 .expect("the server is listening");
1319 let _: serde_json::Value = client
1320 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1321 .await
1322 .unwrap();
1323 handle.await.unwrap().unwrap();
1324 }
1325}
1326
1327#[cfg(test)]
1328mod service_spec_tests {
1329 use super::*;
1330 use sapphire_workspace::AppContext;
1331
1332 static CTX: AppContext = AppContext::new("sapphire-servicetest");
1333
1334 #[test]
1335 fn the_generated_spec_runs_the_server_not_the_cli() {
1336 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1340 assert_eq!(spec.args, vec!["serve".to_owned()]);
1341 }
1342
1343 #[test]
1344 fn the_generated_spec_retires_the_first_label() {
1345 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1348 assert_eq!(
1349 spec.legacy_labels,
1350 [format!("net.fireturtle.sapphire.{}", CTX.app_name)]
1351 );
1352 }
1353
1354 #[test]
1355 fn the_generated_spec_names_this_application() {
1356 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1357 assert_eq!(spec.app_name, CTX.app_name);
1358 }
1359
1360 #[test]
1361 fn the_generated_spec_describes_the_server() {
1362 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1363 assert!(
1364 spec.description.contains(CTX.app_name),
1365 "the unit's description should name the application: {:?}",
1366 spec.description
1367 );
1368 assert!(spec.description.contains("0.0.0"));
1369 }
1370}