use std::num::NonZeroUsize;
use std::path::Path;
use serde_saphyr::{DefaultMessageFormatter, MessageFormatter};
use super::syntax::syntax_diagnostic;
use crate::types::format::YamlValue;
use crate::types::format::parse_yaml;
use crate::types::frontmatter::body::BodyStart;
use crate::types::frontmatter::error::FrontmatterError;
use crate::types::report::Diagnostic;
use crate::types::report::Location;
const DELIMITER: &str = "---";
fn is_delimiter(line: &str) -> bool {
let without_newline = line.strip_suffix('\n').unwrap_or(line);
without_newline
.strip_suffix('\r')
.unwrap_or(without_newline)
== DELIMITER
}
#[derive(Debug, Clone, Copy)]
pub struct Frontmatter<'a> {
file: &'a Path,
yaml: &'a str,
body_start: BodyStart,
}
impl<'a> Frontmatter<'a> {
pub fn split(file: &'a Path, text: &'a str) -> Result<Self, Diagnostic> {
let missing = || Diagnostic::new(Location::file(file), FrontmatterError::Missing);
let mut lines = text.split_inclusive('\n');
let opening = lines.next().ok_or_else(missing)?;
if !is_delimiter(opening) {
return Err(missing());
}
let yaml_start = opening.len();
let mut line_start = yaml_start;
for (index, line) in lines.enumerate() {
let line_end = line_start + line.len();
if is_delimiter(line) {
let body_line = NonZeroUsize::MIN.saturating_add(index + 2);
return Ok(Self {
file,
yaml: &text[yaml_start..line_start],
body_start: BodyStart::new(line_end, body_line),
});
}
line_start = line_end;
}
Err(missing())
}
pub fn mapping(&self) -> Result<Vec<(String, YamlValue)>, Diagnostic> {
match parse_yaml(self.yaml) {
Ok(YamlValue::Map(entries)) => Ok(entries),
Ok(other) => Err(Diagnostic::new(
Location::at_key(self.file, "frontmatter"),
FrontmatterError::NotAMapping {
got: other.kind_word(),
},
)),
Err(error) => Err(syntax_diagnostic(
self.file,
self.yaml,
error.location().map(|location| location.line()),
&DefaultMessageFormatter.format_message(&error),
)),
}
}
#[must_use]
pub const fn yaml(&self) -> &'a str {
self.yaml
}
#[must_use]
pub const fn body_start(&self) -> BodyStart {
self.body_start
}
}
#[cfg(test)]
mod tests {
use super::*;
type TestResult = Result<(), Box<dyn std::error::Error>>;
const FILE: &str = "SKILL.md";
fn split(text: &str) -> Result<Frontmatter<'_>, String> {
Frontmatter::split(Path::new(FILE), text).map_err(|d| d.to_string())
}
fn mapped(block: &str) -> Result<Vec<(String, YamlValue)>, String> {
let text = format!("---\n{block}---\n");
split(&text)?.mapping().map_err(|d| d.to_string())
}
fn mapped_error(block: &str) -> Option<String> {
mapped(block).err()
}
const HINT: &str = "(a value starting with {{ must be quoted)";
#[test]
fn quoting_hint_on_value_starting_with_token() {
assert_eq!(
mapped_error("description: {{skill status}} runs it\n").as_deref(),
Some(format!("SKILL.md:2: expected string scalar {HINT}").as_str())
);
}
#[test]
fn quoting_hint_on_list_item_starting_with_token() {
assert_eq!(
mapped_error("tools:\n - {{skill x}}\n").as_deref(),
Some(format!("SKILL.md:3: expected string scalar {HINT}").as_str())
);
}
#[test]
fn quoting_hint_on_flow_sequence_item() {
assert_eq!(
mapped_error("tools: [a, {{skill x}}]\n").as_deref(),
Some(format!("SKILL.md:2: expected string scalar {HINT}").as_str())
);
}
#[test]
fn no_hint_when_reported_line_has_no_token() {
assert_eq!(
mapped_error("a: [1, 2\n").as_deref(),
Some("SKILL.md:2: unclosed bracket '['")
);
}
#[test]
fn duplicate_key_is_a_syntax_error() {
assert_eq!(
mapped_error("a: 1\na: 2\n").as_deref(),
Some(
"SKILL.md:3: duplicate mapping key: a, set DuplicateKeyPolicy in Options if acceptable"
)
);
}
#[test]
fn duplicate_key_on_a_token_line_gets_no_hint() {
assert_eq!(
mapped_error("a: run {{skill x}}\na: run {{skill y}}\n").as_deref(),
Some(
"SKILL.md:3: duplicate mapping key: a, set DuplicateKeyPolicy in Options if acceptable"
)
);
}
#[test]
fn integer_beyond_i64_gets_its_own_message() {
assert_eq!(
mapped_error("a: 1\nn: 9223372036854775808\n").as_deref(),
Some("SKILL.md:3: integer beyond i64")
);
assert_eq!(
mapped_error("n: [18446744073709551615]\n").as_deref(),
Some("SKILL.md:2: integer beyond i64")
);
}
#[test]
fn integer_at_i64_max_parses() -> TestResult {
let entries = mapped("n: 9223372036854775807\n")?;
assert_eq!(entries, vec![("n".to_owned(), YamlValue::Int(i64::MAX))]);
Ok(())
}
#[test]
fn quoted_token_value_parses() -> TestResult {
let entries = mapped("description: \"{{skill status}} runs it\"\n")?;
assert_eq!(
entries,
vec![(
"description".to_owned(),
YamlValue::Str("{{skill status}} runs it".to_owned())
)]
);
Ok(())
}
#[test]
fn empty_frontmatter_is_refused_as_null() {
let refused = "SKILL.md: frontmatter: expected a mapping, got null";
assert_eq!(mapped_error("").as_deref(), Some(refused));
assert_eq!(mapped_error("# a comment\n").as_deref(), Some(refused));
}
#[test]
fn non_mapping_frontmatter_is_refused() {
assert_eq!(
mapped_error("- a\n").as_deref(),
Some("SKILL.md: frontmatter: expected a mapping, got array")
);
assert_eq!(
mapped_error("just text\n").as_deref(),
Some("SKILL.md: frontmatter: expected a mapping, got string")
);
}
#[test]
fn split_returns_yaml_and_body_start() -> TestResult {
let text = "---\nname: x\n---\n# Title\n";
let split = split(text)?;
assert_eq!(split.yaml(), "name: x\n");
assert_eq!(split.body_start().body(text), "# Title\n");
assert_eq!(split.body_start().line().get(), 4);
Ok(())
}
#[test]
fn split_accepts_closing_line_at_end_of_file() -> TestResult {
let text = "---\nname: x\n---";
let split = split(text)?;
assert_eq!(split.yaml(), "name: x\n");
assert_eq!(split.body_start().body(text), "");
Ok(())
}
#[test]
fn split_stops_at_first_closing_line() -> TestResult {
let text = "---\nname: x\n---\nintro\n---\nmore\n";
let split = split(text)?;
assert_eq!(split.yaml(), "name: x\n");
assert_eq!(split.body_start().body(text), "intro\n---\nmore\n");
Ok(())
}
#[test]
fn split_accepts_crlf_delimiters() -> TestResult {
let text = "---\r\nname: x\r\n---\r\n# Title\r\n";
let split = split(text)?;
assert_eq!(split.yaml(), "name: x\r\n");
assert_eq!(split.body_start().body(text), "# Title\r\n");
assert_eq!(split.body_start().line().get(), 4);
Ok(())
}
#[test]
fn split_refuses_missing_frontmatter() {
let cases = [
"# Title\nbody\n",
"\n---\nname: x\n---\n",
"---\nname: x\nno closing line\n",
];
for text in cases {
let refused = Frontmatter::split(Path::new(FILE), text)
.err()
.map(|d| d.to_string());
assert_eq!(
refused.as_deref(),
Some("SKILL.md: missing frontmatter"),
"{text:?}"
);
}
}
}