use crate::util::{ok, run, step, CliResult};
use std::path::Path;
use std::process::Command;
pub const CLI_VERSION: &str = env!("CARGO_PKG_VERSION");
fn series(v: &str) -> Option<(u64, u64)> {
let mut it = v.trim().trim_start_matches(['^', '~', '=']).split('.');
Some((it.next()?.parse().ok()?, it.next().and_then(|m| m.parse().ok()).unwrap_or(0)))
}
fn triple(v: &str) -> Option<(u64, u64, u64)> {
let mut it = v.trim().split(['.', '-', '+']);
Some((it.next()?.parse().ok()?, it.next()?.parse().ok()?, it.next().and_then(|p| p.parse().ok()).unwrap_or(0)))
}
fn requirement(v: &str) -> String {
match series(v) {
Some((0, minor)) => format!("0.{minor}"),
Some((major, _)) => major.to_string(),
None => v.to_string(),
}
}
pub fn locked_version(lock: &str) -> Option<String> {
let mut lines = lock.lines();
while let Some(l) = lines.next() {
if l.trim() == "name = \"chyabrung\"" {
let v = lines.next()?.trim().strip_prefix("version = \"")?.strip_suffix('"')?;
return Some(v.to_string());
}
}
None
}
pub fn bump_manifest(manifest: &str, req: &str) -> (String, bool) {
let mut changed = false;
let out: Vec<String> = manifest
.lines()
.map(|line| {
let t = line.trim_start();
let is_dep = ["chyabrung =", "chyabrung=", "chyabrung-testing =", "chyabrung-testing="].iter().any(|p| t.starts_with(p));
if !is_dep || t.contains("path =") || t.contains("git =") {
return line.to_string();
}
let new = replace_version(line, req);
changed |= new != line;
new
})
.collect();
let mut s = out.join("\n");
if manifest.ends_with('\n') {
s.push('\n');
}
(s, changed)
}
fn replace_version(line: &str, req: &str) -> String {
let (key, rest) = match line.split_once('=') {
Some(kv) => kv,
None => return line.to_string(),
};
let rest_t = rest.trim_start();
if rest_t.starts_with('"') {
return format!("{key}= \"{req}\"");
}
if let Some(i) = line.find("version") {
let after = &line[i..];
if let (Some(q1), true) = (after.find('"'), after.contains('=')) {
if let Some(q2) = after[q1 + 1..].find('"') {
return format!("{}\"{req}\"{}", &line[..i + q1], &after[q1 + 1 + q2 + 1..]);
}
}
}
line.to_string()
}
pub fn upgrade() -> CliResult {
let manifest = std::fs::read_to_string("Cargo.toml").map_err(|_| "no Cargo.toml here: run `chy upgrade` in your app's folder".to_string())?;
let req = requirement(CLI_VERSION);
let before = std::fs::read_to_string("Cargo.lock").ok().and_then(|l| locked_version(&l));
if before.as_deref().and_then(triple).is_some_and(|v| v < (0, 2, 2)) && triple(CLI_VERSION).is_some_and(|v| v >= (0, 2, 2)) {
migrate_models_to_0_2_2()?;
}
let (new, changed) = bump_manifest(&manifest, &req);
if changed {
std::fs::write("Cargo.toml", new).map_err(|e| format!("cannot write Cargo.toml: {e}"))?;
ok(&format!("Cargo.toml now asks for chyabrung \"{req}\""));
} else if !manifest.contains("chyabrung") {
return Err("this Cargo.toml does not depend on chyabrung".into());
}
step("updating Cargo.lock…");
let mut cmd = Command::new("cargo");
cmd.args(["update", "-p", "chyabrung"]);
if manifest.contains("chyabrung-testing") {
cmd.args(["-p", "chyabrung-testing"]);
}
run(&mut cmd)?;
let after = std::fs::read_to_string("Cargo.lock").ok().and_then(|l| locked_version(&l));
match (before, after) {
(Some(b), Some(a)) if a != b => ok(&format!("chyabrung {b} → {a}")),
(_, Some(a)) => ok(&format!("chyabrung {a} (already up to date)")),
_ => {}
}
println!(" release notes: https://github.com/Chyabrung/chyabrung/releases");
println!(" new template features (e.g. `.openapi(...)`) are opt-in; run `cargo build` to check the app");
Ok(())
}
pub fn rewrite_models_0_2_2(src: &str) -> String {
use regex::Regex;
use std::sync::OnceLock;
static RULES: OnceLock<Vec<(Regex, &'static str)>> = OnceLock::new();
let rules = RULES.get_or_init(|| {
let db = r"(&?(?:[A-Za-z_][\w.]*\.)?(?:[a-z_]*db|tx|[a-z_]*_db|db_[a-z_]+))";
let r = |p: String| Regex::new(&p).expect("valid rewrite rule");
vec![
(r(format!(r"\b([A-Z]\w*)::(find|search|find_many|create|force_create)\(\s*{db},\s*")), "${1}::on(${3}).${2}("),
(r(format!(r"\b([A-Z]\w*)::query\({db}\)")), "${1}::on(${2})"),
(r(format!(r"\b([A-Z]\w*)::all\({db}\)")), "${1}::on(${2}).get()"),
(r(format!(r"\.(save|delete|force_delete|restore|refresh)\({db}\)")), ".${1}_on(${2})"),
(r(format!(r"\.(has_many|has_one|belongs_to|belongs_to_many|morph_many|morph_to)(::<[^>]+>)?\({db},\s*")), ".${1}${2}("),
(r(format!(r"::load_many(::<[^>]+>)?\({db},\s*")), "::load_many${1}("),
]
});
let mut out = src.to_string();
for (re, rep) in rules {
out = re.replace_all(&out, *rep).into_owned();
}
out
}
fn migrate_models_to_0_2_2() -> CliResult {
let mut changed = Vec::new();
for dir in ["src", "tests", "app", "benches", "examples"] {
visit_rs(Path::new(dir), &mut |p| {
if let Ok(s) = std::fs::read_to_string(p) {
let new = rewrite_models_0_2_2(&s);
if new != s && std::fs::write(p, new).is_ok() {
changed.push(p.display().to_string().replace('\\', "/"));
}
}
});
}
if changed.is_empty() {
return Ok(());
}
ok(&format!("rewrote model calls for 0.2.2 in {} file(s):", changed.len()));
for c in &changed {
println!(" {c}");
}
println!(" `Post::find(&db, id)` is now `Post::on(&db).find(id)`, or simply `Post::find(id)` in a request");
Ok(())
}
fn visit_rs(dir: &Path, f: &mut dyn FnMut(&Path)) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
if p.file_name().is_some_and(|n| n != "target") {
visit_rs(&p, f);
}
} else if p.extension().is_some_and(|x| x == "rs") {
f(&p);
}
}
}
pub fn check_app_version() {
let Some(app) = std::fs::read_to_string("Cargo.lock").ok().and_then(|l| locked_version(&l)) else { return };
let (Some(a), Some(c)) = (triple(&app), triple(CLI_VERSION)) else { return };
if a < c {
println!("\x1b[33m!\x1b[0m this app uses chyabrung {app}, chy is {CLI_VERSION}: run `chy upgrade` to update the app");
} else if (a.0, a.1) > (c.0, c.1) {
println!("\x1b[33m!\x1b[0m this app uses chyabrung {app}, but chy is {CLI_VERSION}: run `chy self-update`");
}
}
pub fn self_update() -> CliResult {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let old = exe.with_extension("old.exe");
let moved = cfg!(windows) && {
let _ = std::fs::remove_file(&old);
std::fs::rename(&exe, &old).is_ok()
};
step(&format!("installing the latest chyabrung-cli (now {CLI_VERSION})…"));
let result = run(Command::new("cargo").args(["install", "chyabrung-cli", "--locked", "--force"]));
if result.is_err() && moved && !exe.exists() {
let _ = std::fs::rename(&old, &exe); }
result?;
ok("chy is up to date; in each app run `chy upgrade` to use the new version");
Ok(())
}
pub fn cleanup_old_exe() {
if let Ok(exe) = std::env::current_exe() {
let old = exe.with_extension("old.exe");
if old.exists() {
let _ = std::fs::remove_file(old);
}
}
}
pub fn port_owner(port: u16) -> Option<String> {
if cfg!(windows) {
let out = Command::new("netstat").args(["-ano", "-p", "TCP"]).output().ok()?;
let text = String::from_utf8_lossy(&out.stdout);
let pid = text.lines().find_map(|l| {
let cols: Vec<&str> = l.split_whitespace().collect();
(cols.len() >= 5 && cols[1].ends_with(&format!(":{port}")) && cols[3].eq_ignore_ascii_case("LISTENING")).then(|| cols[4].to_string())
})?;
let out = Command::new("tasklist").args(["/FI", &format!("PID eq {pid}"), "/FO", "CSV", "/NH"]).output().ok()?;
let name = String::from_utf8_lossy(&out.stdout).split(',').next().map(|s| s.trim().trim_matches('"').to_string()).filter(|s| !s.is_empty());
Some(match name {
Some(n) => format!("{n} (PID {pid})"),
None => format!("PID {pid}"),
})
} else {
let out = Command::new("lsof").args(["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN", "-Fpc"]).output().ok()?;
let text = String::from_utf8_lossy(&out.stdout);
let pid = text.lines().find_map(|l| l.strip_prefix('p'))?.to_string();
let name = text.lines().find_map(|l| l.strip_prefix('c')).unwrap_or("process");
Some(format!("{name} (PID {pid})"))
}
}
pub fn stop_hint(owner: &str) -> String {
let pid = owner.rsplit("PID ").next().unwrap_or("").trim_end_matches(')');
if cfg!(windows) {
format!("Stop-Process -Id {pid}")
} else {
format!("kill {pid}")
}
}
pub fn app_port() -> u16 {
let _ = dotenvy::dotenv();
if let Some(p) = std::env::var("APP_PORT").ok().and_then(|p| p.parse().ok()) {
return p;
}
crate::util::config()
.get("app")
.and_then(|a| a.get("port"))
.and_then(|p| match p {
toml::Value::Integer(i) => u16::try_from(*i).ok(),
toml::Value::String(s) => chyabrung_core::config::interpolate(s).parse().ok(),
_ => None,
})
.unwrap_or(2007)
}
pub fn check_port(port: u16) -> CliResult {
let owner = port_owner(port);
let bind_ok = std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() && std::net::TcpListener::bind(("0.0.0.0", port)).is_ok();
if bind_ok && owner.is_none() {
return Ok(());
}
let mut msg = format!("port {port} is already in use");
match owner {
Some(owner) => {
msg.push_str(&format!(" by {owner}.\n Probably another `chy dev` is still running in another terminal: press Ctrl-C there, or run `{}`.", stop_hint(&owner)));
}
None => msg.push_str(".\n Probably another `chy dev` is still running in another terminal: press Ctrl-C there."),
}
msg.push_str("\n To run this app next to it, use another port: set APP_PORT=2008 in .env");
Err(msg)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn versions() {
assert_eq!(requirement("0.2.0"), "0.2");
assert_eq!(requirement("1.4.2"), "1");
assert_eq!(series("^0.1"), Some((0, 1)));
let lock = "[[package]]\nname = \"chyabrung\"\nversion = \"0.1.0\"\nsource = \"x\"\n";
assert_eq!(locked_version(lock).as_deref(), Some("0.1.0"));
}
#[test]
fn rewrites_models_for_0_2_2() {
let old = r#"let p = Post::find(&db, id).await?;
let u = User::create(&state.db, &json!({"a": 1})).await?;
let m = Post::create(
&db,
&json!({"t": 1}),
).await?;
let q = Post::query(&db).where_("x", 1);
let all = Tag::all(&tx).await?;
post.save(&db).await?; post.delete(&db).await?; let f = post.refresh(&self.db).await?;
let c = user.has_many::<Post>(&db, "user_id");
storage.delete(&key).await?; File::create(&path)?;
"#;
let new = rewrite_models_0_2_2(old);
assert!(new.contains("Post::on(&db).find(id)"));
assert!(new.contains("User::on(&state.db).create(&json!"));
assert!(new.contains("Post::on(&db).where_"));
assert!(new.contains("Post::on(&db).create(&json!({\"t\": 1})"), "multi-line calls");
assert!(new.contains("Tag::on(&tx).get()"));
assert!(new.contains("post.save_on(&db)") && new.contains("post.delete_on(&db)") && new.contains("post.refresh_on(&self.db)"));
assert!(new.contains("user.has_many::<Post>(\"user_id\")"));
assert!(new.contains("storage.delete(&key)") && new.contains("File::create(&path)"), "non-db calls untouched");
assert_eq!(rewrite_models_0_2_2(&new), new, "idempotent");
}
#[test]
fn bumps_manifest() {
let m = "[dependencies]\nchyabrung = { version = \"0.1\", features = [\"sqlite\"] }\nchyabrung-core = \"0.1\"\nserde = \"1\"\n\n[dev-dependencies]\nchyabrung-testing = \"0.1\"\nlocal = { path = \"x\" }\n";
let (out, changed) = bump_manifest(m, "0.2");
assert!(changed);
assert!(out.contains("chyabrung = { version = \"0.2\", features = [\"sqlite\"] }"));
assert!(out.contains("chyabrung-testing = \"0.2\""));
assert!(out.contains("chyabrung-core = \"0.1\""), "only the facade and testing crates are touched");
let (_, again) = bump_manifest(&out, "0.2");
assert!(!again);
let (_, path) = bump_manifest("chyabrung = { path = \"../chyabrung\" }\n", "0.2");
assert!(!path);
}
}