use std::error::Error;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::contract::DEFAULT_MANIFEST_PATH;
pub const CONFIG_VERSION: u16 = 1;
pub const CONFIG_FILE: &str = "Coatcheck.toml";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
pub version: u16,
pub name: String,
pub host: HostConfig,
#[serde(default)]
pub test: TestConfig,
}
impl Config {
pub fn load(path: &Path) -> Result<Self, ConfigError> {
let source = fs::read_to_string(path).map_err(|source| ConfigError::Read {
path: path.to_path_buf(),
source,
})?;
let config: Self = toml::from_str(&source).map_err(ConfigError::Parse)?;
config.validate()?;
Ok(config)
}
pub fn validate(&self) -> Result<(), ConfigError> {
if self.version != CONFIG_VERSION {
return Err(ConfigError::UnsupportedVersion(self.version));
}
if self.name.trim().is_empty() {
return Err(ConfigError::Invalid("name cannot be empty"));
}
if self.host.command.is_empty()
|| self.host.command.iter().any(|part| part.trim().is_empty())
{
return Err(ConfigError::Invalid(
"host.command must contain non-empty program arguments",
));
}
let base_url = Url::parse(&self.host.url)
.map_err(|_| ConfigError::Invalid("host.url must be an absolute HTTP(S) URL"))?;
if !matches!(base_url.scheme(), "http" | "https") || base_url.cannot_be_a_base() {
return Err(ConfigError::Invalid(
"host.url must be an absolute HTTP(S) URL",
));
}
for (name, value) in [
("host.health", self.host.health.as_str()),
("host.manifest", self.host.manifest.as_str()),
] {
if value.trim().is_empty() || !value.starts_with('/') {
return Err(ConfigError::Invalid(match name {
"host.health" => "host.health must start with /",
_ => "host.manifest must start with /",
}));
}
}
if self.host.startup_timeout_seconds == 0 {
return Err(ConfigError::Invalid(
"host.startup_timeout_seconds must be greater than zero",
));
}
if self.test.timeout_ms == 0 {
return Err(ConfigError::Invalid(
"test.timeout_ms must be greater than zero",
));
}
if self
.test
.story_globs
.iter()
.any(|glob| glob.trim().is_empty())
{
return Err(ConfigError::Invalid(
"test.story_globs cannot contain empty patterns",
));
}
if self.test.artifacts.as_os_str().is_empty() {
return Err(ConfigError::Invalid("test.artifacts cannot be empty"));
}
if self.test.axe_impacts.is_empty()
|| self.test.axe_impacts.iter().any(|impact| {
!matches!(
impact.as_str(),
"minor" | "moderate" | "serious" | "critical"
)
})
{
return Err(ConfigError::Invalid(
"test.axe_impacts must use minor, moderate, serious, or critical",
));
}
Ok(())
}
pub fn endpoint(&self, path: &str) -> Result<Url, ConfigError> {
let base = Url::parse(&self.host.url)
.map_err(|_| ConfigError::Invalid("host.url must be an absolute HTTP(S) URL"))?;
base.join(path)
.map_err(|_| ConfigError::Invalid("host endpoint path is invalid"))
}
#[must_use]
pub fn artifacts_dir(&self, project_root: &Path) -> PathBuf {
project_root.join(&self.test.artifacts)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HostConfig {
pub command: Vec<String>,
pub url: String,
#[serde(default = "default_health")]
pub health: String,
#[serde(default = "default_manifest")]
pub manifest: String,
#[serde(default = "default_startup_timeout")]
pub startup_timeout_seconds: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct TestConfig {
pub story_globs: Vec<String>,
pub artifacts: PathBuf,
pub timeout_ms: u64,
pub axe_impacts: Vec<String>,
}
impl Default for TestConfig {
fn default() -> Self {
Self {
story_globs: vec!["coatcheck/**/*.spec.ts".to_owned()],
artifacts: PathBuf::from(".coatcheck/artifacts"),
timeout_ms: 30_000,
axe_impacts: vec!["serious".to_owned(), "critical".to_owned()],
}
}
}
fn default_health() -> String {
"/health".to_owned()
}
fn default_manifest() -> String {
DEFAULT_MANIFEST_PATH.to_owned()
}
const fn default_startup_timeout() -> u64 {
30
}
#[derive(Debug)]
pub enum ConfigError {
Read {
path: PathBuf,
source: std::io::Error,
},
Parse(toml::de::Error),
UnsupportedVersion(u16),
Invalid(&'static str),
}
impl fmt::Display for ConfigError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Read { path, source } => {
write!(formatter, "could not read {}: {source}", path.display())
}
Self::Parse(error) => write!(formatter, "invalid Coatcheck.toml: {error}"),
Self::UnsupportedVersion(version) => {
write!(formatter, "unsupported Coatcheck.toml version: {version}")
}
Self::Invalid(message) => formatter.write_str(message),
}
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Read { source, .. } => Some(source),
Self::Parse(source) => Some(source),
Self::UnsupportedVersion(_) | Self::Invalid(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use super::{Config, TestConfig};
#[test]
fn parses_a_cold_front_style_config() {
let config: Config = toml::from_str(
r#"
version = 1
name = "Cold Front"
[host]
command = ["cargo", "run", "-p", "coldfront-coatcheck"]
url = "http://127.0.0.1:3001"
health = "/health"
manifest = "/__coatcheck/manifest.json"
[test]
story_globs = ["coatcheck/**/*.spec.ts"]
artifacts = ".coatcheck/artifacts"
timeout_ms = 30000
axe_impacts = ["serious", "critical"]
"#,
)
.unwrap();
assert_eq!(config.test, TestConfig::default());
assert!(config.validate().is_ok());
assert_eq!(
config.endpoint(&config.host.manifest).unwrap().as_str(),
"http://127.0.0.1:3001/__coatcheck/manifest.json"
);
}
#[test]
fn rejects_shell_strings_as_commands() {
let config: Config = toml::from_str(
r#"
version = 1
name = "Example"
[host]
command = []
url = "http://127.0.0.1:3000"
"#,
)
.unwrap();
assert!(config.validate().is_err());
}
}