use crate::admin_client;
use crate::dev::{app_name_default, build};
use crate::release_slots;
use crate::restart;
use crate::service;
use anyhow::{Context, Result};
use larust_core::__internal::admin;
use std::path::Path;
const RELEASE_PREFIX: &str = "release";
pub fn run(run_if_idle: bool, install_service: bool, clean: bool, clean_all: bool) -> Result<()> {
dotenvy::from_filename(".env").ok();
let deploy_type = std::env::var("DEPLOY_TYPE").unwrap_or_else(|_| "web".to_string());
match deploy_type.as_str() {
"web" => {
deploy_web(run_if_idle, install_service)?;
if clean || clean_all {
let app_root = std::env::current_dir().context("reading current directory")?;
clean_build_artifacts(&app_root, clean_all)?;
}
Ok(())
}
"app" => {
anyhow::ensure!(
!clean && !clean_all,
"xr deploy --clean / --clean-all is only supported for DEPLOY_TYPE=web; desktop bundles live in Cargo's release directory and must be preserved"
);
if run_if_idle {
println!(
"xr deploy: --run has no effect for DEPLOY_TYPE=app - a desktop bundle \
isn't something `xr deploy` starts for you"
);
}
if install_service {
println!(
"xr deploy: --service has no effect for DEPLOY_TYPE=app - a desktop bundle \
has no systemd analogue"
);
}
deploy_app()
}
other => {
anyhow::bail!("unrecognized DEPLOY_TYPE {other:?} - expected \"web\" or \"app\"")
}
}
}
fn clean_build_artifacts(app_root: &Path, all: bool) -> Result<()> {
let command_label = if all {
"cargo clean"
} else {
"cargo clean --release"
};
println!("xr deploy: cleaning build artifacts ({command_label})...");
let mut command = std::process::Command::new("cargo");
command.arg("clean").current_dir(app_root);
if !all {
command.arg("--release");
}
let status = command
.status()
.with_context(|| format!("release was deployed, but failed to run `{command_label}`"))?;
anyhow::ensure!(
status.success(),
"release was deployed, but `{command_label}` exited with a non-zero status"
);
if all {
println!("xr deploy: all build artifacts cleaned; development and deployment builds will rebuild dependencies");
} else {
println!(
"xr deploy: release build artifacts cleaned; the next deploy will rebuild dependencies"
);
}
Ok(())
}
fn deploy_web(run_if_idle: bool, install_service: bool) -> Result<()> {
let app_root = std::env::current_dir().context("reading current directory")?;
build_frontend_assets(&app_root)?;
println!("xr deploy: building release...");
let binary = build(&app_root, true)?
.context("release build produced no binary artifact - check your app's [[bin]] target")?;
let generation = release_slots::next_generation(&app_root, RELEASE_PREFIX);
let slot = release_slots::publish(&app_root, &binary, RELEASE_PREFIX, generation)
.context("failed to publish the release")?;
release_slots::prune(&app_root, RELEASE_PREFIX, generation);
println!(
"xr deploy: published release {generation} at {}",
slot.display()
);
let bytes = std::fs::metadata(&slot)
.context("reading published release size")?
.len();
println!(
"xr deploy: executable size {:.2} MiB; target/ is a build cache, not part of the runtime release",
bytes as f64 / (1024.0 * 1024.0)
);
let app_name = std::env::var("APP_NAME").unwrap_or_else(|_| app_name_default());
let address = admin::channel_address(&app_name);
match admin_client::send_command(&address, admin::RESTART_COMMAND) {
Ok(response) => restart::report(&response),
Err(_) if install_service => service::install(None),
Err(_) if run_if_idle => start_detached(&slot, &app_root),
Err(_) => {
println!(
"xr deploy: no running app found to hand off to - the release is published \
and ready. Start the app once manually to pick it up, re-run with `--run` to \
have `xr deploy` start it for you, or `--service` to also register it with \
systemd (crash- and reboot-safe from the start); every later `xr deploy` will \
hand off to it with zero downtime regardless."
);
Ok(())
}
}
}
pub(crate) fn start_detached(binary: &Path, app_root: &Path) -> Result<()> {
#[cfg(windows)]
unmark_stdio_inheritable();
let child = std::process::Command::new(binary)
.current_dir(app_root)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.env("LARUST_STDIO_DETACHED", "1")
.spawn()
.with_context(|| format!("failed to start {}", binary.display()))?;
println!(
"xr deploy: started the app in the background (pid {}) - give it a moment to finish \
binding its port; every later `xr deploy` will hand off to it with zero downtime.",
child.id()
);
Ok(())
}
#[cfg(windows)]
fn unmark_stdio_inheritable() {
use windows_sys::Win32::Foundation::SetHandleInformation;
use windows_sys::Win32::Foundation::{HANDLE, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Console::{GetStdHandle, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE};
for which in [STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
unsafe {
let handle: HANDLE = GetStdHandle(which);
if handle != INVALID_HANDLE_VALUE && !handle.is_null() {
SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
}
}
}
}
fn deploy_app() -> Result<()> {
let app_root = std::env::current_dir().context("reading current directory")?;
let tauri_dir = app_root.join("src-tauri");
anyhow::ensure!(
tauri_dir.is_dir(),
"DEPLOY_TYPE=app but this app has no src-tauri/ directory yet - run `xr add tauri` first"
);
let icons_present = tauri_dir
.join("icons")
.read_dir()
.map(|mut entries| entries.next().is_some())
.unwrap_or(false);
anyhow::ensure!(
icons_present,
"no icons found in src-tauri/icons/ - run `cargo tauri icon <path-to-a-logo.png>` from \
src-tauri/ once before your first build (generates every size the bundler needs)"
);
build_frontend_assets(&app_root)?;
println!("xr deploy: building desktop bundle (cargo tauri build)...");
let status = std::process::Command::new("cargo")
.args(["tauri", "build"])
.current_dir(&tauri_dir)
.status()
.context("failed to run `cargo tauri build`")?;
if !status.success() {
eprintln!(
"\nIf tauri-cli isn't installed yet: cargo install tauri-cli --version \"^2.0.0\""
);
anyhow::bail!("cargo tauri build exited with a non-zero status");
}
println!("xr deploy: desktop bundle(s) published under src-tauri/target/release/bundle/");
Ok(())
}
pub(crate) fn build_frontend_assets(app_root: &Path) -> Result<()> {
if !app_root.join("node_modules").is_dir() {
return Ok(());
}
println!("xr: building frontend assets (npm run build)...");
let npm = if cfg!(windows) { "npm.cmd" } else { "npm" };
let status = std::process::Command::new(npm)
.args(["run", "build"])
.current_dir(app_root)
.status()
.with_context(|| format!("failed to run `{npm} run build`"))?;
anyhow::ensure!(
status.success(),
"`npm run build` exited with a non-zero status"
);
Ok(())
}