use crate::admin_client;
use crate::dev_placeholder;
use crate::dev_registry;
use crate::process_scan;
use crate::release_slots;
use anyhow::{Context, Result};
use larust_core::__internal::{admin, handoff, listener};
use notify_debouncer_mini::new_debouncer;
use std::io::{self, BufRead, BufReader};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use tokio::sync::Notify;
macro_rules! status {
($($arg:tt)*) => {{
println!($($arg)*);
let _ = ::std::io::Write::flush(&mut ::std::io::stdout());
}};
}
macro_rules! status_err {
($($arg:tt)*) => {{
eprintln!($($arg)*);
let _ = ::std::io::Write::flush(&mut ::std::io::stderr());
}};
}
fn set_debug_env_vars() {
unsafe {
std::env::set_var("APP_DEBUG", "true");
std::env::set_var("LOG_LEVEL", "trace");
std::env::set_var("RUST_BACKTRACE", "full");
}
}
const WATCH_DEBOUNCE: Duration = Duration::from_millis(300);
const READY_TIMEOUT: Duration = Duration::from_secs(15);
const DEFAULT_APP_PORT: u16 = 34187;
const PORT_RELEASE_RETRY_TIMEOUT: Duration = Duration::from_secs(5);
const PORT_RELEASE_RETRY_INTERVAL: Duration = Duration::from_millis(200);
const MAX_PORT_FALLBACK_ATTEMPTS: u16 = 20;
const WATCHED_SUBDIRS: &[&str] = &[
"app",
"config",
"database/migrations",
"database/factories",
"database/seeders",
"resources",
"routes",
"src",
"tests",
];
const WATCHED_ASSET_SUBDIRS: &[&str] = &["public"];
enum ServerState {
NotStarted,
Direct(Box<tokio::process::Child>),
HandedOff,
}
struct DevState {
server: ServerState,
generation: u64,
placeholder_listener: Option<std::net::TcpListener>,
placeholder_stop: Arc<Notify>,
placeholder_message: dev_placeholder::SharedMessage,
}
pub fn run(port_override: Option<u16>, debug: bool) -> Result<()> {
unsafe {
std::env::set_var("LARUST_DEV_RELOAD", "1");
}
if debug {
set_debug_env_vars();
status!(
"xr dev: --debug is on for this session - full error detail pages (APP_DEBUG=true), \
maximum log verbosity (LOG_LEVEL=trace), and full panic backtraces \
(RUST_BACKTRACE=full). Never run a real deploy this way - see \
docs/the-basics/error-handling.md's own APP_DEBUG warning."
);
}
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 dev` from inside a Larust app"
);
let (admin_address, app_name, app_port) = dev_config(port_override);
crate::terminal_title::set(&format!("xr dev - {app_name}"));
let runtime = tokio::runtime::Runtime::new()
.context("failed to start the placeholder server's async runtime")?;
let found_previous_generation = stop_any_previous_generation(&admin_address);
let placeholder_message = dev_placeholder::initial_message();
let placeholder_stop = Arc::new(Notify::new());
let (placeholder_listener, bound_port) = bind_placeholder(
&runtime,
app_port,
found_previous_generation,
app_name.clone(),
Arc::clone(&placeholder_message),
Arc::clone(&placeholder_stop),
)?;
if bound_port != app_port {
if found_previous_generation {
status!(
"xr dev: port {app_port} is still held by this app's own previous generation - \
it was asked to stop but hasn't released the port yet, so using {bound_port} \
for now"
);
} else {
status!(
"xr dev: port {app_port} is already in use by something else (likely a different \
app's own `xr dev`) - using {bound_port} instead"
);
}
}
if let Err(error) = dev_registry::register(&dev_registry::Session {
pid: std::process::id(),
app_name: app_name.clone(),
project_dir: app_root.clone(),
port: bound_port,
admin_address: admin_address.clone(),
started_at_unix: dev_registry::now_unix(),
}) {
status_err!("xr dev: couldn't register this session for `xr list`/`xr kill`: {error}");
}
let state: Arc<Mutex<DevState>> = Arc::new(Mutex::new(DevState {
server: ServerState::NotStarted,
generation: starting_generation(&app_root),
placeholder_listener: Some(placeholder_listener),
placeholder_stop,
placeholder_message,
}));
register_ctrlc_handler(
Arc::clone(&state),
admin_address.clone(),
runtime.handle().clone(),
);
let (tx, rx) = channel();
let mut debouncer =
new_debouncer(WATCH_DEBOUNCE, tx).context("failed to start file watcher")?;
watch_source_dirs(&mut debouncer, &app_root)?;
status!(
"xr dev: watching {} - press Ctrl+C to stop",
app_root.display()
);
status!("xr dev: serving a placeholder on port {bound_port} until the first build succeeds");
rebuild_and_restart(&app_root, &state, &admin_address, &runtime);
let mut last_env_mtime = env_mtime(&app_root);
let mut last_prune = Instant::now();
loop {
let current_env_mtime = env_mtime(&app_root);
if current_env_mtime != last_env_mtime {
last_env_mtime = current_env_mtime;
status!("\nxr dev: change detected, rebuilding...");
rebuild_and_restart(&app_root, &state, &admin_address, &runtime);
}
if last_prune.elapsed() >= Duration::from_secs(30) {
let generation = lock_state(&state).generation;
release_slots::prune(&app_root, "dev", generation);
last_prune = Instant::now();
}
let result = match rx.recv_timeout(Duration::from_secs(1)) {
Ok(result) => result,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
};
match result {
Ok(events) => {
let relevant: Vec<_> = events
.iter()
.filter(|e| is_relevant(&app_root, &e.path))
.collect();
if relevant.is_empty() {
continue;
}
if relevant.iter().all(|e| is_asset_only(&app_root, &e.path)) {
status!("\nxr dev: asset change detected, refreshing connected browsers...");
signal_asset_reload(&state, &admin_address);
} else {
status!("\nxr dev: change detected, rebuilding...");
rebuild_and_restart(&app_root, &state, &admin_address, &runtime);
}
}
Err(error) => status_err!("xr dev: watch error: {error}"),
}
}
Ok(())
}
fn dev_config(port_override: Option<u16>) -> (String, String, u16) {
dotenvy::from_filename(".env").ok();
let app_name = std::env::var("APP_NAME").unwrap_or_else(|_| app_name_default());
let app_port = resolve_app_port(
port_override,
std::env::var("APP_PORT").ok().as_deref(),
std::env::var("APP_URL").ok().as_deref(),
);
let address = admin::channel_address(&app_name);
(address, app_name, app_port)
}
pub(crate) fn resolve_app_port(
port_override: Option<u16>,
env_app_port: Option<&str>,
env_app_url: Option<&str>,
) -> u16 {
port_override
.or_else(|| env_app_port.and_then(|p| p.parse().ok()))
.or_else(|| env_app_url.and_then(port_from_url))
.unwrap_or(DEFAULT_APP_PORT)
}
fn port_from_url(url: &str) -> Option<u16> {
let without_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
let authority_end = without_scheme
.find(['/', '?', '#'])
.unwrap_or(without_scheme.len());
let (_, port) = without_scheme[..authority_end].rsplit_once(':')?;
port.parse().ok()
}
pub(crate) fn app_name_default() -> String {
match std::fs::read_to_string("config/app.rs") {
Ok(source) => app_name_default_from_source(&source),
Err(_) => FALLBACK_APP_NAME.to_string(),
}
}
const FALLBACK_APP_NAME: &str = "Larust";
fn app_name_default_from_source(source: &str) -> String {
const NEEDLE: &str = "env_or(\"APP_NAME\", \"";
let Some(start) = source.find(NEEDLE) else {
return FALLBACK_APP_NAME.to_string();
};
let rest = &source[start + NEEDLE.len()..];
match rest.find('"') {
Some(end) => rest[..end].to_string(),
None => FALLBACK_APP_NAME.to_string(),
}
}
fn starting_generation(app_root: &Path) -> u64 {
release_slots::next_generation(app_root, "dev").saturating_sub(1)
}
fn stop_any_previous_generation(admin_address: &str) -> bool {
let found = admin_client::send_command(admin_address, admin::STOP_COMMAND).is_ok();
if found {
status!("xr dev: found a previous generation of this app still running - stopping it...");
}
found
}
fn bind_with_retry(addr: SocketAddr, retry: bool) -> io::Result<std::net::TcpListener> {
if !retry {
return listener::bind(addr);
}
let deadline = Instant::now() + PORT_RELEASE_RETRY_TIMEOUT;
loop {
match listener::bind(addr) {
Ok(tcp_listener) => return Ok(tcp_listener),
Err(error) if error.kind() == io::ErrorKind::AddrInUse && Instant::now() < deadline => {
std::thread::sleep(PORT_RELEASE_RETRY_INTERVAL);
}
Err(error) => return Err(error),
}
}
}
fn bind_available_port(
starting_port: u16,
found_previous_generation: bool,
) -> io::Result<(std::net::TcpListener, u16)> {
match bind_with_retry(
SocketAddr::from(([127, 0, 0, 1], starting_port)),
found_previous_generation,
) {
Ok(tcp_listener) => return Ok((tcp_listener, starting_port)),
Err(error) if error.kind() != io::ErrorKind::AddrInUse => return Err(error),
Err(_) => {}
}
let mut last_error = None;
for offset in 1..=MAX_PORT_FALLBACK_ATTEMPTS {
let port = starting_port.saturating_add(offset);
match listener::bind(SocketAddr::from(([127, 0, 0, 1], port))) {
Ok(tcp_listener) => return Ok((tcp_listener, port)),
Err(error) if error.kind() == io::ErrorKind::AddrInUse => last_error = Some(error),
Err(error) => return Err(error),
}
}
Err(last_error.unwrap_or_else(|| {
io::Error::new(
io::ErrorKind::AddrInUse,
format!(
"no free port found in {starting_port}..={}",
starting_port.saturating_add(MAX_PORT_FALLBACK_ATTEMPTS)
),
)
}))
}
fn bind_placeholder(
runtime: &tokio::runtime::Runtime,
port: u16,
found_previous_generation: bool,
app_name: String,
message: dev_placeholder::SharedMessage,
stop: Arc<Notify>,
) -> Result<(std::net::TcpListener, u16)> {
let (std_listener, bound_port) = bind_available_port(port, found_previous_generation)
.with_context(|| format!("failed to bind a port for `xr dev` starting at {port}"))?;
let placeholder_listener = std_listener
.try_clone()
.context("failed to clone the placeholder listener")?;
std_listener
.set_nonblocking(true)
.context("failed to set the placeholder listener non-blocking")?;
let _guard = runtime.enter();
let tokio_listener = tokio::net::TcpListener::from_std(std_listener)
.context("failed to adopt the placeholder listener into tokio")?;
runtime.spawn(dev_placeholder::serve(
tokio_listener,
app_name,
message,
stop,
));
Ok((placeholder_listener, bound_port))
}
fn watch_source_dirs(
debouncer: &mut notify_debouncer_mini::Debouncer<notify::RecommendedWatcher>,
app_root: &Path,
) -> Result<()> {
for subdir in WATCHED_SUBDIRS.iter().chain(WATCHED_ASSET_SUBDIRS) {
let path = app_root.join(subdir);
if !path.exists() {
continue;
}
debouncer
.watcher()
.watch(&path, notify::RecursiveMode::Recursive)
.with_context(|| format!("failed to watch {}", path.display()))?;
}
Ok(())
}
fn env_mtime(app_root: &Path) -> Option<std::time::SystemTime> {
std::fs::metadata(app_root.join(".env"))
.ok()?
.modified()
.ok()
}
fn rebuild_and_restart(
app_root: &Path,
state: &Arc<Mutex<DevState>>,
admin_address: &str,
runtime: &tokio::runtime::Runtime,
) {
let mut guard = lock_state(state);
notify_build_status(&guard, admin_address, "building");
match build(app_root, false) {
Ok(Some(binary)) => {
let generation = guard.generation + 1;
match release_slots::publish(app_root, &binary, "dev", generation) {
Ok(slot) => {
guard.generation = generation;
release_slots::prune(app_root, "dev", generation);
advance(&mut guard, &slot, admin_address, generation, runtime);
}
Err(error) => {
let still_serving = still_serving_message(&guard);
status_err!(
"xr dev: build succeeded but failed to publish release slot: {error}\n\
xr dev: {still_serving}"
);
dev_placeholder::set_message(
&guard.placeholder_message,
format!("Build succeeded but failed to publish release slot:\n{error}"),
);
notify_build_status(&guard, admin_address, "failed");
}
}
}
Ok(None) => {
let still_serving = still_serving_message(&guard);
status_err!("xr dev: build produced no binary artifact\nxr dev: {still_serving}");
dev_placeholder::set_message(
&guard.placeholder_message,
"Build produced no binary artifact - check your app's [[bin]] target.",
);
notify_build_status(&guard, admin_address, "failed");
}
Err(error) => {
let still_serving = still_serving_message(&guard);
status_err!("xr dev: build failed\n{error}\nxr dev: {still_serving}");
dev_placeholder::set_message(
&guard.placeholder_message,
format!("Build failed:\n\n{error}"),
);
notify_build_status(&guard, admin_address, "failed");
}
}
}
fn still_serving_message(guard: &DevState) -> &'static str {
match guard.server {
ServerState::NotStarted => "no server has started yet - still serving the placeholder page",
ServerState::Direct(_) | ServerState::HandedOff => {
"still serving the last successful build"
}
}
}
fn advance(
guard: &mut MutexGuard<'_, DevState>,
slot: &Path,
admin_address: &str,
generation: u64,
runtime: &tokio::runtime::Runtime,
) {
match std::mem::replace(&mut guard.server, ServerState::NotStarted) {
ServerState::NotStarted => {
let Some(listener) = guard.placeholder_listener.take() else {
status_err!(
"xr dev: no placeholder listener available to hand off to {generation}"
);
return;
};
match runtime.block_on(handoff::spawn_replacement_and_wait_for_ready(
&listener,
slot,
READY_TIMEOUT,
true,
)) {
Ok(Some(child)) => {
guard.server = ServerState::Direct(Box::new(child));
guard.placeholder_stop.notify_one();
status!("xr dev: built and running (generation {generation})");
}
Ok(None) => {
guard.placeholder_listener = Some(listener);
dev_placeholder::set_message(
&guard.placeholder_message,
format!(
"{} built, but didn't report ready within {}s.",
slot.display(),
READY_TIMEOUT.as_secs()
),
);
status_err!(
"xr dev: {} built but never reported ready - still serving the placeholder page",
slot.display()
);
}
Err(error) => {
guard.placeholder_listener = Some(listener);
dev_placeholder::set_message(
&guard.placeholder_message,
format!("Failed to start {}:\n{error}", slot.display()),
);
status_err!("xr dev: failed to start {}: {error}", slot.display());
}
}
}
ServerState::Direct(child) => {
reap_in_background(*child, runtime.handle());
request_handoff(guard, admin_address, generation);
}
ServerState::HandedOff => {
request_handoff(guard, admin_address, generation);
}
}
}
fn signal_asset_reload(state: &Arc<Mutex<DevState>>, admin_address: &str) {
if matches!(lock_state(state).server, ServerState::NotStarted) {
return;
}
if let Err(error) = admin_client::send_command(admin_address, admin::RELOAD_ASSETS_COMMAND) {
status_err!(
"xr dev: couldn't reach the running server's admin channel to refresh assets: {error}"
);
}
}
fn notify_build_status(guard: &DevState, admin_address: &str, status: &str) {
if matches!(guard.server, ServerState::NotStarted) {
return;
}
let command = format!("{} {status}", admin::BUILD_STATUS_COMMAND);
if let Err(error) = admin_client::send_command(admin_address, &command) {
status_err!(
"xr dev: couldn't reach the running server's admin channel to signal build \
status: {error}"
);
}
}
fn request_handoff(guard: &mut MutexGuard<'_, DevState>, admin_address: &str, generation: u64) {
guard.server = ServerState::HandedOff;
match admin_client::send_command(admin_address, admin::RESTART_COMMAND) {
Ok(response) if response == admin::ACK_HANDOFF_STARTED => {
status!("xr dev: rebuilt and restarted (generation {generation})");
}
Ok(response) if response == admin::ACK_HANDOFF_FAILED => {
status_err!(
"xr dev: restart handoff failed (the new build didn't come up in time) - \
still serving the last successful build"
);
notify_build_status(&*guard, admin_address, "failed");
}
Ok(other) => {
status_err!("xr dev: unexpected response from the admin channel: {other:?}");
}
Err(error) => {
status_err!(
"xr dev: couldn't reach the running server's admin channel: {error}\n\
xr dev: still serving the last successful build"
);
}
}
}
fn reap_in_background(mut child: tokio::process::Child, handle: &tokio::runtime::Handle) {
handle.spawn(async move {
let _ = child.wait().await;
});
}
pub(crate) fn build(app_root: &Path, release: bool) -> Result<Option<PathBuf>> {
let mut attempt = 0;
loop {
match build_once(app_root, release) {
Ok(executable) => return Ok(executable),
Err(error) => {
attempt += 1;
if !cfg!(windows)
|| attempt > BUILD_LOCK_RETRY_ATTEMPTS
|| !process_scan::looks_like_a_transient_windows_file_lock(&error.to_string())
{
return Err(error);
}
std::thread::sleep(BUILD_LOCK_RETRY_INTERVAL);
}
}
}
}
const BUILD_LOCK_RETRY_ATTEMPTS: u32 = 5;
const BUILD_LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(400);
fn build_once(app_root: &Path, release: bool) -> Result<Option<PathBuf>> {
let mut args = vec![
"build",
"--message-format=json-render-diagnostics",
"--color=always",
];
if release {
args.push("--release");
}
let mut child = Command::new("cargo")
.args(&args)
.current_dir(app_root)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context("failed to run `cargo build`")?;
let stderr = child.stderr.take().expect("stderr was piped");
let stderr_relay = std::thread::spawn(move || {
let mut captured = String::new();
for line in BufReader::new(stderr).lines() {
let Ok(line) = line else { break };
status_err!("{line}");
captured.push_str(&line);
captured.push('\n');
}
captured
});
let stdout = child.stdout.take().expect("stdout was piped");
let mut executable = None;
for line in BufReader::new(stdout).lines() {
let line = line.context("reading `cargo build` output")?;
let Ok(message) = serde_json::from_str::<serde_json::Value>(&line) else {
continue;
};
if message.get("reason").and_then(|r| r.as_str()) != Some("compiler-artifact") {
continue;
}
let is_bin = message
.get("target")
.and_then(|t| t.get("kind"))
.and_then(|k| k.as_array())
.is_some_and(|kinds| kinds.iter().any(|k| k.as_str() == Some("bin")));
if !is_bin {
continue;
}
if let Some(exe) = message.get("executable").and_then(|e| e.as_str()) {
executable = Some(PathBuf::from(exe));
}
}
let status = child.wait().context("waiting for `cargo build`")?;
let captured_stderr = stderr_relay.join().unwrap_or_default();
if !status.success() {
anyhow::bail!(format_build_failure(&captured_stderr));
}
Ok(executable)
}
const MAX_CAPTURED_BUILD_STDERR: usize = 4000;
fn format_build_failure(stderr: &str) -> String {
let stderr = strip_ansi_codes(stderr.trim());
if stderr.is_empty() {
return "cargo build exited with a non-zero status".to_string();
}
if stderr.len() <= MAX_CAPTURED_BUILD_STDERR {
return stderr;
}
let tail_start = stderr.len() - MAX_CAPTURED_BUILD_STDERR;
let tail_start = (tail_start..stderr.len())
.find(|&i| stderr.is_char_boundary(i))
.unwrap_or(stderr.len());
format!(
"(truncated - showing the last {MAX_CAPTURED_BUILD_STDERR} characters)\n...\n{}",
&stderr[tail_start..]
)
}
fn strip_ansi_codes(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == '\u{1b}' && chars.peek() == Some(&'[') {
chars.next();
for next in chars.by_ref() {
if next.is_ascii_alphabetic() {
break;
}
}
} else {
out.push(c);
}
}
out
}
fn kill(child: &mut tokio::process::Child, handle: &tokio::runtime::Handle) {
handle.block_on(async {
if let Err(error) = child.kill().await {
status_err!("xr dev: failed to stop the previous server process: {error}");
}
if let Err(error) = child.wait().await {
status_err!("xr dev: failed to reap the previous server process: {error}");
}
});
}
fn register_ctrlc_handler(
state: Arc<Mutex<DevState>>,
admin_address: String,
handle: tokio::runtime::Handle,
) {
let result = ctrlc::set_handler(move || {
let mut guard = lock_state(&state);
match std::mem::replace(&mut guard.server, ServerState::NotStarted) {
ServerState::NotStarted => {}
ServerState::Direct(mut child) => kill(&mut child, &handle),
ServerState::HandedOff => {
let _ = admin_client::send_command(&admin_address, admin::STOP_COMMAND);
}
}
dev_registry::unregister(std::process::id());
std::process::exit(0);
});
if let Err(error) = result {
status_err!("xr dev: failed to register a Ctrl+C handler: {error}");
}
}
fn lock_state(state: &Arc<Mutex<DevState>>) -> MutexGuard<'_, DevState> {
state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn is_relevant(app_root: &Path, path: &Path) -> bool {
let Ok(relative) = path.strip_prefix(app_root) else {
return true;
};
if let Some(std::path::Component::Normal(first)) = relative.components().next() {
if first == ".git" {
return false;
}
}
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.contains(".sqlite") {
return false;
}
}
true
}
fn is_asset_only(app_root: &Path, path: &Path) -> bool {
let Ok(relative) = path.strip_prefix(app_root) else {
return false;
};
matches!(
relative.components().next(),
Some(std::path::Component::Normal(first))
if WATCHED_ASSET_SUBDIRS.iter().any(|dir| Path::new(dir) == Path::new(first))
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn starting_generation_is_zero_with_no_prior_dev_slots_on_disk() {
let app_root = tempfile::tempdir().unwrap();
assert_eq!(starting_generation(app_root.path()), 0);
}
#[test]
fn starting_generation_continues_from_a_previous_sessions_leftover_slots() {
let app_root = tempfile::tempdir().unwrap();
let source = app_root.path().join("built.exe");
std::fs::write(&source, b"x").unwrap();
release_slots::publish(app_root.path(), &source, "dev", 32).unwrap();
release_slots::publish(app_root.path(), &source, "dev", 33).unwrap();
release_slots::publish(app_root.path(), &source, "dev", 34).unwrap();
assert_eq!(starting_generation(app_root.path()), 34);
}
#[test]
fn starting_generation_ignores_a_release_prefixed_slot_from_a_real_deploy() {
let app_root = tempfile::tempdir().unwrap();
let source = app_root.path().join("built.exe");
std::fs::write(&source, b"x").unwrap();
release_slots::publish(app_root.path(), &source, "release", 99).unwrap();
assert_eq!(starting_generation(app_root.path()), 0);
}
#[test]
fn strip_ansi_codes_removes_color_sequences_but_keeps_the_text() {
let colored = "\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9merror\u{1b}[0m: mismatched types";
assert_eq!(strip_ansi_codes(colored), "error: mismatched types");
}
#[test]
fn strip_ansi_codes_leaves_plain_text_untouched() {
assert_eq!(strip_ansi_codes("no escapes here"), "no escapes here");
}
#[test]
fn format_build_failure_falls_back_to_a_generic_message_when_stderr_was_empty() {
let message = format_build_failure("");
assert!(message.contains("non-zero status"));
}
#[test]
fn format_build_failure_includes_the_real_captured_error_text() {
let message =
format_build_failure("error: expected one of `!` or `::`, found `is`\n\nerror: could not compile `blog` (lib) due to 1 previous error\n");
assert!(message.contains("expected one of `!` or `::`"));
}
#[test]
fn format_build_failure_strips_ansi_color_codes() {
let colored = "\u{1b}[1m\u{1b}[38;5;9merror\u{1b}[0m: mismatched types";
let message = format_build_failure(colored);
assert_eq!(message, "error: mismatched types");
}
#[test]
fn format_build_failure_truncates_a_very_long_capture_to_its_tail() {
let huge = "x".repeat(MAX_CAPTURED_BUILD_STDERR * 2);
let message = format_build_failure(&huge);
assert!(message.contains("truncated"));
assert!(message.len() < huge.len());
assert!(message.ends_with(&"x".repeat(50)));
}
#[test]
fn format_build_failure_leaves_a_short_capture_untouched_beyond_trimming() {
let message = format_build_failure(" error: a short one \n");
assert_eq!(message, "error: a short one");
assert!(!message.contains("truncated"));
}
#[test]
fn app_name_default_recovers_a_converted_apps_real_default() {
let source = r#"config["app_name"] = json!(larust_support::config_env::env_or("APP_NAME", "Laravel"));"#;
assert_eq!(app_name_default_from_source(source), "Laravel");
}
#[test]
fn app_name_default_recovers_a_scaffolded_apps_generic_default() {
let source = r#"config["app_name"] = json!(larust_support::config_env::env_or("APP_NAME", "Larust"));"#;
assert_eq!(app_name_default_from_source(source), "Larust");
}
#[test]
fn app_name_default_falls_back_when_the_pattern_is_absent() {
let source = "// no app_name field written this way";
assert_eq!(app_name_default_from_source(source), "Larust");
}
#[test]
fn app_name_default_falls_back_on_an_unterminated_literal() {
let source = r#"env_or("APP_NAME", "Laravel"#; assert_eq!(app_name_default_from_source(source), "Larust");
}
#[test]
fn resolve_app_port_prefers_the_override_over_env_and_default() {
assert_eq!(
resolve_app_port(Some(8001), Some("9000"), Some("http://127.0.0.1:7000")),
8001
);
}
#[test]
fn resolve_app_port_falls_back_to_env_when_no_override_is_given() {
assert_eq!(
resolve_app_port(None, Some("9000"), Some("http://127.0.0.1:7000")),
9000
);
}
#[test]
fn resolve_app_port_falls_back_to_the_url_port_when_app_port_is_unset() {
assert_eq!(
resolve_app_port(None, None, Some("http://127.0.0.1:7000")),
7000
);
}
#[test]
fn resolve_app_port_falls_back_to_the_default_when_nothing_is_set() {
assert_eq!(resolve_app_port(None, None, None), DEFAULT_APP_PORT);
}
#[test]
fn resolve_app_port_falls_back_to_the_default_when_the_url_has_no_port() {
assert_eq!(
resolve_app_port(None, None, Some("http://localhost")),
DEFAULT_APP_PORT
);
}
#[test]
fn resolve_app_port_treats_a_malformed_env_value_as_absent() {
assert_eq!(
resolve_app_port(None, Some("not-a-port"), Some("http://127.0.0.1:7000")),
7000
);
}
#[test]
fn port_from_url_extracts_an_explicit_port() {
assert_eq!(port_from_url("http://127.0.0.1:1234"), Some(1234));
assert_eq!(port_from_url("https://example.com:8443/path"), Some(8443));
}
#[test]
fn port_from_url_returns_none_without_an_explicit_port() {
assert_eq!(port_from_url("http://localhost"), None);
}
#[test]
fn is_relevant_excludes_git_metadata() {
let root = Path::new("/app");
assert!(!is_relevant(root, Path::new("/app/.git/HEAD")));
}
#[test]
fn is_relevant_excludes_the_sqlite_database_and_its_journal_files() {
let root = Path::new("/app");
assert!(!is_relevant(
root,
Path::new("/app/database/database.sqlite")
));
assert!(!is_relevant(
root,
Path::new("/app/database/database.sqlite-wal")
));
assert!(!is_relevant(
root,
Path::new("/app/database/database.sqlite-shm")
));
}
#[test]
fn is_relevant_allows_real_source_changes() {
let root = Path::new("/app");
assert!(is_relevant(root, Path::new("/app/src/main.rs")));
assert!(is_relevant(
root,
Path::new("/app/resources/views/posts/index.blade.xr")
));
assert!(is_relevant(
root,
Path::new("/app/database/migrations/0001_create_posts_table.sql")
));
}
#[test]
fn is_relevant_defaults_to_true_for_paths_outside_app_root() {
assert!(is_relevant(Path::new("/app"), Path::new("/elsewhere/x.rs")));
}
#[test]
fn is_asset_only_true_for_paths_under_public() {
let root = Path::new("/app");
assert!(is_asset_only(
root,
Path::new("/app/public/styles/style.css")
));
assert!(is_asset_only(root, Path::new("/app/public/logo.png")));
}
#[test]
fn is_asset_only_false_for_source_changes() {
let root = Path::new("/app");
assert!(!is_asset_only(root, Path::new("/app/src/main.rs")));
assert!(!is_asset_only(
root,
Path::new("/app/resources/views/welcome.blade.xr")
));
}
#[test]
fn is_asset_only_defaults_to_false_for_paths_outside_app_root() {
assert!(!is_asset_only(
Path::new("/app"),
Path::new("/elsewhere/style.css")
));
}
#[test]
fn env_mtime_is_none_when_env_file_is_absent() {
let app_root = tempfile::tempdir().unwrap();
assert_eq!(env_mtime(app_root.path()), None);
}
#[test]
fn env_mtime_is_some_once_env_exists() {
let app_root = tempfile::tempdir().unwrap();
std::fs::write(app_root.path().join(".env"), b"APP_NAME=demo").unwrap();
assert!(env_mtime(app_root.path()).is_some());
}
#[test]
fn env_mtime_changes_when_env_is_rewritten() {
let app_root = tempfile::tempdir().unwrap();
let env_path = app_root.path().join(".env");
let file = std::fs::File::create(&env_path).unwrap();
let first = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
file.set_modified(first).unwrap();
let baseline = env_mtime(app_root.path());
assert_eq!(baseline, Some(first));
let second = first + Duration::from_secs(1);
file.set_modified(second).unwrap();
assert_ne!(env_mtime(app_root.path()), baseline);
}
fn free_port() -> u16 {
std::net::TcpListener::bind(("127.0.0.1", 0))
.unwrap()
.local_addr()
.unwrap()
.port()
}
#[test]
fn bind_with_retry_fails_immediately_when_retry_is_false() {
let port = free_port();
let addr = SocketAddr::from(([127, 0, 0, 1], port));
let _occupying = std::net::TcpListener::bind(addr).unwrap();
let started = Instant::now();
let result = bind_with_retry(addr, false);
assert_eq!(
result.err().map(|error| error.kind()),
Some(io::ErrorKind::AddrInUse)
);
assert!(started.elapsed() < Duration::from_millis(100));
}
#[test]
fn bind_with_retry_recovers_once_the_port_is_released_when_retry_is_true() {
let port = free_port();
let addr = SocketAddr::from(([127, 0, 0, 1], port));
let occupying = std::net::TcpListener::bind(addr).unwrap();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(150));
drop(occupying);
});
assert!(bind_with_retry(addr, true).is_ok());
}
#[test]
fn bind_available_port_skips_the_retry_window_when_nothing_was_found_to_stop() {
let starting_port = free_port();
let addr = SocketAddr::from(([127, 0, 0, 1], starting_port));
let _occupying = std::net::TcpListener::bind(addr).unwrap();
let started = Instant::now();
let (_listener, bound_port) = bind_available_port(starting_port, false).unwrap();
assert!(bound_port > starting_port);
assert!(started.elapsed() < Duration::from_millis(500));
}
fn env_lock() -> &'static std::sync::Mutex<()> {
static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
LOCK.get_or_init(|| std::sync::Mutex::new(()))
}
#[test]
fn set_debug_env_vars_sets_every_debug_variable() {
let _guard = env_lock()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for var in ["APP_DEBUG", "LOG_LEVEL", "RUST_BACKTRACE"] {
std::env::remove_var(var);
}
set_debug_env_vars();
assert_eq!(std::env::var("APP_DEBUG").as_deref(), Ok("true"));
assert_eq!(std::env::var("LOG_LEVEL").as_deref(), Ok("trace"));
assert_eq!(std::env::var("RUST_BACKTRACE").as_deref(), Ok("full"));
for var in ["APP_DEBUG", "LOG_LEVEL", "RUST_BACKTRACE"] {
std::env::remove_var(var);
}
}
}