use std::fs;
use std::io::{self, Read};
use std::path::Path;
use fig::{Document, Format, Value};
const FORMATS: &[(Format, &str, &[&str])] = &[
(Format::Json, "json", &["json"]),
(Format::Jsonc, "jsonc", &["jsonc"]),
(Format::Json5, "json5", &["json5"]),
(Format::Yaml, "yaml", &["yaml", "yml"]),
(Format::Toml, "toml", &["toml"]),
(Format::Zon, "zon", &["zon"]),
(Format::Fig, "fig", &["figl", "fig"]),
];
pub fn format_named(name: &str) -> Option<Format> {
FORMATS
.iter()
.find(|(_, word, _)| *word == name)
.or_else(|| FORMATS.iter().find(|(_, _, ext)| ext.contains(&name)))
.map(|(format, _, _)| *format)
}
pub fn format_words() -> String {
FORMATS
.iter()
.map(|(_, word, _)| *word)
.collect::<Vec<_>>()
.join(", ")
}
pub fn load(path: &str, forced: Option<Format>) -> Result<Value, String> {
load_with(path, forced, NoBlock::IsAnError)
}
pub fn load_or_empty(path: &str, forced: Option<Format>) -> Result<Value, String> {
load_with(path, forced, NoBlock::IsEmpty)
}
#[derive(Clone, Copy)]
enum NoBlock {
IsAnError,
IsEmpty,
}
fn load_with(path: &str, forced: Option<Format>, no_block: NoBlock) -> Result<Value, String> {
let bytes = read(path)?;
if forced.is_none() && is_markdown(path) {
return embedded(path, &bytes, no_block);
}
let format = match forced {
Some(format) => format,
None => extension_format(path).ok_or_else(|| {
let what = if path == "-" {
"standard input has no extension".to_owned()
} else {
format!("nothing names the format of {path}")
};
format!("{what}; pass --input <{}>", format_words())
})?,
};
parse(path, &bytes, format)
}
fn read(path: &str) -> Result<Vec<u8>, String> {
if path == "-" {
let mut bytes = Vec::new();
return io::stdin()
.read_to_end(&mut bytes)
.map(|_| bytes)
.map_err(|error| format!("standard input: {error}"));
}
fs::read(path).map_err(|error| format!("{path}: {error}"))
}
fn embedded(path: &str, bytes: &[u8], no_block: NoBlock) -> Result<Value, String> {
let source = std::str::from_utf8(bytes).map_err(|_| format!("{path}: not valid UTF-8"))?;
let kind = match (fig::detect(source), no_block) {
(Some(kind), _) => kind,
(None, NoBlock::IsEmpty) => return Ok(Value::Map(Vec::new())),
(None, NoBlock::IsAnError) => {
return Err(format!(
"{path} holds no frontmatter or endmatter block, so there is no \
document in it"
));
}
};
let (_, content, _) = fig::split(source, kind)
.ok_or_else(|| format!("{path}: the {kind:?} block could not be read"))?;
parse(path, content.as_bytes(), kind.inner_format())
}
fn parse(path: &str, bytes: &[u8], format: Format) -> Result<Value, String> {
let document = Document::parse(bytes, format).map_err(|error| match error {
fig::Error::UnsupportedFormat => explain_unsupported(format),
other => format!("{path}: {other}"),
})?;
document
.to_value()
.map_err(|error| format!("{path}: {error}"))
}
fn explain_unsupported(format: Format) -> String {
format!(
"this build of fig-schema cannot read {format:?}: it links fig's default \
languages (json, yaml, toml, fig), because any other set has to be \
compiled from source with a Zig toolchain. `fig convert` will move the \
document into one of them"
)
}
fn is_markdown(path: &str) -> bool {
matches!(extension(path).as_deref(), Some("md" | "markdown"))
}
pub fn extensions() -> impl Iterator<Item = &'static str> {
FORMATS
.iter()
.flat_map(|(_, _, extensions)| extensions.iter().copied())
.chain(["md", "markdown"])
}
fn extension_format(path: &str) -> Option<Format> {
let ext = extension(path)?;
FORMATS
.iter()
.find(|(_, _, extensions)| extensions.contains(&ext.as_str()))
.map(|(format, _, _)| *format)
}
fn extension(path: &str) -> Option<String> {
Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.map(str::to_lowercase)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_format_is_reachable_by_its_word_and_by_an_extension() {
for (format, word, extensions) in FORMATS {
assert_eq!(format_named(word), Some(*format), "--input {word}");
for ext in *extensions {
assert_eq!(
extension_format(&format!("doc.{ext}")),
Some(*format),
"doc.{ext}",
);
assert_eq!(format_named(ext), Some(*format), "--input {ext}");
}
}
}
#[test]
fn an_extension_is_matched_case_insensitively_and_only_the_last_one() {
assert_eq!(extension_format("VOCAB.YAML"), Some(Format::Yaml));
assert_eq!(extension_format("audience.vocab.figl"), Some(Format::Fig));
assert_eq!(extension_format(".env.production"), None);
assert_eq!(extension_format("Makefile"), None);
}
#[test]
fn markdown_is_recognized_but_is_not_a_format() {
assert!(is_markdown("note.md") && is_markdown("NOTE.Markdown"));
assert_eq!(extension_format("note.md"), None);
assert_eq!(format_named("md"), None);
}
#[test]
fn a_format_this_build_cannot_read_says_which_ones_it_can() {
let message = explain_unsupported(Format::Zon);
assert!(message.contains("Zon"), "{message}");
assert!(message.contains("json, yaml, toml, fig"), "{message}");
}
#[test]
fn an_unnameable_format_asks_for_input_and_lists_the_words() {
let path = std::env::temp_dir().join("fig-schema-lint-test.ini");
fs::write(&path, b"[vocabulary]\n").unwrap();
let error = load(path.to_str().unwrap(), None).unwrap_err();
let _ = fs::remove_file(&path);
assert!(error.contains("--input"), "{error}");
assert!(error.contains("yaml"), "{error}");
}
#[test]
fn a_missing_file_is_reported_as_missing_rather_than_as_a_format() {
let error = load("no/such/vocabulary.yaml", None).unwrap_err();
assert!(error.starts_with("no/such/vocabulary.yaml:"), "{error}");
assert!(!error.contains("--input"), "{error}");
}
}