use crate::rules::line::{
ParseError, is_skippable, parse_builtin, parse_file, parse_flag,
};
use crate::rules::rule_line::parse_rule;
use crate::rules::{Origin, Rule};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Place<'a> {
Builtin,
File(&'a Path),
Argument(usize),
}
impl Place<'_> {
#[must_use]
pub(crate) fn origin(self, line: usize) -> Origin {
match self {
Self::Builtin => Origin::Builtin { line },
Self::File(path) => Origin::File {
path: path.to_path_buf(),
line,
},
Self::Argument(index) => Origin::Argument { index },
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Sources {
builtin: Option<String>,
dotfiles: Vec<(PathBuf, String)>,
files: Vec<(PathBuf, String)>,
flags: Vec<(usize, String)>,
}
impl Sources {
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn builtin(mut self, text: impl Into<String>) -> Self {
self.builtin = Some(text.into());
self
}
pub(crate) fn dotfile(
mut self,
path: impl Into<PathBuf>,
text: impl Into<String>,
) -> Self {
self.dotfiles.push((path.into(), text.into()));
self
}
pub(crate) fn file(
mut self,
path: impl Into<PathBuf>,
text: impl Into<String>,
) -> Self {
self.files.push((path.into(), text.into()));
self
}
pub(crate) fn flag(
mut self,
index: usize,
value: impl Into<String>,
) -> Self {
self.flags.push((index, value.into()));
self
}
pub(crate) fn fidelity(self, index: usize, family: &str) -> Self {
self.flag(index, format!("* @{family}"))
}
#[cfg(test)]
pub(crate) fn from_argv<I>(flags: I) -> Self
where
I: IntoIterator<Item = (usize, String)>,
{
let mut sources = Self::new();
sources.flags = flags.into_iter().collect();
sources
}
pub(crate) fn assemble<T, P>(&self, parse: P) -> Result<Vec<T>, ParseError>
where
P: Fn(&str, Origin) -> Result<T, ParseError> + Copy,
{
let mut entries = Vec::new();
if let Some(text) = &self.builtin {
entries.extend(parse_builtin(text, parse)?);
}
for (path, text) in self.dotfiles.iter().chain(&self.files) {
entries.extend(parse_file(text, path, parse)?);
}
for (index, value) in &self.flags {
entries.extend(parse_flag(value, *index, parse)?);
}
Ok(entries)
}
pub(crate) fn rules(&self) -> Result<Vec<Rule>, ParseError> {
self.assemble(parse_rule)
}
#[must_use]
pub(crate) fn has_builtin(&self) -> bool {
self.builtin.is_some()
}
#[must_use]
pub(crate) fn layers(&self) -> Vec<(Place<'_>, &str)> {
let builtin = self.builtin.iter().map(|t| (Place::Builtin, t.as_str()));
let files = self.dotfiles.iter().chain(&self.files);
let files = files.map(|(path, t)| (Place::File(path), t.as_str()));
let flags = self.flags.iter();
let flags = flags.map(|(at, t)| (Place::Argument(*at), t.as_str()));
builtin.chain(files).chain(flags).collect()
}
#[must_use]
pub(crate) fn lines(&self) -> Vec<String> {
let layers = self.layers().into_iter();
let added = layers.filter(|(place, _)| *place != Place::Builtin);
added
.flat_map(|(_, text)| text.lines())
.filter(|line| !is_skippable(line))
.map(|line| line.trim().to_owned())
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rules::line::describe;
use crate::rules::{ASCII, resolve};
fn matches(pattern: &str, path: &str) -> bool {
match pattern.strip_suffix('*') {
Some(prefix) => path.starts_with(prefix),
None => pattern == path,
}
}
fn winning_set(sources: &Sources, path: &str) -> String {
let rules = sources.rules().unwrap_or_default();
let resolution = resolve(path, &rules, &matches);
resolution.sets.join("+")
}
fn family_of(sources: &Sources, path: &str) -> String {
let rules = sources.rules().unwrap_or_default();
resolve(path, &rules, &matches).family
}
fn origins(sources: &Sources) -> Vec<String> {
let rules = sources.rules().unwrap_or_default();
rules.iter().map(|rule| describe(&rule.origin)).collect()
}
fn every_group() -> Sources {
Sources::new()
.builtin("* box")
.dotfile(".ctrm", "* caveman")
.file("other.ctrm", "* math")
.flag(3, "* legal")
}
#[test]
fn a_flag_beats_a_named_file() {
let sources = every_group();
assert_eq!(winning_set(&sources, "SPEC.md"), "ascii+legal");
}
#[test]
fn a_named_file_beats_a_discovered_dotfile() {
let sources = Sources::new()
.dotfile(".ctrm", "* caveman")
.file("other.ctrm", "* math");
assert_eq!(winning_set(&sources, "SPEC.md"), "ascii+math");
}
#[test]
fn a_dotfile_beats_the_builtin() {
let sources = Sources::new()
.builtin("* box")
.dotfile(".ctrm", "* caveman");
assert_eq!(winning_set(&sources, "SPEC.md"), "ascii+caveman");
}
#[test]
fn the_chain_holds_whatever_order_the_groups_were_filled_in() {
let backwards = Sources::new()
.flag(3, "* legal")
.file("other.ctrm", "* math")
.dotfile(".ctrm", "* caveman")
.builtin("* box");
assert_eq!(backwards.assemble(parse_rule), every_group().rules());
}
#[test]
fn two_files_keep_the_order_they_were_named_in() {
let sources = Sources::new()
.file("first.ctrm", "* caveman")
.file("second.ctrm", "* math");
assert_eq!(winning_set(&sources, "SPEC.md"), "ascii+math");
}
#[test]
fn two_flags_keep_their_argv_order() {
let sources = Sources::new().flag(2, "* caveman").flag(5, "* math");
assert_eq!(winning_set(&sources, "SPEC.md"), "ascii+math");
}
#[test]
fn every_entry_carries_an_origin_that_names_its_source() {
let expected = vec![
"builtin:1".to_string(),
".ctrm:1".to_string(),
"other.ctrm:1".to_string(),
"argv[3]".to_string(),
];
assert_eq!(origins(&every_group()), expected);
}
#[test]
fn an_origin_keeps_the_line_number_inside_its_own_file() {
let sources =
Sources::new().dotfile(".ctrm", "# note\n* caveman\nSPEC.md box");
assert_eq!(origins(&sources), vec![".ctrm:2", ".ctrm:3"]);
}
#[test]
fn a_bad_line_names_the_source_it_came_from() {
let sources = Sources::new().file("other.ctrm", "*.md !loud");
let failure = sources.rules().err().map(|fail| fail.to_string());
let message = "other.ctrm:1: unknown level `loud`".to_string();
assert_eq!(failure, Some(message));
}
#[test]
fn a_source_contributing_nothing_changes_nothing() {
let sources = every_group().file("empty.ctrm", "# only a comment\n");
assert_eq!(sources.rules(), every_group().rules());
}
fn argv_only() -> Sources {
let flags =
[(1, "* caveman".to_string()), (4, "src/* ascii".to_string())];
Sources::from_argv(flags)
}
#[test]
fn the_fidelity_flag_is_exactly_the_rule_flag_it_stands_for() {
let spelled = Sources::new().flag(2, "* @emoji");
assert_eq!(Sources::new().fidelity(2, "emoji"), spelled);
}
#[test]
fn the_fidelity_flag_beats_a_family_named_in_a_file() {
let sources = Sources::new()
.dotfile(".ctrm", "docs/* marks @emoji")
.fidelity(4, "text");
assert_eq!(family_of(&sources, "docs/a.md"), "text");
}
#[test]
fn a_file_read_after_the_flag_would_not_exist_to_beat_it() {
let sources = Sources::new()
.file("other.ctrm", "docs/* @emoji")
.fidelity(4, "text");
assert_eq!(family_of(&sources, "docs/a.md"), "text");
}
#[test]
fn a_run_with_no_source_at_all_holds_no_rule() {
assert_eq!(Sources::new().rules(), Ok(Vec::new()));
}
#[test]
fn a_path_in_a_zero_file_run_still_gets_ascii() {
assert_eq!(winning_set(&Sources::new(), "src/main.rs"), ASCII);
}
#[test]
fn argv_alone_carries_a_whole_configuration() {
assert_eq!(winning_set(&argv_only(), "src/main.rs"), "ascii");
assert_eq!(winning_set(&argv_only(), "SPEC.md"), "ascii+caveman");
}
#[test]
fn a_zero_file_run_records_argv_origins_only() {
let expected = vec!["argv[1]".to_string(), "argv[4]".to_string()];
assert_eq!(origins(&argv_only()), expected);
}
#[test]
fn a_path_no_argv_rule_matches_gets_ascii_too() {
let flags = [(1, "docs/** caveman".to_string())];
let sources = Sources::from_argv(flags);
assert_eq!(winning_set(&sources, "src/main.rs"), ASCII);
}
}