use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Target {
Rust,
Go,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Layout {
#[default]
OneFilePerModule,
FilePerType,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct TypeSpelling {
pub name: String,
pub import: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct Substitution {
pub rust: Option<TypeSpelling>,
pub go: Option<TypeSpelling>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct FieldConfig {
pub attrs: Vec<String>,
pub go_tags: BTreeMap<String, String>,
pub rename: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct TypeConfig {
pub attrs: Vec<String>,
pub rename: Option<String>,
pub validation: Option<bool>,
pub fields: BTreeMap<String, FieldConfig>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct RustConfigFile {
pub module: Option<String>,
pub edition: Option<String>,
pub derives: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct GoConfigFile {
pub package: Option<String>,
pub file: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields, rename_all = "snake_case")]
#[non_exhaustive]
pub struct ConfigFile {
pub target: Option<Target>,
pub layout: Option<Layout>,
pub validation: Option<bool>,
pub exact_numbers: Option<bool>,
pub header: Option<String>,
pub extra_imports: Vec<String>,
pub allow_codegen_extensions: Option<bool>,
pub template_dir: Option<PathBuf>,
pub rust: RustConfigFile,
pub go: GoConfigFile,
pub substitutions: BTreeMap<String, Substitution>,
pub types: BTreeMap<String, TypeConfig>,
}
impl ConfigFile {
pub fn from_path(path: &Path) -> Result<ConfigFile, ConfigError> {
let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
path: path.to_path_buf(),
source,
})?;
let base = path.parent().unwrap_or_else(|| Path::new("."));
ConfigFile::from_toml(&text, base).map_err(|error| match error {
ConfigError::Parse { source, .. } => ConfigError::Parse {
path: Some(path.to_path_buf()),
source,
},
other => other,
})
}
pub fn from_toml(text: &str, base: &Path) -> Result<ConfigFile, ConfigError> {
let mut file: ConfigFile =
toml::from_str(text).map_err(|source| ConfigError::Parse { path: None, source })?;
if let Some(dir) = file.template_dir.take() {
file.template_dir = Some(if dir.is_absolute() {
dir
} else {
base.join(dir)
});
}
Ok(file)
}
pub fn merge(mut self, over: ConfigFile) -> ConfigFile {
self.target = over.target.or(self.target);
self.layout = over.layout.or(self.layout);
self.validation = over.validation.or(self.validation);
self.exact_numbers = over.exact_numbers.or(self.exact_numbers);
self.header = over.header.or(self.header);
self.extra_imports.extend(over.extra_imports);
self.allow_codegen_extensions = over
.allow_codegen_extensions
.or(self.allow_codegen_extensions);
self.template_dir = over.template_dir.or(self.template_dir);
self.rust.module = over.rust.module.or(self.rust.module);
self.rust.edition = over.rust.edition.or(self.rust.edition);
self.rust.derives.extend(over.rust.derives);
self.go.package = over.go.package.or(self.go.package);
self.go.file = over.go.file.or(self.go.file);
self.substitutions.extend(over.substitutions);
self.types.extend(over.types);
self
}
pub fn build(self) -> Result<Config, ConfigError> {
let target = self.target.ok_or(ConfigError::MissingTarget)?;
Ok(Config {
target,
layout: self.layout.unwrap_or_default(),
validation: self.validation.unwrap_or(false),
exact_numbers: self.exact_numbers.unwrap_or(false),
header: self.header,
extra_imports: self.extra_imports,
allow_codegen_extensions: self.allow_codegen_extensions.unwrap_or(false),
template_dir: self.template_dir,
rust: RustConfig {
module: match self.rust.module {
Some(module) => {
if !is_module_name(&module) {
return Err(ConfigError::InvalidModule(module));
}
module
}
None => "types".to_owned(),
},
edition: self.rust.edition.unwrap_or_else(|| "2024".to_owned()),
derives: self.rust.derives,
},
go: GoConfig {
package: match self.go.package {
Some(package) => {
if !crate::go::naming::is_package_name(&package) {
return Err(ConfigError::InvalidPackage(package));
}
package
}
None => "api".to_owned(),
},
file: match self.go.file {
Some(file) => {
if !crate::go::naming::is_file_stem(&file) {
return Err(ConfigError::InvalidGoFile(file));
}
file
}
None => "types".to_owned(),
},
},
substitutions: self.substitutions,
types: self.types,
})
}
}
fn shadows_a_crate(module: &str) -> bool {
matches!(
module,
"std" | "core" | "alloc" | "proc_macro" | "test" | "serde" | "serde_json" | "lib" | "main"
)
}
pub(crate) fn is_module_name(module: &str) -> bool {
crate::write::windows_safe(module)
&& !shadows_a_crate(module)
&& !crate::rust::naming::is_keyword(module)
&& module.starts_with(|c: char| c.is_ascii_lowercase())
&& module
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
}
pub fn rust_module_name(text: &str) -> String {
let mut module: String = text
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'_'
}
})
.collect();
while module.contains("__") {
module = module.replace("__", "_");
}
let module = module.trim_matches('_').to_owned();
let module = match module.chars().next() {
None => "api".to_owned(),
Some(c) if c.is_ascii_digit() => format!("m_{module}"),
Some(_) => module,
};
if crate::rust::naming::is_keyword(&module)
|| !crate::write::windows_safe(&module)
|| shadows_a_crate(&module)
{
format!("{module}_types")
} else {
module
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RustConfig {
pub module: String,
pub edition: String,
pub derives: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct GoConfig {
pub package: String,
pub file: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Config {
pub target: Target,
pub layout: Layout,
pub validation: bool,
pub exact_numbers: bool,
pub header: Option<String>,
pub extra_imports: Vec<String>,
pub allow_codegen_extensions: bool,
pub template_dir: Option<PathBuf>,
pub rust: RustConfig,
pub go: GoConfig,
pub substitutions: BTreeMap<String, Substitution>,
pub types: BTreeMap<String, TypeConfig>,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ConfigError {
#[error("cannot read configuration file {path}")]
Read {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("configuration{} is not valid: {source}", match path { Some(p) => format!(" file {}", p.display()), None => String::new() })]
Parse {
path: Option<PathBuf>,
#[source]
source: toml::de::Error,
},
#[error("no target language: set `target`")]
MissingTarget,
#[error(
"`rust.module = {0:?}` must be a lowercase Rust module name: a letter, then letters, digits or `_`; not a keyword, a crate name such as `std` or `serde`, `lib` or `main`, or a name Windows reserves"
)]
InvalidModule(String),
#[error(
"`go.package = {0:?}` must be a lowercase Go package name: a letter, then letters, digits or `_`; not a keyword, nor `main`, `init` or `documentation`, which no other package can import"
)]
InvalidPackage(String),
#[error(
"`go.file = {0:?}` must be a lowercase file stem `go build` reads as plain source: a letter, then letters, digits or `_`; no `_test`, `_<os>` or `_<arch>` suffix, and not a name Windows reserves"
)]
InvalidGoFile(String),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_two_line_file_parses_and_builds_with_a_target() {
let file = ConfigFile::from_toml(
"[types.Pet.fields.tag]\nattrs = ['#[validate(length(min = 1))]']\n",
Path::new("/cfg"),
)
.unwrap();
assert_eq!(
file.types["Pet"].fields["tag"].attrs,
vec!["#[validate(length(min = 1))]".to_owned()]
);
assert!(matches!(
file.clone().build(),
Err(ConfigError::MissingTarget)
));
let config = file
.merge(ConfigFile {
target: Some(Target::Rust),
..Default::default()
})
.build()
.unwrap();
assert_eq!(config.target, Target::Rust);
assert_eq!(config.layout, Layout::OneFilePerModule);
assert!(!config.validation);
assert_eq!(config.rust.edition, "2024");
assert_eq!(config.go.package, "api");
}
#[test]
fn unknown_keys_are_rejected_at_every_level() {
for text in [
"validaton = true\n",
"[rust]\ncrate = \"x\"\n",
"[types.Pet]\nattr = []\n",
"[types.Pet.fields.tag]\nattr = []\n",
"[substitutions.uuid.rust]\ntype = \"x\"\n",
] {
let error = ConfigFile::from_toml(text, Path::new("/cfg")).unwrap_err();
assert!(
matches!(error, ConfigError::Parse { .. }),
"{text:?} -> {error}"
);
}
}
#[test]
fn relative_template_dir_resolves_against_the_base() {
let file = ConfigFile::from_toml("template_dir = \"templates\"\n", Path::new("/proj/cfg"))
.unwrap();
assert_eq!(
file.template_dir.as_deref(),
Some(Path::new("/proj/cfg/templates"))
);
let file =
ConfigFile::from_toml("template_dir = \"/abs\"\n", Path::new("/proj/cfg")).unwrap();
assert_eq!(file.template_dir.as_deref(), Some(Path::new("/abs")));
}
#[test]
fn from_path_resolves_against_the_files_directory_and_names_it_on_error() {
let dir = std::env::temp_dir().join(format!("roas-codegen-config-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("codegen.toml");
std::fs::write(&path, "target = \"go\"\ntemplate_dir = \"tpl\"\n").unwrap();
let file = ConfigFile::from_path(&path).unwrap();
assert_eq!(
file.template_dir.as_deref(),
Some(dir.join("tpl").as_path())
);
std::fs::write(&path, "target = 1\n").unwrap();
let error = ConfigFile::from_path(&path).unwrap_err();
assert!(error.to_string().contains("codegen.toml"), "{error}");
let missing = ConfigFile::from_path(&dir.join("absent.toml")).unwrap_err();
assert!(matches!(missing, ConfigError::Read { .. }));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn merge_lets_later_values_win_and_combines_collections() {
let base = ConfigFile::from_toml(
"target = \"rust\"\nvalidation = true\nextra_imports = [\"a\"]\n[rust]\nderives = [\"Eq\"]\n[types.Pet]\nrename = \"Animal\"\n",
Path::new("/"),
)
.unwrap();
let over = ConfigFile::from_toml(
"target = \"go\"\nextra_imports = [\"b\"]\n[types.Owner]\nrename = \"Person\"\n",
Path::new("/"),
)
.unwrap();
let merged = base.merge(over);
assert_eq!(merged.target, Some(Target::Go));
assert_eq!(merged.validation, Some(true));
assert_eq!(merged.extra_imports, vec!["a".to_owned(), "b".to_owned()]);
assert_eq!(merged.rust.derives, vec!["Eq".to_owned()]);
assert_eq!(merged.types.len(), 2);
}
#[test]
fn substitutions_and_layout_parse() {
let file = ConfigFile::from_toml(
"target = \"rust\"\nlayout = \"file_per_type\"\n[substitutions.uuid]\nrust = { name = \"uuid::Uuid\", import = \"uuid\" }\ngo = { name = \"uuid.UUID\" }\n",
Path::new("/"),
)
.unwrap();
let config = file.build().unwrap();
assert_eq!(config.layout, Layout::FilePerType);
let uuid = &config.substitutions["uuid"];
assert_eq!(uuid.rust.as_ref().unwrap().import.as_deref(), Some("uuid"));
assert_eq!(uuid.go.as_ref().unwrap().name, "uuid.UUID");
assert!(uuid.go.as_ref().unwrap().import.is_none());
}
#[test]
fn module_names_windows_resolves_elsewhere_are_avoided() {
assert_eq!(rust_module_name("aux"), "aux_types");
assert_eq!(rust_module_name("COM1"), "com1_types");
assert!(is_module_name(&rust_module_name("nul")));
assert!(!is_module_name("con"));
}
#[test]
fn module_names_never_shadow_a_crate() {
assert_eq!(rust_module_name("std"), "std_types");
assert_eq!(rust_module_name("serde"), "serde_types");
assert_eq!(rust_module_name("lib"), "lib_types");
assert!(!is_module_name("main"));
assert!(!is_module_name("core"));
}
}