use crate::util::{ok, step, CliResult};
use chyabrung_core::prelude::*;
use chyabrung_core::sse::{Event, Sse};
use notify::{RecursiveMode, Watcher};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use tokio::sync::broadcast;
const WATCH: &[&str] = &["src", "app", "templates", "migrations", "chyabrung.toml", "Cargo.toml", ".env"];
pub fn cargo_build(release: bool, features: Option<&str>) -> CliResult<PathBuf> {
let mut cmd = Command::new("cargo");
cmd.arg("build").arg("--message-format=json-render-diagnostics");
if release {
cmd.arg("--release");
}
if let Some(f) = features {
cmd.args(["--features", f]);
}
cmd.stdout(Stdio::piped()).stderr(Stdio::inherit());
let out = cmd.output().map_err(|e| format!("failed to run cargo: {e}"))?;
let mut exe = None;
for line in String::from_utf8_lossy(&out.stdout).lines() {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
if v["reason"] == "compiler-artifact" {
if let Some(e) = v["executable"].as_str() {
exe = Some(PathBuf::from(e));
}
}
}
}
if !out.status.success() {
return Err("build failed".into());
}
exe.ok_or_else(|| "cargo produced no binary (is this an application crate?)".into())
}
fn spawn_app(exe: &Path, reload_url: &str) -> CliResult<Child> {
Command::new(exe)
.env("APP_ENV", std::env::var("APP_ENV").unwrap_or_else(|_| "development".into()))
.env("CHY_LIVE_RELOAD", reload_url)
.env("CHY_DEV_PARENT_PIPE", "1")
.stdin(Stdio::piped())
.spawn()
.map_err(|e| format!("failed to start {}: {e}", exe.display()))
}
fn relevant(path: &Path) -> bool {
let s = path.to_string_lossy();
!(s.contains("target") || s.contains(".git") || s.ends_with('~') || s.contains("public/app.css") || s.contains("public\\app.css"))
}
pub fn run(features: Option<&str>, reload_port: u16) -> CliResult {
crate::util::package_name()?;
crate::upgrade::check_app_version();
crate::upgrade::check_port(crate::upgrade::app_port())?;
if let Err(e) = crate::upgrade::check_port(reload_port) {
let first = e.lines().next().unwrap_or("").to_string();
println!("[33m![0m live reload is off: {first}");
}
let rt = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?;
let (tx, _) = broadcast::channel::<()>(16);
let reload_url = format!("http://127.0.0.1:{reload_port}/_chy/livereload");
{
let tx = tx.clone();
rt.spawn(async move {
let livereload = move || {
let rx = tx.subscribe();
async move {
let stream = futures_util::stream::unfold(rx, |mut rx| async move {
match rx.recv().await {
Ok(()) | Err(broadcast::error::RecvError::Lagged(_)) => Some((Event::default().data("reload"), rx)),
Err(_) => None,
}
});
Sse::new(stream).keep_alive(Duration::from_secs(15))
}
};
let app = App::bare().middleware(cors()).routes(|route| {
route.get("/_chy/livereload", livereload);
});
if let Err(e) = app.try_listen(&format!("127.0.0.1:{reload_port}")).await {
eprintln!("live reload disabled: {}", e.message());
}
});
}
let mut tailwind = if Path::new("style/app.css").exists() {
tailwind_watch()
} else {
None
};
let (fs_tx, fs_rx) = mpsc::channel();
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
if let Ok(ev) = res {
if ev.paths.iter().any(|p| relevant(p)) {
let _ = fs_tx.send(());
}
}
})
.map_err(|e| format!("cannot watch files: {e}"))?;
for w in WATCH {
let p = Path::new(w);
if p.exists() {
let mode = if p.is_dir() { RecursiveMode::Recursive } else { RecursiveMode::NonRecursive };
let _ = watcher.watch(p, mode);
}
}
step("building…");
let mut child = match cargo_build(false, features) {
Ok(exe) => Some(spawn_app(&exe, &reload_url)?),
Err(e) => {
eprintln!("{e} — waiting for changes");
None
}
};
ok(&format!("watching for changes (live reload on :{reload_port}); Ctrl-C to stop"));
loop {
if fs_rx.recv().is_err() {
break;
}
let start = Instant::now();
while start.elapsed() < Duration::from_millis(300) {
if fs_rx.recv_timeout(Duration::from_millis(100)).is_ok() {
continue;
}
}
step("change detected, rebuilding…");
match cargo_build(false, features) {
Ok(exe) => {
if let Some(mut c) = child.take() {
let _ = c.kill();
let _ = c.wait();
}
child = Some(spawn_app(&exe, &reload_url)?);
std::thread::sleep(Duration::from_millis(600));
let _ = tx.send(());
ok("reloaded");
}
Err(e) => eprintln!("{e} — keeping the previous version running"),
}
}
if let Some(mut c) = child {
let _ = c.kill();
}
if let Some(t) = tailwind.as_mut() {
let _ = t.kill();
}
Ok(())
}
fn tailwind_watch() -> Option<Child> {
let bin = if crate::util::which("tailwindcss") {
Some((PathBuf::from("tailwindcss"), vec![]))
} else if Path::new("bin/tailwindcss").exists() || Path::new("bin/tailwindcss.exe").exists() {
Some((PathBuf::from(if cfg!(windows) { "bin/tailwindcss.exe" } else { "bin/tailwindcss" }), vec![]))
} else if crate::util::which("npx") && Path::new("node_modules/tailwindcss").is_dir() {
Some((PathBuf::from(if cfg!(windows) { "npx.cmd" } else { "npx" }), vec!["@tailwindcss/cli".to_string()]))
} else {
eprintln!("tailwind: CLI not found; download it to ./bin/tailwindcss to enable CSS rebuilds");
None
}?;
let (exe, mut args) = bin;
args.extend(["-i", "style/app.css", "-o", "public/app.css", "--watch"].map(String::from));
Command::new(exe).args(args).stdout(Stdio::null()).spawn().ok()
}