use std::path::{Path, PathBuf};
use anyhow::bail;
pub(crate) use nsh_bundler::app_dir::ENTRY;
pub(crate) fn resolve(path: &Path) -> anyhow::Result<PathBuf> {
if !path.is_dir() {
if path.exists() {
return Ok(path.to_owned());
}
bail!("{} does not exist", path.display());
}
let config = path.join("nsh.json");
if nsh_bundler::app_dir::read(&config)
.ok()
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
.is_some_and(|json| json.get("root").is_some())
{
return Ok(config);
}
match nsh_bundler::app_dir::config_entry(path) {
Ok(Some(entry)) if entry.is_file() => return Ok(entry),
Ok(Some(entry)) => bail!(
"{}: \"entry\" names {}, which does not exist",
config.display(),
entry.display()
),
Ok(None) => {}
Err(e) => bail!("{}: {e}", config.display()),
}
let entry = std::fs::read_dir(path)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.is_file())
.find(|p| {
p.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.eq_ignore_ascii_case(ENTRY))
});
match entry {
Some(entry) => Ok(entry),
None => bail!(
"no {ENTRY} in {}: add one, or pass the entry module",
path.display()
),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn conventional_entry() {
let dir = std::env::temp_dir().join(format!("nsh-entry-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
assert!(resolve(&dir).is_err());
std::fs::write(dir.join("Other.tsx"), "").unwrap();
assert!(resolve(&dir).is_err());
std::fs::write(dir.join("app.tsx"), "").unwrap();
assert_eq!(resolve(&dir).unwrap(), dir.join("app.tsx"));
assert_eq!(
resolve(&dir.join("Other.tsx")).unwrap(),
dir.join("Other.tsx")
);
assert!(resolve(&dir.join("missing.tsx")).is_err());
std::fs::write(dir.join("nsh.json"), r#"{ "rust": "." }"#).unwrap();
assert_eq!(resolve(&dir).unwrap(), dir.join("app.tsx"));
std::fs::write(dir.join("nsh.json"), r#"{ "rust": ".", "root": "App" }"#).unwrap();
assert_eq!(resolve(&dir).unwrap(), dir.join("nsh.json"));
std::fs::write(
dir.join("nsh.json"),
"\u{feff}{ \"rust\": \".\", \"root\": \"App\" }",
)
.unwrap();
assert_eq!(resolve(&dir).unwrap(), dir.join("nsh.json"));
assert_eq!(resolve(&dir.join("app.tsx")).unwrap(), dir.join("app.tsx"));
std::fs::create_dir_all(dir.join("app")).unwrap();
std::fs::write(dir.join("nsh.json"), r#"{ "entry": "app/Main.tsx" }"#).unwrap();
assert!(resolve(&dir).is_err());
std::fs::write(dir.join("app/Main.tsx"), "").unwrap();
assert_eq!(resolve(&dir).unwrap(), dir.join("app/Main.tsx"));
std::fs::write(dir.join("nsh.json"), r#"{ "entry": "../Main.tsx" }"#).unwrap();
assert!(resolve(&dir).is_err());
std::fs::remove_dir_all(&dir).unwrap();
}
}