use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::error::Error;
pub const VERSION: u32 = 1;
pub const NAME_LEVEL: usize = 3;
pub const SECTION_LEVEL: usize = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Toml,
Json,
Yaml,
}
impl Format {
pub fn from_path(path: &Path) -> Result<Self, Error> {
Self::from_extension(path.extension().and_then(|ext| ext.to_str()).unwrap_or(""))
}
pub fn from_extension(extension: &str) -> Result<Self, Error> {
match extension {
"toml" => Ok(Self::Toml),
"json" => Ok(Self::Json),
"yaml" | "yml" => Ok(Self::Yaml),
other => Err(Error::UnknownFormat(other.to_owned())),
}
}
#[must_use]
pub const fn extension(self) -> &'static str {
match self {
Self::Toml => "toml",
Self::Json => "json",
Self::Yaml => "yaml",
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub header: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub version: u32,
#[serde(default, skip_serializing_if = "Target::is_empty")]
pub gitignore: Target,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Target {
#[serde(default, rename = "section", skip_serializing_if = "Vec::is_empty")]
pub sections: Vec<Section>,
}
impl Target {
#[must_use]
pub const fn is_empty(&self) -> bool {
self.sections.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Section {
#[serde(default = "default_level", skip_serializing_if = "is_default_level")]
pub level: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
#[serde(default, rename = "rule", skip_serializing_if = "Vec::is_empty")]
pub rules: Vec<Rule>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rule {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub add: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ignore: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
impl Default for Section {
fn default() -> Self {
Self {
level: default_level(),
name: None,
note: None,
rules: Vec::new(),
}
}
}
const fn default_level() -> usize {
SECTION_LEVEL
}
#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_default_level(level: &usize) -> bool {
*level == default_level()
}
impl Config {
#[must_use]
pub fn new() -> Self {
Self {
version: VERSION,
..Self::default()
}
}
pub fn decode(text: &str, format: Format) -> Result<Self, Error> {
let config: Self = match format {
Format::Toml => toml::from_str(text)?,
Format::Json => serde_json::from_str(text)?,
Format::Yaml => serde_norway::from_str(text)?,
};
if config.version != VERSION {
return Err(Error::UnsupportedVersion {
found: config.version,
expected: VERSION,
});
}
config.validate()?;
Ok(config)
}
pub fn validate(&self) -> Result<(), Error> {
for (index, section) in self.gitignore.sections.iter().enumerate() {
let at = format!("gitignore.section[{index}]");
if section.level == 0 {
return Err(Error::Invalid {
at,
why: "level must be at least 1: a header needs at least one `#`".to_owned(),
});
}
if section.name.is_none() && section.note.is_some() {
return Err(Error::Invalid {
at,
why: "a note needs a name: without a header there is nothing to attach it to"
.to_owned(),
});
}
for (position, rule) in section.rules.iter().enumerate() {
rule.validate(&format!("{at}.rule[{position}]"))?;
}
}
Ok(())
}
pub fn encode(&self, format: Format) -> Result<String, Error> {
encode_value(self, format)
}
}
impl Rule {
fn validate(&self, at: &str) -> Result<(), Error> {
if self.ignore.is_empty() && self.add.is_empty() && self.note.is_none() {
return Err(Error::Invalid {
at: at.to_owned(),
why:
"a rule needs at least one `ignore` or `add` pattern, or a `note` to stand as \
a placeholder"
.to_owned(),
});
}
for pattern in self.ignore.iter().chain(&self.add) {
if pattern.trim().is_empty() {
return Err(Error::Invalid {
at: at.to_owned(),
why: "a pattern cannot be blank".to_owned(),
});
}
if pattern.contains('\n') {
return Err(Error::Invalid {
at: at.to_owned(),
why: format!("a pattern cannot contain a newline: {pattern:?}"),
});
}
}
for pattern in &self.add {
if let Some(stripped) = pattern.strip_prefix('!') {
return Err(Error::Invalid {
at: at.to_owned(),
why: format!(
"`add` patterns are stored without the leading `!`, which is added when \
rendering. Write {stripped:?} instead of {pattern:?}"
),
});
}
}
Ok(())
}
}
fn encode_value<T: Serialize>(value: &T, format: Format) -> Result<String, Error> {
match format {
Format::Toml => toml::to_string(value).map_err(Error::from),
Format::Json => serde_json::to_string_pretty(value)
.map(|mut json| {
json.push('\n');
json
})
.map_err(Error::from),
Format::Yaml => serde_norway::to_string(value).map_err(Error::from),
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::{Format, encode_value};
fn unserializable() -> BTreeMap<BTreeMap<String, i32>, i32> {
BTreeMap::from([(BTreeMap::from([("key".to_owned(), 1)]), 2)])
}
#[test]
fn every_encoder_reports_its_own_failure() {
for format in [Format::Toml, Format::Json, Format::Yaml] {
let err = encode_value(&unserializable(), format).expect_err("cannot encode");
assert!(
!err.to_string().is_empty(),
"{format:?} should carry the encoder's message"
);
}
}
}