use crate::deploy::start_detached;
use crate::dev::resolve_app_port;
use crate::service::published_binary;
use anyhow::{Context, Result};
use std::net::TcpStream;
use std::time::Duration;
pub fn run() -> Result<()> {
dotenvy::from_filename(".env").ok();
let app_root = std::env::current_dir().context("reading current directory")?;
anyhow::ensure!(
app_root.join("Cargo.toml").exists(),
"no Cargo.toml in the current directory - run `xr run` from inside a Larust app"
);
let binary = published_binary(&app_root)?;
let port = resolve_app_port(
None,
std::env::var("APP_PORT").ok().as_deref(),
std::env::var("APP_URL").ok().as_deref(),
);
let addr = format!("127.0.0.1:{port}");
if is_listening(&addr) {
println!(
"xr run: {addr} is already being served - nothing to do (`xr restart` to hand off \
to it with a fresh build, `xr deploy` to publish a new release first)"
);
return Ok(());
}
start_detached(&binary, &app_root)
}
fn is_listening(addr: &str) -> bool {
addr.parse()
.ok()
.map(|socket_addr| {
TcpStream::connect_timeout(&socket_addr, Duration::from_millis(200)).is_ok()
})
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_listening_is_true_when_something_is_bound_to_the_port() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
assert!(is_listening(&format!("127.0.0.1:{port}")));
}
#[test]
fn is_listening_is_false_when_nothing_is_bound_to_the_port() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
assert!(!is_listening(&format!("127.0.0.1:{port}")));
}
#[test]
fn is_listening_is_false_for_an_unparseable_address() {
assert!(!is_listening("not-an-address"));
}
}