use crate::scaffold;
use crate::wizard::OPTIONAL_FEATURES;
use anyhow::{Context, Result};
use dialoguer::theme::ColorfulTheme;
use dialoguer::MultiSelect;
use std::path::Path;
fn supported_feature_names() -> Vec<&'static str> {
let mut names = vec!["tauri"];
names.extend(
OPTIONAL_FEATURES
.iter()
.map(|(name, _)| *name)
.filter(|name| *name != "db"),
);
names
}
pub fn run(feature: Option<&str>) -> Result<()> {
let Some(feature) = feature else {
return run_interactive();
};
add_one(feature)
}
fn add_one(feature: &str) -> Result<()> {
let app_root = std::env::current_dir().context("reading current directory")?;
match feature {
"tauri" => add_tauri(&app_root),
"db" => anyhow::bail!(
"`xr add db` isn't supported yet - unlike every other optional feature, `db` \
splices generated code into main.rs/lib.rs/routes/web.rs at scaffold time, and \
safely retrofitting that onto files you may have since hand-edited needs a real \
merge strategy this command doesn't attempt. Add it by hand: `--features db` on a \
fresh `xr new`, or see docs/digging-deeper/key-value-store-and-sitemaps.md."
),
other if OPTIONAL_FEATURES.iter().any(|(name, _)| *name == other) => {
add_support_feature(&app_root, other)
}
other => anyhow::bail!(
"unknown feature {other:?} - `xr add` supports: {}",
supported_feature_names().join(", ")
),
}
}
fn run_interactive() -> Result<()> {
let theme = ColorfulTheme::default();
let mut labels: Vec<String> = OPTIONAL_FEATURES
.iter()
.filter(|(name, _)| *name != "db")
.map(|(name, desc)| format!("{name} - {desc}"))
.collect();
labels.push(
"tauri - Also scaffold Tauri desktop-app support (src-tauri/, DEPLOY_TYPE=app)".to_string(),
);
let mut names: Vec<&str> = OPTIONAL_FEATURES
.iter()
.filter(|(name, _)| *name != "db")
.map(|(name, _)| *name)
.collect();
names.push("tauri");
let selected_indices = MultiSelect::with_theme(&theme)
.with_prompt("Features to add (space to toggle, enter to confirm)")
.items(&labels)
.interact()
.context("reading feature selection")?;
if selected_indices.is_empty() {
println!("xr add: nothing selected");
return Ok(());
}
for index in selected_indices {
add_one(names[index])?;
}
Ok(())
}
fn add_support_feature(app_root: &Path, feature: &str) -> Result<()> {
let cargo_toml_path = app_root.join("Cargo.toml");
let contents = std::fs::read_to_string(&cargo_toml_path).with_context(|| {
format!(
"reading {} - run `xr add` from inside a Larust app's own directory",
cargo_toml_path.display()
)
})?;
let Some((updated, already_enabled)) = add_feature_to_cargo_toml(&contents, feature) else {
anyhow::bail!(
"couldn't find a `larust-support = {{ ... }}` dependency line in {} - is this \
really a Larust app?",
cargo_toml_path.display()
);
};
if already_enabled {
println!("xr add: `{feature}` is already enabled");
return Ok(());
}
std::fs::write(&cargo_toml_path, updated)
.with_context(|| format!("writing {}", cargo_toml_path.display()))?;
let description = OPTIONAL_FEATURES
.iter()
.find(|(name, _)| *name == feature)
.map(|(_, desc)| *desc)
.unwrap_or_default();
println!("xr add: enabled `{feature}` - {description}");
println!("Run `cargo build` to pull it in.");
Ok(())
}
fn add_feature_to_cargo_toml(contents: &str, feature: &str) -> Option<(String, bool)> {
let line_start = contents.find("larust-support = {")?;
let line_end = contents[line_start..]
.find('\n')
.map(|i| line_start + i)
.unwrap_or(contents.len());
let line = &contents[line_start..line_end];
let Some(features_start) = line.find("features = [") else {
let brace_end = line.rfind('}')?;
let insertion =
format!(", default-features = false, features = [\"sqlite\", \"{feature}\"] ");
let new_line = format!("{}{insertion}{}", &line[..brace_end], &line[brace_end..]);
let updated = format!(
"{}{new_line}{}",
&contents[..line_start],
&contents[line_end..]
);
return Some((updated, false));
};
let array_start = line_start + features_start + "features = [".len();
let array_end = contents[array_start..].find(']').map(|i| array_start + i)?;
let array_contents = &contents[array_start..array_end];
let already_present = array_contents
.split(',')
.map(|name| name.trim().trim_matches('"'))
.any(|name| name == feature);
if already_present {
return Some((contents.to_string(), true));
}
let insertion = format!(", \"{feature}\"");
let updated = format!(
"{}{insertion}{}",
&contents[..array_end],
&contents[array_end..]
);
Some((updated, false))
}
fn add_tauri(app_root: &Path) -> Result<()> {
let tauri_dir = app_root.join("src-tauri");
anyhow::ensure!(
!tauri_dir.exists(),
"Tauri support is already scaffolded (src-tauri/ exists)"
);
let cargo_toml_path = app_root.join("Cargo.toml");
let app_name = read_package_name(&cargo_toml_path)?;
let crate_ident = scaffold::crate_ident(&app_name);
scaffold::write_tauri_scaffold(app_root, &crate_ident, &app_name)?;
update_dot_env(app_root)?;
println!("xr add: scaffolded src-tauri/ for {app_name}");
println!("Next: cd src-tauri && cargo tauri dev");
Ok(())
}
fn read_package_name(cargo_toml_path: &Path) -> Result<String> {
let contents = std::fs::read_to_string(cargo_toml_path).with_context(|| {
format!(
"reading {} - run `xr add` from inside a Larust app's own directory",
cargo_toml_path.display()
)
})?;
const NEEDLE: &str = "name = \"";
let start = contents
.find(NEEDLE)
.ok_or_else(|| anyhow::anyhow!("couldn't find a `name = \"...\"` line in Cargo.toml"))?;
let rest = &contents[start + NEEDLE.len()..];
let end = rest
.find('"')
.ok_or_else(|| anyhow::anyhow!("malformed `name = \"...\"` line in Cargo.toml"))?;
Ok(rest[..end].to_string())
}
fn update_dot_env(app_root: &Path) -> Result<()> {
let env_path = app_root.join(".env");
let contents = std::fs::read_to_string(&env_path)
.with_context(|| format!("reading {}", env_path.display()))?;
if contents.contains("# DEPLOY_TYPE=web") {
let updated = contents.replace("# DEPLOY_TYPE=web", "DEPLOY_TYPE=app");
std::fs::write(&env_path, updated)
.with_context(|| format!("writing {}", env_path.display()))?;
} else {
println!(
"xr add: .env already sets DEPLOY_TYPE explicitly - set it to `app` yourself \
when you're ready to build the desktop target"
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn scaffold_plain_app(root: &Path) {
fs::create_dir_all(root).unwrap();
fs::write(
root.join("Cargo.toml"),
"[package]\nname = \"blog\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
fs::write(root.join(".env"), "APP_ENV=local\n# DEPLOY_TYPE=web\n").unwrap();
}
#[test]
fn add_feature_to_cargo_toml_inserts_into_an_existing_features_array() {
let contents = "[dependencies]\n\
larust-support = { version = \"0.8.0\", default-features = false, features = [\"sqlite\"] }\n\
tokio = { version = \"1\" }\n";
let (updated, already_enabled) = add_feature_to_cargo_toml(contents, "sanctum").unwrap();
assert!(!already_enabled);
assert!(updated.contains("features = [\"sqlite\", \"sanctum\"]"));
assert!(updated.contains("tokio = { version = \"1\" }"));
}
#[test]
fn add_feature_to_cargo_toml_is_a_no_op_when_already_present() {
let contents = "larust-support = { version = \"0.8.0\", default-features = false, \
features = [\"sanctum\", \"sqlite\"] }\n";
let (updated, already_enabled) = add_feature_to_cargo_toml(contents, "sanctum").unwrap();
assert!(already_enabled);
assert_eq!(updated, contents);
}
#[test]
fn add_feature_to_cargo_toml_seeds_sqlite_when_no_features_array_exists_yet() {
let contents = "larust-support = { version = \"0.8.0\" }\n";
let (updated, already_enabled) = add_feature_to_cargo_toml(contents, "sanctum").unwrap();
assert!(!already_enabled);
assert!(updated.contains("default-features = false"));
assert!(updated.contains("features = [\"sqlite\", \"sanctum\"]"));
}
#[test]
fn add_feature_to_cargo_toml_returns_none_without_a_larust_support_line() {
let contents = "[dependencies]\ntokio = { version = \"1\" }\n";
assert!(add_feature_to_cargo_toml(contents, "sanctum").is_none());
}
#[test]
fn add_support_feature_writes_the_file_and_is_idempotent_on_rerun() {
let tmp = tempfile::tempdir().unwrap();
fs::write(
tmp.path().join("Cargo.toml"),
"[dependencies]\n\
larust-support = { version = \"0.8.0\", default-features = false, \
features = [\"sqlite\"] }\n",
)
.unwrap();
add_support_feature(tmp.path(), "pennant").unwrap();
let contents = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
assert!(contents.contains("features = [\"sqlite\", \"pennant\"]"));
add_support_feature(tmp.path(), "pennant").unwrap();
let contents_again = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
assert_eq!(contents, contents_again);
}
#[test]
fn add_tauri_scaffolds_src_tauri_and_flips_deploy_type() {
let tmp = tempfile::tempdir().unwrap();
scaffold_plain_app(tmp.path());
add_tauri(tmp.path()).unwrap();
assert!(tmp.path().join("src-tauri/Cargo.toml").is_file());
let cargo_toml = fs::read_to_string(tmp.path().join("src-tauri/Cargo.toml")).unwrap();
assert!(cargo_toml.contains("blog = { path = \"..\" }"));
let env = fs::read_to_string(tmp.path().join(".env")).unwrap();
assert!(env.contains("DEPLOY_TYPE=app") && !env.contains("# DEPLOY_TYPE=web"));
}
#[test]
fn add_tauri_errors_when_already_scaffolded() {
let tmp = tempfile::tempdir().unwrap();
scaffold_plain_app(tmp.path());
fs::create_dir_all(tmp.path().join("src-tauri")).unwrap();
assert!(add_tauri(tmp.path()).is_err());
}
#[test]
fn add_tauri_leaves_an_explicit_deploy_type_untouched() {
let tmp = tempfile::tempdir().unwrap();
scaffold_plain_app(tmp.path());
fs::write(tmp.path().join(".env"), "APP_ENV=local\nDEPLOY_TYPE=web\n").unwrap();
add_tauri(tmp.path()).unwrap();
let env = fs::read_to_string(tmp.path().join(".env")).unwrap();
assert_eq!(env, "APP_ENV=local\nDEPLOY_TYPE=web\n");
}
}