mod banner;
mod errors;
mod guard;
mod listen;
mod serve;
mod watch;
use crate::errors::cannot_reach;
use anyhow::{Context, Result, bail};
use clap::Parser;
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use tower_livereload::LiveReloadLayer;
#[derive(Parser, Debug)]
#[command(
author,
version,
about = "HTTP server for static files, with live reload, for local development"
)]
struct Args {
#[arg(short, long)]
port: Option<u16>,
#[arg(long, default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
host: IpAddr,
#[arg(short, long, default_value = ".")]
dir: PathBuf,
#[arg(long)]
spa: bool,
#[arg(long)]
no_reload: bool,
#[arg(long)]
cache_assets: bool,
}
#[tokio::main]
async fn main() -> ExitCode {
match run().await {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
errors::report(&error);
ExitCode::FAILURE
}
}
}
async fn run() -> Result<()> {
let args = Args::parse();
let static_dir = resolve_dir(&args.dir)?;
if !static_dir.is_dir() {
bail!(
"cannot serve {}: it is not a directory",
static_dir.display()
);
}
let livereload = LiveReloadLayer::new();
if !args.no_reload {
watch::start(&static_dir, livereload.reloader())?;
}
let no_app_page = args.spa && !static_dir.join(serve::INDEX_FILE).is_file();
let app = serve::app(
&static_dir,
args.spa,
args.cache_assets,
(!args.no_reload).then_some(livereload),
no_app_page,
);
let listener = listen::listen(args.host, args.port).await?;
let bound = listener
.local_addr()
.context("cannot tell which address the server is listening on")?;
banner::print(bound, &args, &static_dir, no_app_page);
axum::serve(listener, app)
.await
.context("the server stopped")?;
Ok(())
}
fn resolve_dir(path: &Path) -> Result<PathBuf> {
let absolute = if path.is_relative() {
std::env::current_dir()
.map_err(|error| cannot_reach("cannot read the current directory".to_string(), &error))?
.join(path)
} else {
path.to_path_buf()
};
absolute
.canonicalize()
.map_err(|error| cannot_reach(format!("cannot serve {}", absolute.display()), &error))
}