use std::{
env, fs,
path::{Path, PathBuf},
};
use serde::Deserialize;
use url::Url;
use crate::{error::CliError, vite_path};
#[derive(Clone, Debug)]
pub struct Project {
pub root: PathBuf,
pub config_path: PathBuf,
pub app_name: String,
pub identifier: String,
pub frontend_dir: PathBuf,
pub native_manifest: PathBuf,
pub dev_command: Vec<String>,
pub build_command: Vec<String>,
pub dev_url: Url,
pub bundle: BundleSettings,
}
#[derive(Clone, Debug)]
pub struct BundleSettings {
pub active: bool,
pub version: Option<String>,
pub publisher: Option<String>,
pub description: Option<String>,
pub copyright: Option<String>,
pub icons: Vec<PathBuf>,
pub resources: Vec<PathBuf>,
pub macos_minimum_system_version: String,
}
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct ProjectFile {
app: AppSection,
#[serde(rename = "window")]
_window: Option<toml::Table>,
#[serde(rename = "frontend")]
_frontend: Option<toml::Table>,
#[serde(rename = "development")]
_development: Option<toml::Table>,
#[serde(rename = "permissions")]
_permissions: Option<toml::Table>,
#[serde(rename = "shell")]
_shell: Option<toml::Table>,
build: BuildSection,
bundle: BundleSection,
}
#[derive(Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct AppSection {
name: String,
identifier: String,
}
impl Default for AppSection {
fn default() -> Self {
Self {
name: "Kayro".to_owned(),
identifier: "dev.kayro.app".to_owned(),
}
}
}
#[derive(Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct BundleSection {
active: bool,
version: Option<String>,
publisher: Option<String>,
description: Option<String>,
copyright: Option<String>,
icons: Vec<PathBuf>,
resources: Vec<PathBuf>,
macos_minimum_system_version: String,
}
impl Default for BundleSection {
fn default() -> Self {
Self {
active: true,
version: None,
publisher: None,
description: None,
copyright: None,
icons: Vec::new(),
resources: Vec::new(),
macos_minimum_system_version: "13.0".to_owned(),
}
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct BuildSection {
frontend_dir: Option<PathBuf>,
native_manifest: Option<PathBuf>,
dev_command: Option<Vec<String>>,
build_command: Option<Vec<String>>,
dev_url: Option<String>,
}
impl Project {
pub fn discover(
explicit_config: Option<&Path>,
project_dir: Option<&Path>,
) -> Result<Self, CliError> {
let current_dir = env::current_dir().map_err(|source| CliError::Io {
action: "reading the current directory",
source,
})?;
let config_path = if let Some(path) = explicit_config {
canonicalize_from(¤t_dir, path)?
} else if let Some(path) = project_dir {
let start = canonicalize_from(¤t_dir, path)?;
find_config(&start)?
} else if let Some(path) = env::var_os("KAYRO_CONFIG") {
canonicalize_from(¤t_dir, Path::new(&path))?
} else {
find_config(¤t_dir)?
};
Self::load(config_path)
}
pub fn load(config_path: PathBuf) -> Result<Self, CliError> {
let source = fs::read_to_string(&config_path).map_err(|source| CliError::ReadConfig {
path: config_path.clone(),
source,
})?;
let file: ProjectFile =
toml::from_str(&source).map_err(|source| CliError::ParseConfig {
path: config_path.clone(),
source,
})?;
let root = config_path
.parent()
.expect("a configuration file has a parent directory")
.to_path_buf();
let ProjectFile {
app, build, bundle, ..
} = file;
validate_text("app.name", &app.name)?;
validate_text("app.identifier", &app.identifier)?;
let BuildSection {
frontend_dir,
native_manifest,
dev_command,
build_command,
dev_url,
} = build;
let frontend_dir = root.join(frontend_dir.unwrap_or_else(|| PathBuf::from(".")));
if !frontend_dir.is_dir() {
return Err(CliError::MissingProjectPath {
kind: "frontend directory",
path: frontend_dir,
});
}
let frontend_dir =
frontend_dir
.canonicalize()
.map_err(|source| CliError::InvalidProjectPath {
path: frontend_dir,
source,
})?;
vite_path::validate(&frontend_dir)?;
let dev_command = dev_command
.unwrap_or_else(|| detected_frontend_command(&frontend_dir, "dev:web", "dev"));
let build_command = build_command
.unwrap_or_else(|| detected_frontend_command(&frontend_dir, "build:web", "build"));
validate_command("build.dev_command", &dev_command)?;
validate_command("build.build_command", &build_command)?;
let native_manifest =
root.join(native_manifest.unwrap_or_else(|| PathBuf::from("src-kayro/Cargo.toml")));
if !native_manifest.is_file() {
return Err(CliError::MissingProjectPath {
kind: "native Cargo manifest",
path: native_manifest,
});
}
let native_manifest =
native_manifest
.canonicalize()
.map_err(|source| CliError::InvalidProjectPath {
path: native_manifest,
source,
})?;
let dev_url = parse_dev_url(dev_url.as_deref().unwrap_or("http://127.0.0.1:5173"))?;
let bundle = resolve_bundle(&root, bundle)?;
Ok(Self {
root,
config_path,
app_name: app.name,
identifier: app.identifier,
frontend_dir,
native_manifest,
dev_command,
build_command,
dev_url,
bundle,
})
}
pub fn effective_dev_url(
&self,
explicit: Option<&str>,
host: Option<&str>,
port: Option<u16>,
) -> Result<Url, CliError> {
if let Some(explicit) = explicit {
return parse_dev_url(explicit);
}
let mut url = self.dev_url.clone();
if let Some(host) = host {
url.set_host(Some(host))
.map_err(|error| CliError::InvalidDevUrl {
url: url.to_string(),
message: format!("invalid host `{host}`: {error}"),
})?;
}
if let Some(port) = port {
url.set_port(Some(port))
.map_err(|()| CliError::InvalidDevUrl {
url: url.to_string(),
message: format!("scheme `{}` cannot use an explicit port", url.scheme()),
})?;
}
Ok(url)
}
}
fn detected_frontend_command(
frontend_dir: &Path,
preferred: &'static str,
fallback: &'static str,
) -> Vec<String> {
let script = fs::read_to_string(frontend_dir.join("package.json"))
.ok()
.and_then(|source| serde_json::from_str::<serde_json::Value>(&source).ok())
.and_then(|package| package.get("scripts").cloned())
.and_then(|scripts| {
[preferred, fallback].into_iter().find(|name| {
scripts
.get(*name)
.and_then(serde_json::Value::as_str)
.is_some_and(|command| !calls_kayro(command))
})
})
.unwrap_or(preferred);
vec!["bun".to_owned(), "run".to_owned(), script.to_owned()]
}
fn calls_kayro(command: &str) -> bool {
command.split_whitespace().any(|part| {
let part = part.trim_matches(['\'', '"']);
part == "kayro" || part.ends_with("/kayro") || part.ends_with("\\kayro.exe")
})
}
fn parse_dev_url(value: &str) -> Result<Url, CliError> {
let url = Url::parse(value).map_err(|error| CliError::InvalidDevUrl {
url: value.to_owned(),
message: error.to_string(),
})?;
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
return Err(CliError::InvalidDevUrl {
url: value.to_owned(),
message: "expected an absolute HTTP(S) URL with a host".to_owned(),
});
}
Ok(url)
}
fn validate_command(field: &'static str, command: &[String]) -> Result<(), CliError> {
if command.is_empty() || command.iter().any(|part| part.trim().is_empty()) {
return Err(CliError::InvalidConfig {
field,
message: "expected a non-empty argument-vector command".to_owned(),
});
}
Ok(())
}
fn validate_text(field: &'static str, value: &str) -> Result<(), CliError> {
if value.trim().is_empty() {
return Err(CliError::InvalidConfig {
field,
message: "cannot be empty".to_owned(),
});
}
Ok(())
}
fn resolve_bundle(root: &Path, bundle: BundleSection) -> Result<BundleSettings, CliError> {
for (field, value) in [
("bundle.version", bundle.version.as_deref()),
("bundle.publisher", bundle.publisher.as_deref()),
("bundle.description", bundle.description.as_deref()),
("bundle.copyright", bundle.copyright.as_deref()),
(
"bundle.macos_minimum_system_version",
Some(bundle.macos_minimum_system_version.as_str()),
),
] {
if let Some(value) = value {
validate_text(field, value)?;
}
}
let icons = resolve_bundle_paths(root, bundle.icons, "bundle icon")?;
let resources = resolve_bundle_paths(root, bundle.resources, "bundle resource")?;
Ok(BundleSettings {
active: bundle.active,
version: bundle.version,
publisher: bundle.publisher,
description: bundle.description,
copyright: bundle.copyright,
icons,
resources,
macos_minimum_system_version: bundle.macos_minimum_system_version,
})
}
fn resolve_bundle_paths(
root: &Path,
paths: Vec<PathBuf>,
kind: &'static str,
) -> Result<Vec<PathBuf>, CliError> {
paths
.into_iter()
.map(|path| {
let path = if path.is_absolute() {
path
} else {
root.join(path)
};
if !path.exists() {
return Err(CliError::MissingProjectPath { kind, path });
}
path.canonicalize()
.map_err(|source| CliError::InvalidProjectPath { path, source })
})
.collect()
}
fn canonicalize_from(current_dir: &Path, path: &Path) -> Result<PathBuf, CliError> {
let path = if path.is_absolute() {
path.to_path_buf()
} else {
current_dir.join(path)
};
path.canonicalize()
.map_err(|source| CliError::InvalidProjectPath { path, source })
}
fn find_config(start: &Path) -> Result<PathBuf, CliError> {
let start = if start.is_file() {
start.parent().unwrap_or(start)
} else {
start
};
for directory in start.ancestors() {
let candidate = directory.join("kayro.toml");
if candidate.is_file() {
return candidate
.canonicalize()
.map_err(|source| CliError::InvalidProjectPath {
path: candidate,
source,
});
}
}
Err(CliError::ProjectNotFound {
start: start.display().to_string(),
})
}
#[cfg(test)]
mod tests {
use std::fs;
use tempfile::tempdir;
use super::*;
fn fixture() -> (tempfile::TempDir, PathBuf) {
let directory = tempdir().unwrap();
let root = directory.path();
fs::create_dir_all(root.join("src-kayro")).unwrap();
fs::write(root.join("src-kayro/Cargo.toml"), "[package]\nname='app'\n").unwrap();
fs::write(
root.join("kayro.toml"),
"[app]\nname='Test'\nidentifier='dev.test.app'\n",
)
.unwrap();
let nested = root.join("src/nested");
fs::create_dir_all(&nested).unwrap();
(directory, nested)
}
#[test]
fn discovers_a_project_from_a_nested_directory() {
let (_directory, nested) = fixture();
let config = find_config(&nested).unwrap();
let project = Project::load(config).unwrap();
assert_eq!(project.dev_command, ["bun", "run", "dev:web"]);
assert_eq!(project.dev_url.as_str(), "http://127.0.0.1:5173/");
assert!(project.native_manifest.ends_with("src-kayro/Cargo.toml"));
}
#[test]
fn reads_explicit_argument_vector_commands() {
let (directory, _) = fixture();
fs::write(
directory.path().join("kayro.toml"),
r#"
[build]
dev_command = ["bun", "x", "vite"]
build_command = ["bun", "x", "vite", "build"]
dev_url = "http://localhost:4000"
"#,
)
.unwrap();
let project = Project::load(directory.path().join("kayro.toml")).unwrap();
assert_eq!(project.dev_command, ["bun", "x", "vite"]);
assert_eq!(project.dev_url.port(), Some(4000));
}
#[test]
fn detects_standard_vite_scripts_without_configuration() {
let (directory, _) = fixture();
fs::write(
directory.path().join("package.json"),
r#"{"scripts":{"dev":"vite","build":"vite build"}}"#,
)
.unwrap();
let project = Project::load(directory.path().join("kayro.toml")).unwrap();
assert_eq!(project.dev_command, ["bun", "run", "dev"]);
assert_eq!(project.build_command, ["bun", "run", "build"]);
}
#[test]
fn resolves_bundle_metadata_and_paths_from_the_project_root() {
let (directory, _) = fixture();
fs::create_dir_all(directory.path().join("icons")).unwrap();
fs::write(directory.path().join("icons/app.png"), "fixture").unwrap();
fs::write(
directory.path().join("kayro.toml"),
r#"
[app]
name = "Bundle Test"
identifier = "dev.test.bundle"
[bundle]
publisher = "Kayro Labs"
icons = ["icons/app.png"]
macos_minimum_system_version = "14.0"
"#,
)
.unwrap();
let project = Project::load(directory.path().join("kayro.toml")).unwrap();
assert_eq!(project.bundle.publisher.as_deref(), Some("Kayro Labs"));
assert_eq!(project.bundle.macos_minimum_system_version, "14.0");
assert!(project.bundle.icons[0].ends_with("icons/app.png"));
}
#[test]
fn rejects_unknown_build_keys() {
let (directory, _) = fixture();
fs::write(
directory.path().join("kayro.toml"),
"[build]\ndev_comand = ['bun']\n",
)
.unwrap();
assert!(matches!(
Project::load(directory.path().join("kayro.toml")),
Err(CliError::ParseConfig { .. })
));
}
#[test]
fn rejects_unknown_top_level_sections() {
let (directory, _) = fixture();
fs::write(
directory.path().join("kayro.toml"),
"[buid]\ndev_command = ['bun']\n",
)
.unwrap();
assert!(matches!(
Project::load(directory.path().join("kayro.toml")),
Err(CliError::ParseConfig { .. })
));
}
}