[core] Canon, claims, hooks: strict parser, fail-closed claim checker, hook templates
This commit is contained in:
+232
-19
@@ -26,6 +26,8 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::text::{self, ItemLine, LineError, UrlKind};
|
||||
|
||||
/// Largest canon file accepted, in bytes.
|
||||
pub const MAX_FILE_BYTES: usize = 64 * 1024;
|
||||
|
||||
@@ -124,40 +126,250 @@ pub enum CanonCode {
|
||||
DuplicateApp(String),
|
||||
}
|
||||
|
||||
const REQUIRED: [&str; 7] = [
|
||||
"id",
|
||||
"name",
|
||||
"one_liner",
|
||||
"audience",
|
||||
"price",
|
||||
"clicks",
|
||||
"status",
|
||||
];
|
||||
const OPTIONAL: [&str; 2] = ["aula", "site"];
|
||||
const MARKER: &str = "(assumption)";
|
||||
|
||||
fn err(line: usize, code: CanonCode) -> CanonError {
|
||||
CanonError { line, code }
|
||||
}
|
||||
|
||||
/// Parse `apps/<file_stem>.md`. Strict: any deviation from the format is an error.
|
||||
///
|
||||
/// Tolerated: a leading byte order mark and CRLF line endings. Rejected anywhere: a lone CR, control characters
|
||||
/// other than tab, and hidden or direction-changing characters (bidi controls, zero-width space, tag characters).
|
||||
pub fn parse(file_stem: &str, text: &str) -> Result<CanonFile, CanonError> {
|
||||
let _ = (file_stem, text);
|
||||
todo!()
|
||||
if text.len() > MAX_FILE_BYTES {
|
||||
return Err(err(0, CanonCode::TooLarge { bytes: text.len() }));
|
||||
}
|
||||
let lines = text::clean_lines(text).map_err(|(line, e)| match e {
|
||||
LineError::LoneCr => err(line, CanonCode::LoneCarriageReturn),
|
||||
LineError::Forbidden(codepoint) => err(line, CanonCode::ForbiddenCharacter { codepoint }),
|
||||
})?;
|
||||
if lines.first() != Some(&"---") {
|
||||
return Err(err(1, CanonCode::NoFrontMatter));
|
||||
}
|
||||
|
||||
// Front matter.
|
||||
let mut fields: BTreeMap<&str, (String, usize)> = BTreeMap::new();
|
||||
let mut i = 1;
|
||||
loop {
|
||||
let line = match lines.get(i) {
|
||||
// The empty piece after the final newline is the end of the file.
|
||||
Some(&"") if i + 1 == lines.len() => None,
|
||||
other => other.copied(),
|
||||
};
|
||||
let Some(line) = line else {
|
||||
return Err(err(i, CanonCode::UnclosedFrontMatter));
|
||||
};
|
||||
let n = i + 1;
|
||||
if line == "---" {
|
||||
break;
|
||||
}
|
||||
let Some((key, rest)) = line.split_once(':') else {
|
||||
return Err(err(n, CanonCode::FrontMatterLine));
|
||||
};
|
||||
if key.is_empty() || !key.bytes().all(|b| b.is_ascii_lowercase() || b == b'_') {
|
||||
return Err(err(n, CanonCode::FrontMatterLine));
|
||||
}
|
||||
if !rest.is_empty() && !rest.starts_with(' ') {
|
||||
return Err(err(n, CanonCode::FrontMatterLine));
|
||||
}
|
||||
if !REQUIRED.contains(&key) && !OPTIONAL.contains(&key) {
|
||||
return Err(err(n, CanonCode::UnknownKey(key.to_string())));
|
||||
}
|
||||
if fields.contains_key(key) {
|
||||
return Err(err(n, CanonCode::DuplicateKey(key.to_string())));
|
||||
}
|
||||
let value = rest.trim();
|
||||
if value.is_empty() {
|
||||
return Err(err(n, CanonCode::EmptyValue(key.to_string())));
|
||||
}
|
||||
fields.insert(key, (value.to_string(), n));
|
||||
i += 1;
|
||||
}
|
||||
let close_line = i + 1;
|
||||
for key in REQUIRED {
|
||||
if !fields.contains_key(key) {
|
||||
return Err(err(close_line, CanonCode::MissingKey(key.to_string())));
|
||||
}
|
||||
}
|
||||
let mut take = |key: &str| fields.remove(key).unwrap_or_default();
|
||||
let (id, id_line) = take("id");
|
||||
if !is_valid_app_id(&id) {
|
||||
return Err(err(id_line, CanonCode::BadId(id)));
|
||||
}
|
||||
if id != file_stem {
|
||||
return Err(err(
|
||||
id_line,
|
||||
CanonCode::IdMismatch {
|
||||
id,
|
||||
stem: file_stem.to_string(),
|
||||
},
|
||||
));
|
||||
}
|
||||
let (status_text, status_line) = take("status");
|
||||
let status = match status_text.as_str() {
|
||||
"released" => Status::Released,
|
||||
"beta" => Status::Beta,
|
||||
"planned" => Status::Planned,
|
||||
_ => return Err(err(status_line, CanonCode::BadStatus(status_text))),
|
||||
};
|
||||
let mut url = |key: &str| -> Result<Option<String>, CanonError> {
|
||||
let (v, line) = take(key);
|
||||
if line == 0 {
|
||||
Ok(None)
|
||||
} else if is_single_https_url(&v) {
|
||||
Ok(Some(v))
|
||||
} else {
|
||||
Err(err(line, CanonCode::BadUrl(v)))
|
||||
}
|
||||
};
|
||||
let aula = url("aula")?;
|
||||
let site = url("site")?;
|
||||
let front = FrontMatter {
|
||||
name: take("name").0,
|
||||
one_liner: take("one_liner").0,
|
||||
audience: take("audience").0,
|
||||
price: take("price").0,
|
||||
clicks: take("clicks").0,
|
||||
status,
|
||||
aula,
|
||||
site,
|
||||
};
|
||||
|
||||
// Body: fact lines.
|
||||
let mut facts: Vec<Fact> = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for (j, &line) in lines.iter().enumerate().skip(i + 1) {
|
||||
let n = j + 1;
|
||||
match text::item_line(line, 'F') {
|
||||
ItemLine::No => {}
|
||||
ItemLine::Malformed => return Err(err(n, CanonCode::MalformedFact)),
|
||||
ItemLine::IdOutOfRange => return Err(err(n, CanonCode::FactIdOutOfRange)),
|
||||
ItemLine::Item { id, text } => {
|
||||
let (text, assumption) = split_marker(text.trim());
|
||||
if text.is_empty() {
|
||||
return Err(err(n, CanonCode::EmptyFact));
|
||||
}
|
||||
if !seen.insert(id) {
|
||||
return Err(err(n, CanonCode::DuplicateFact(id)));
|
||||
}
|
||||
facts.push(Fact {
|
||||
id,
|
||||
text: text.to_string(),
|
||||
assumption,
|
||||
line: n,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CanonFile {
|
||||
id: file_stem.to_string(),
|
||||
front,
|
||||
facts,
|
||||
})
|
||||
}
|
||||
|
||||
/// Split a trailing `(assumption)` marker off (any case). A marker anywhere else also makes the fact an assumption.
|
||||
fn split_marker(text: &str) -> (&str, bool) {
|
||||
let len = text.len();
|
||||
if len >= MARKER.len() && text.is_char_boundary(len - MARKER.len()) {
|
||||
let (head, tail) = text.split_at(len - MARKER.len());
|
||||
if tail.eq_ignore_ascii_case(MARKER) {
|
||||
return (head.trim_end(), true);
|
||||
}
|
||||
}
|
||||
(text, text.to_lowercase().contains(MARKER))
|
||||
}
|
||||
|
||||
fn is_single_https_url(v: &str) -> bool {
|
||||
let Some(rest) = v.strip_prefix("https://") else {
|
||||
return false;
|
||||
};
|
||||
if rest.is_empty() || v.chars().any(char::is_whitespace) {
|
||||
return false;
|
||||
}
|
||||
let found = text::find_urls(v);
|
||||
found.len() == 1 && found[0].kind == UrlKind::Scheme && found[0].as_str(v) == v
|
||||
}
|
||||
|
||||
/// True if `id` is a valid app id: 1-32 of `[a-z0-9-]`, no leading or trailing `-`.
|
||||
pub fn is_valid_app_id(id: &str) -> bool {
|
||||
let _ = id;
|
||||
todo!()
|
||||
!id.is_empty()
|
||||
&& id.len() <= 32
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||
&& !id.starts_with('-')
|
||||
&& !id.ends_with('-')
|
||||
}
|
||||
|
||||
/// True if a front matter value is marked `(assumption) `.
|
||||
pub fn is_assumption_value(value: &str) -> bool {
|
||||
let _ = value;
|
||||
todo!()
|
||||
let v = value.trim_start();
|
||||
v.len() >= MARKER.len()
|
||||
&& v.is_char_boundary(MARKER.len())
|
||||
&& v[..MARKER.len()].eq_ignore_ascii_case(MARKER)
|
||||
}
|
||||
|
||||
impl CanonFile {
|
||||
/// The fact with this number.
|
||||
pub fn fact(&self, id: u32) -> Option<&Fact> {
|
||||
let _ = id;
|
||||
todo!()
|
||||
self.facts.iter().find(|f| f.id == id)
|
||||
}
|
||||
|
||||
/// Allowed URLs of this file: `aula`, `site`, and every `https://` URL inside a fact's text. Sorted, unique.
|
||||
pub fn urls(&self) -> Vec<String> {
|
||||
todo!()
|
||||
let mut set: BTreeSet<String> = BTreeSet::new();
|
||||
set.extend(self.front.aula.iter().cloned());
|
||||
set.extend(self.front.site.iter().cloned());
|
||||
for f in &self.facts {
|
||||
for u in text::find_urls(&f.text) {
|
||||
let s = u.as_str(&f.text);
|
||||
if u.kind == UrlKind::Scheme
|
||||
&& s.len() > "https://".len()
|
||||
&& s.starts_with("https://")
|
||||
{
|
||||
set.insert(s.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
set.into_iter().collect()
|
||||
}
|
||||
|
||||
/// An in-memory canon file (for the `release` source). Facts count as confirmed. Not validated.
|
||||
pub fn adhoc(id: &str, name: &str, facts: Vec<(u32, String)>) -> CanonFile {
|
||||
let _ = (id, name, facts);
|
||||
todo!()
|
||||
CanonFile {
|
||||
id: id.to_string(),
|
||||
front: FrontMatter {
|
||||
name: name.to_string(),
|
||||
one_liner: String::new(),
|
||||
audience: String::new(),
|
||||
price: String::new(),
|
||||
clicks: String::new(),
|
||||
status: Status::Released,
|
||||
aula: None,
|
||||
site: None,
|
||||
},
|
||||
facts: facts
|
||||
.into_iter()
|
||||
.map(|(id, text)| Fact {
|
||||
id,
|
||||
text,
|
||||
assumption: false,
|
||||
line: 0,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,18 +381,20 @@ pub struct Canon {
|
||||
|
||||
impl Canon {
|
||||
pub fn new() -> Self {
|
||||
todo!()
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Add a file. A second file with the same id is an error.
|
||||
pub fn insert(&mut self, f: CanonFile) -> Result<(), CanonError> {
|
||||
let _ = f;
|
||||
todo!()
|
||||
if self.files.contains_key(&f.id) {
|
||||
return Err(err(0, CanonCode::DuplicateApp(f.id)));
|
||||
}
|
||||
self.files.insert(f.id.clone(), f);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get(&self, app: &str) -> Option<&CanonFile> {
|
||||
let _ = app;
|
||||
todo!()
|
||||
self.files.get(app)
|
||||
}
|
||||
|
||||
/// All files, sorted by id.
|
||||
@@ -189,12 +403,11 @@ impl Canon {
|
||||
}
|
||||
|
||||
pub fn fact(&self, app: &str, id: u32) -> Option<&Fact> {
|
||||
let _ = (app, id);
|
||||
todo!()
|
||||
self.get(app)?.fact(id)
|
||||
}
|
||||
|
||||
/// The union of every file's [`CanonFile::urls`].
|
||||
pub fn allowed_urls(&self) -> BTreeSet<String> {
|
||||
todo!()
|
||||
self.files.values().flat_map(CanonFile::urls).collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,18 @@
|
||||
//! Every sentence that states a fact carries at least one `[app#Fn]` reference (several may be adjacent:
|
||||
//! `[tabula#F3][tabula#F7]`) at its end, and every reference must point to a confirmed canon fact.
|
||||
//! Fail closed: a sentence states a fact unless it is one of a short list of plain phrases
|
||||
//! ("Here's what's new.", "Try it today.").
|
||||
//! ("Here's what's new.", "Try it today."), so numbers, prices, platforms and feature claims always need a reference.
|
||||
//!
|
||||
//! Sentences end at `.`, `!`, `?` or `…` followed by whitespace (or the end), and at every line break.
|
||||
//! References directly after the end mark belong to the sentence before them.
|
||||
//! URLs (`scheme://`, `www.`, bare `host.tld/path`) must be in [`Canon::allowed_urls`].
|
||||
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::canon::Canon;
|
||||
use crate::canon::{self, Canon};
|
||||
use crate::text::{self, FoundUrl};
|
||||
|
||||
/// A claim reference `[app#F<fact>]`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
@@ -19,8 +26,14 @@ pub struct Ref {
|
||||
pub fact: u32,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Ref {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "[{}#F{}]", self.app, self.fact)
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a text fails the claim check.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub enum Problem {
|
||||
/// A sentence that states a fact without any reference.
|
||||
@@ -42,7 +55,25 @@ pub enum Problem {
|
||||
impl Problem {
|
||||
/// Plain English, for "Needs facts".
|
||||
pub fn reason(&self) -> String {
|
||||
todo!()
|
||||
match self {
|
||||
Problem::Unsourced { sentence } => {
|
||||
format!("States a fact with no source: \"{sentence}\"")
|
||||
}
|
||||
Problem::MissingFact { r } => format!("{r} does not exist in the canon."),
|
||||
Problem::UnknownApp { r } => format!("{r} points to an unknown app \"{}\".", r.app),
|
||||
Problem::Unconfirmed { r } => {
|
||||
format!(
|
||||
"{r} is an unconfirmed fact (marked assumption); confirm it in the canon first."
|
||||
)
|
||||
}
|
||||
Problem::MalformedRef { text } => {
|
||||
format!("\"{text}\" is not a valid reference; use [app#Fn].")
|
||||
}
|
||||
Problem::UrlNotInCanon { url } => format!("The URL {url} is not in the canon."),
|
||||
Problem::HiddenCharacter { codepoint } => {
|
||||
format!("Hidden or direction-changing character U+{codepoint:04X}.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,26 +91,362 @@ impl Report {
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain phrases that state no fact (normalised: lower case, letters, digits and apostrophes only).
|
||||
/// `{app}` matches the name or id of any app in the canon. Keep this list short and conservative.
|
||||
const PLAIN: &[&str] = &[
|
||||
"here's what's new",
|
||||
"here is what's new",
|
||||
"what's new",
|
||||
"here's what changed",
|
||||
"what changed",
|
||||
"try it",
|
||||
"try it today",
|
||||
"try it now",
|
||||
"try it out",
|
||||
"try {app}",
|
||||
"try {app} today",
|
||||
"try {app} now",
|
||||
"check it out",
|
||||
"take a look",
|
||||
"have a look",
|
||||
"learn more",
|
||||
"read more",
|
||||
"more here",
|
||||
"details here",
|
||||
"more below",
|
||||
"details below",
|
||||
"get it here",
|
||||
"get {app} here",
|
||||
"download it here",
|
||||
"release notes",
|
||||
"full release notes",
|
||||
"release notes below",
|
||||
"thanks for reading",
|
||||
"thank you",
|
||||
"thanks",
|
||||
"enjoy",
|
||||
"let me know what you think",
|
||||
"tell me what you think",
|
||||
"feedback welcome",
|
||||
"feedback is welcome",
|
||||
];
|
||||
|
||||
/// Parse the inside of `[...]` as a reference.
|
||||
fn parse_ref(content: &str) -> Option<Ref> {
|
||||
let (app, fact) = content.split_once("#F")?;
|
||||
if !canon::is_valid_app_id(app) {
|
||||
return None;
|
||||
}
|
||||
Some(Ref {
|
||||
app: app.to_string(),
|
||||
fact: text::parse_id(fact)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn is_terminator(c: char) -> bool {
|
||||
matches!(c, '.' | '!' | '?' | '…' | '。' | '!' | '?')
|
||||
}
|
||||
|
||||
fn is_closer(c: char) -> bool {
|
||||
matches!(c, ')' | '"' | '\'' | '”' | '’' | '»' | '*' | '_')
|
||||
}
|
||||
|
||||
/// Sentence byte ranges (untrimmed; may be blank).
|
||||
fn split(text: &str, urls: &[FoundUrl]) -> Vec<(usize, usize)> {
|
||||
let chars: Vec<(usize, char)> = text.char_indices().collect();
|
||||
let n = chars.len();
|
||||
let mut in_url = vec![false; n];
|
||||
{
|
||||
let mut u = 0;
|
||||
for (k, &(pos, _)) in chars.iter().enumerate() {
|
||||
while u < urls.len() && urls[u].end <= pos {
|
||||
u += 1;
|
||||
}
|
||||
in_url[k] = u < urls.len() && urls[u].start <= pos && pos < urls[u].end;
|
||||
}
|
||||
}
|
||||
let pos_of = |k: usize| if k < n { chars[k].0 } else { text.len() };
|
||||
let mut out = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut k = 0;
|
||||
while k < n {
|
||||
let (pos, c) = chars[k];
|
||||
if in_url[k] {
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
if c == '\n' || c == '\r' {
|
||||
out.push((start, pos));
|
||||
start = pos + c.len_utf8();
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
if is_terminator(c) {
|
||||
let mut j = k + 1;
|
||||
while j < n && !in_url[j] && (is_terminator(chars[j].1) || is_closer(chars[j].1)) {
|
||||
j += 1;
|
||||
}
|
||||
// References right after the end mark belong to this sentence.
|
||||
loop {
|
||||
let mut m = j;
|
||||
while m < n && matches!(chars[m].1, ' ' | '\t') {
|
||||
m += 1;
|
||||
}
|
||||
match text::bracket_group(&chars, m) {
|
||||
Some((end, range)) if text::is_ref_like(&text[range.clone()]) => j = end,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
if j >= n || chars[j].1.is_whitespace() {
|
||||
let end = pos_of(j);
|
||||
out.push((start, end));
|
||||
start = end;
|
||||
k = j;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
out.push((start, text.len()));
|
||||
out
|
||||
}
|
||||
|
||||
struct Scan {
|
||||
refs: Vec<Ref>,
|
||||
malformed: Vec<String>,
|
||||
/// The sentence without references, malformed references and URLs.
|
||||
residual: String,
|
||||
}
|
||||
|
||||
fn scan(seg: &str, seg_start: usize, urls: &[FoundUrl]) -> Scan {
|
||||
let chars: Vec<(usize, char)> = seg.char_indices().collect();
|
||||
let n = chars.len();
|
||||
let mut refs = Vec::new();
|
||||
let mut malformed = Vec::new();
|
||||
let mut residual = String::with_capacity(seg.len());
|
||||
let mut k = 0;
|
||||
while k < n {
|
||||
let (pos, c) = chars[k];
|
||||
let abs = seg_start + pos;
|
||||
if let Some(u) = urls.iter().find(|u| u.start <= abs && abs < u.end) {
|
||||
residual.push(' ');
|
||||
while k < n && seg_start + chars[k].0 < u.end {
|
||||
k += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if c == '[' {
|
||||
if let Some((end, range)) = text::bracket_group(&chars, k) {
|
||||
let content = &seg[range];
|
||||
if let Some(r) = parse_ref(content) {
|
||||
refs.push(r);
|
||||
residual.push(' ');
|
||||
k = end;
|
||||
continue;
|
||||
}
|
||||
if text::is_ref_like(content) {
|
||||
malformed.push(format!("[{content}]"));
|
||||
residual.push(' ');
|
||||
k = end;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// An unclosed bracket: `[tabula#F1` up to the next whitespace.
|
||||
let run_end = chars[k..]
|
||||
.iter()
|
||||
.position(|&(_, c)| c.is_whitespace())
|
||||
.map_or(n, |p| k + p);
|
||||
let run = &seg[pos..pos_of(&chars, run_end, seg.len())];
|
||||
if run.contains('#') || text::is_ref_like(&run[1..]) {
|
||||
malformed.push(run.to_string());
|
||||
residual.push(' ');
|
||||
k = run_end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
residual.push(c);
|
||||
k += 1;
|
||||
}
|
||||
// A bare `app#F1` without brackets.
|
||||
for word in residual.split_whitespace() {
|
||||
let w = word.as_bytes();
|
||||
if w.windows(3)
|
||||
.any(|x| x[0] == b'#' && (x[1] == b'F' || x[1] == b'f') && x[2].is_ascii_digit())
|
||||
{
|
||||
malformed.push(word.to_string());
|
||||
}
|
||||
}
|
||||
Scan {
|
||||
refs,
|
||||
malformed,
|
||||
residual,
|
||||
}
|
||||
}
|
||||
|
||||
fn pos_of(chars: &[(usize, char)], k: usize, len: usize) -> usize {
|
||||
chars.get(k).map_or(len, |x| x.0)
|
||||
}
|
||||
|
||||
/// Lower case, letters, digits and apostrophes, single spaces.
|
||||
fn normalize(s: &str) -> String {
|
||||
let mapped: String = s
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'’' | '‘' | 'ʼ' | '`' => '\'',
|
||||
c if c.is_alphanumeric() || c == '\'' => c,
|
||||
_ => ' ',
|
||||
})
|
||||
.collect();
|
||||
let words: Vec<String> = mapped
|
||||
.split_whitespace()
|
||||
.map(|w| w.trim_matches('\'').to_lowercase())
|
||||
.filter(|w| !w.is_empty())
|
||||
.collect();
|
||||
words.join(" ")
|
||||
}
|
||||
|
||||
fn app_names(canon: &Canon) -> BTreeSet<String> {
|
||||
let mut names = BTreeSet::new();
|
||||
for f in canon.apps() {
|
||||
for n in [normalize(&f.front.name), normalize(&f.id)] {
|
||||
if !n.is_empty() && !n.chars().any(char::is_numeric) {
|
||||
names.insert(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
fn is_plain(norm: &str, names: &BTreeSet<String>) -> bool {
|
||||
PLAIN.iter().any(|p| match p.split_once("{app}") {
|
||||
None => *p == norm,
|
||||
Some((pre, post)) => norm
|
||||
.strip_prefix(pre)
|
||||
.and_then(|rest| rest.strip_suffix(post))
|
||||
.is_some_and(|mid| names.contains(mid)),
|
||||
})
|
||||
}
|
||||
|
||||
fn needs_ref(residual: &str, names: &BTreeSet<String>) -> bool {
|
||||
let norm = normalize(residual);
|
||||
!norm.is_empty() && !is_plain(&norm, names)
|
||||
}
|
||||
|
||||
/// Check generated text against the canon.
|
||||
pub fn check(text: &str, canon: &Canon) -> Report {
|
||||
let _ = (text, canon);
|
||||
todo!()
|
||||
let mut problems: Vec<Problem> = Vec::new();
|
||||
let mut seen: HashSet<Problem> = HashSet::new();
|
||||
let mut push = |p: Problem, problems: &mut Vec<Problem>| {
|
||||
if seen.insert(p.clone()) {
|
||||
problems.push(p);
|
||||
}
|
||||
};
|
||||
|
||||
for c in text.chars() {
|
||||
if c != '\r' && text::is_forbidden(c) {
|
||||
push(
|
||||
Problem::HiddenCharacter {
|
||||
codepoint: c as u32,
|
||||
},
|
||||
&mut problems,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let urls = text::find_urls(text);
|
||||
let allowed = canon.allowed_urls();
|
||||
for u in &urls {
|
||||
let s = u.as_str(text);
|
||||
if !text::url_allowed(s, u.kind, &allowed) {
|
||||
push(Problem::UrlNotInCanon { url: s.to_string() }, &mut problems);
|
||||
}
|
||||
}
|
||||
|
||||
let names = app_names(canon);
|
||||
let mut all_refs: BTreeSet<Ref> = BTreeSet::new();
|
||||
for (s, e) in split(text, &urls) {
|
||||
let seg = &text[s..e];
|
||||
let first = urls.partition_point(|u| u.end <= s);
|
||||
let last = urls.partition_point(|u| u.start < e);
|
||||
let sc = scan(seg, s, &urls[first..last.max(first)]);
|
||||
for m in sc.malformed {
|
||||
push(Problem::MalformedRef { text: m }, &mut problems);
|
||||
}
|
||||
for r in &sc.refs {
|
||||
let p = match canon.get(&r.app) {
|
||||
None => Some(Problem::UnknownApp { r: r.clone() }),
|
||||
Some(f) => match f.fact(r.fact) {
|
||||
None => Some(Problem::MissingFact { r: r.clone() }),
|
||||
Some(fact) if fact.assumption => Some(Problem::Unconfirmed { r: r.clone() }),
|
||||
Some(_) => None,
|
||||
},
|
||||
};
|
||||
if let Some(p) = p {
|
||||
push(p, &mut problems);
|
||||
}
|
||||
}
|
||||
if sc.refs.is_empty() && needs_ref(&sc.residual, &names) {
|
||||
push(
|
||||
Problem::Unsourced {
|
||||
sentence: seg.trim().to_string(),
|
||||
},
|
||||
&mut problems,
|
||||
);
|
||||
}
|
||||
all_refs.extend(sc.refs);
|
||||
}
|
||||
Report {
|
||||
refs: all_refs.into_iter().collect(),
|
||||
problems,
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove every well-formed `[app#Fn]` reference (and the spaces before it), for display and posting.
|
||||
/// Malformed references are left in place.
|
||||
pub fn strip_refs(text: &str) -> String {
|
||||
let _ = text;
|
||||
todo!()
|
||||
let chars: Vec<(usize, char)> = text.char_indices().collect();
|
||||
let n = chars.len();
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut k = 0;
|
||||
while k < n {
|
||||
let c = chars[k].1;
|
||||
if c == '[' {
|
||||
if let Some((end, range)) = text::bracket_group(&chars, k) {
|
||||
if parse_ref(&text[range]).is_some() {
|
||||
while out.ends_with([' ', '\t']) {
|
||||
out.pop();
|
||||
}
|
||||
k = end;
|
||||
let next_alnum = chars.get(k).is_some_and(|x| x.1.is_alphanumeric());
|
||||
let prev_space = out.chars().last().is_none_or(char::is_whitespace);
|
||||
if next_alnum && !prev_space {
|
||||
out.push(' ');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(c);
|
||||
k += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Split text into sentences the way [`check`] does.
|
||||
/// Split text into sentences the way [`check`] does (trimmed, blank ones left out).
|
||||
pub fn sentences(text: &str) -> Vec<String> {
|
||||
let _ = text;
|
||||
todo!()
|
||||
let urls = text::find_urls(text);
|
||||
split(text, &urls)
|
||||
.into_iter()
|
||||
.map(|(s, e)| text[s..e].trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether [`check`] treats this sentence (without its references) as stating a fact. Fail closed.
|
||||
pub fn states_fact(sentence: &str, canon: &Canon) -> bool {
|
||||
let _ = (sentence, canon);
|
||||
todo!()
|
||||
let urls = text::find_urls(sentence);
|
||||
let sc = scan(sentence, 0, &urls);
|
||||
needs_ref(&sc.residual, &app_names(canon))
|
||||
}
|
||||
|
||||
@@ -3,12 +3,17 @@
|
||||
|
||||
//! Hook templates: `brand/hooks.md` lines `- [H<n>] <template>` with slots from a fixed set.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use crate::text::{self, ItemLine, LineError};
|
||||
|
||||
/// The only slot names a template may use.
|
||||
pub const SLOTS: [&str; 7] = ["app", "feature", "pain", "number", "platform", "clicks", "audience"];
|
||||
pub const SLOTS: [&str; 7] = [
|
||||
"app", "feature", "pain", "number", "platform", "clicks", "audience",
|
||||
];
|
||||
|
||||
/// Largest hooks file accepted, in bytes.
|
||||
pub const MAX_FILE_BYTES: usize = 64 * 1024;
|
||||
@@ -44,13 +49,64 @@ pub struct Genome {
|
||||
pub lead_verb: Option<String>,
|
||||
}
|
||||
|
||||
/// Imperative openers recognised as commands.
|
||||
const COMMAND_VERBS: &[&str] = &[
|
||||
"ask", "build", "check", "discover", "ditch", "do", "don't", "dont", "download", "find",
|
||||
"forget", "get", "give", "grab", "imagine", "install", "join", "keep", "learn", "let", "make",
|
||||
"meet", "never", "open", "picture", "plan", "quit", "read", "save", "say", "see", "skip",
|
||||
"start", "stop", "switch", "take", "track", "try", "turn", "use", "watch", "write",
|
||||
];
|
||||
|
||||
impl Genome {
|
||||
/// Derive the genome from a template or a filled hook.
|
||||
///
|
||||
/// Opening, in this order: starts with a digit or `{number}` → number; first sentence ends with `?` →
|
||||
/// question; first word is a known imperative verb → command; otherwise statement.
|
||||
pub fn of(text: &str) -> Genome {
|
||||
let _ = text;
|
||||
todo!()
|
||||
let words: Vec<&str> = text.unicode_words().collect();
|
||||
let has_number = text.chars().any(char::is_numeric) || text.contains("{number}");
|
||||
let lead = text
|
||||
.trim_start()
|
||||
.trim_start_matches(|c: char| !c.is_alphanumeric() && c != '{');
|
||||
let first_word = words.first().map(|w| w.to_lowercase().replace('’', "'"));
|
||||
let opening = if lead.starts_with(|c: char| c.is_numeric()) || lead.starts_with("{number}")
|
||||
{
|
||||
Opening::Number
|
||||
} else if first_sentence_is_question(text) {
|
||||
Opening::Question
|
||||
} else if first_word
|
||||
.as_deref()
|
||||
.is_some_and(|w| COMMAND_VERBS.contains(&w))
|
||||
&& !lead.starts_with('{')
|
||||
{
|
||||
Opening::Command
|
||||
} else {
|
||||
Opening::Statement
|
||||
};
|
||||
let lead_verb = if opening == Opening::Command {
|
||||
first_word
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Genome {
|
||||
opening,
|
||||
words: words.len(),
|
||||
has_number,
|
||||
lead_verb,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn first_sentence_is_question(text: &str) -> bool {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
if matches!(c, '.' | '!' | '?' | '…') && chars.get(i + 1).is_none_or(|n| n.is_whitespace())
|
||||
{
|
||||
return c == '?';
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A hooks file error.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
@@ -58,8 +114,12 @@ impl Genome {
|
||||
pub enum HookError {
|
||||
#[error("the file is {bytes} bytes; the limit is 65536")]
|
||||
TooLarge { bytes: usize },
|
||||
#[error("line {line}: forbidden character U+{codepoint:04X} (control, hidden or direction-changing)")]
|
||||
#[error(
|
||||
"line {line}: forbidden character U+{codepoint:04X} (control, hidden or direction-changing)"
|
||||
)]
|
||||
ForbiddenCharacter { line: usize, codepoint: u32 },
|
||||
#[error("line {line}: a carriage return that is not part of a CRLF line ending")]
|
||||
LoneCarriageReturn { line: usize },
|
||||
#[error("line {line}: a line starting '- [H' must be '- [H<n>] <template>'")]
|
||||
Malformed { line: usize },
|
||||
#[error("line {line}: hook number must be 1-9999 without leading zeros")]
|
||||
@@ -76,16 +136,100 @@ pub enum HookError {
|
||||
MissingValue { slot: String },
|
||||
}
|
||||
|
||||
/// The slots of a template, unique, in order of first use.
|
||||
fn slots_of(template: &str, line: usize) -> Result<Vec<String>, HookError> {
|
||||
let mut slots: Vec<String> = Vec::new();
|
||||
let mut rest = template;
|
||||
while let Some(i) = rest.find(['{', '}']) {
|
||||
if rest[i..].starts_with('}') {
|
||||
return Err(HookError::UnbalancedBrace { line });
|
||||
}
|
||||
let after = &rest[i + 1..];
|
||||
let Some(j) = after.find(['{', '}']) else {
|
||||
return Err(HookError::UnbalancedBrace { line });
|
||||
};
|
||||
if after[j..].starts_with('{') {
|
||||
return Err(HookError::UnbalancedBrace { line });
|
||||
}
|
||||
let name = &after[..j];
|
||||
if !SLOTS.contains(&name) {
|
||||
return Err(HookError::UnknownSlot {
|
||||
line,
|
||||
slot: name.to_string(),
|
||||
});
|
||||
}
|
||||
if !slots.iter().any(|s| s == name) {
|
||||
slots.push(name.to_string());
|
||||
}
|
||||
rest = &after[j + 1..];
|
||||
}
|
||||
Ok(slots)
|
||||
}
|
||||
|
||||
/// Parse `brand/hooks.md`. Lines that do not start `- [H` are ignored (headings, prose).
|
||||
///
|
||||
/// Strict like the canon: a bullet line starting `[H` must be exactly `- [H<n>] <template>`; a leading BOM and CRLF
|
||||
/// are tolerated; control, hidden and direction-changing characters are errors; 64 KiB at most.
|
||||
pub fn parse(md: &str) -> Result<Vec<HookTemplate>, HookError> {
|
||||
let _ = md;
|
||||
todo!()
|
||||
if md.len() > MAX_FILE_BYTES {
|
||||
return Err(HookError::TooLarge { bytes: md.len() });
|
||||
}
|
||||
let lines = text::clean_lines(md).map_err(|(line, e)| match e {
|
||||
LineError::LoneCr => HookError::LoneCarriageReturn { line },
|
||||
LineError::Forbidden(codepoint) => HookError::ForbiddenCharacter { line, codepoint },
|
||||
})?;
|
||||
let mut out = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for (i, &l) in lines.iter().enumerate() {
|
||||
let line = i + 1;
|
||||
match text::item_line(l, 'H') {
|
||||
ItemLine::No => {}
|
||||
ItemLine::Malformed => return Err(HookError::Malformed { line }),
|
||||
ItemLine::IdOutOfRange => return Err(HookError::IdOutOfRange { line }),
|
||||
ItemLine::Item { id, text } => {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Err(HookError::Empty { line });
|
||||
}
|
||||
let id = format!("H{id}");
|
||||
if !seen.insert(id.clone()) {
|
||||
return Err(HookError::Duplicate { line, id });
|
||||
}
|
||||
let slots = slots_of(text, line)?;
|
||||
out.push(HookTemplate {
|
||||
id,
|
||||
text: text.to_string(),
|
||||
slots,
|
||||
genome: Genome::of(text),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl HookTemplate {
|
||||
/// Fill every slot. A missing value is an error; braces inside values are not expanded again.
|
||||
/// Extra values are ignored.
|
||||
pub fn fill(&self, values: &BTreeMap<String, String>) -> Result<String, HookError> {
|
||||
let _ = values;
|
||||
todo!()
|
||||
let mut out = String::with_capacity(self.text.len() + 32);
|
||||
let mut rest = self.text.as_str();
|
||||
while let Some(i) = rest.find('{') {
|
||||
out.push_str(&rest[..i]);
|
||||
let after = &rest[i + 1..];
|
||||
// Templates are validated at parse time; a hand-built one with a stray brace keeps it literally.
|
||||
let Some(j) = after.find('}') else {
|
||||
out.push_str(&rest[i..]);
|
||||
return Ok(out);
|
||||
};
|
||||
let name = &after[..j];
|
||||
let value = values.get(name).ok_or_else(|| HookError::MissingValue {
|
||||
slot: name.to_string(),
|
||||
})?;
|
||||
out.push_str(value);
|
||||
rest = &after[j + 1..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,299 @@
|
||||
// SPDX-License-Identifier: CPAL-1.0
|
||||
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
|
||||
|
||||
//! Shared text scanning: forbidden characters, URLs, line splitting.
|
||||
//! Shared text scanning: forbidden characters, line splitting, URLs, claim references.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Control, hidden and direction-changing characters. `\n` and `\t` are fine; `\r` is handled by callers.
|
||||
pub(crate) fn is_forbidden(c: char) -> bool {
|
||||
match c {
|
||||
'\n' | '\t' => false,
|
||||
c if c.is_control() => true,
|
||||
'\u{061C}'
|
||||
| '\u{200B}'
|
||||
| '\u{200E}'
|
||||
| '\u{200F}'
|
||||
| '\u{202A}'..='\u{202E}'
|
||||
| '\u{2060}'..='\u{2064}'
|
||||
| '\u{2066}'..='\u{2069}'
|
||||
| '\u{FEFF}'
|
||||
| '\u{FFF9}'..='\u{FFFB}'
|
||||
| '\u{E0000}'..='\u{E007F}' => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum LineError {
|
||||
LoneCr,
|
||||
Forbidden(u32),
|
||||
}
|
||||
|
||||
/// Split a file into lines. A leading BOM is dropped and CRLF counts as LF; a lone CR or a forbidden
|
||||
/// character is an error with its 1-based line number.
|
||||
pub(crate) fn clean_lines(text: &str) -> Result<Vec<&str>, (usize, LineError)> {
|
||||
let text = text.strip_prefix('\u{FEFF}').unwrap_or(text);
|
||||
let mut out = Vec::new();
|
||||
for (i, raw) in text.split('\n').enumerate() {
|
||||
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
if line.contains('\r') {
|
||||
return Err((i + 1, LineError::LoneCr));
|
||||
}
|
||||
if let Some(c) = line.chars().find(|&c| is_forbidden(c)) {
|
||||
return Err((i + 1, LineError::Forbidden(c as u32)));
|
||||
}
|
||||
out.push(line);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Parse the number of a `[F<n>]` / `[H<n>]` id: 1-9999, ASCII digits, no leading zeros.
|
||||
pub(crate) fn parse_id(digits: &str) -> Option<u32> {
|
||||
if digits.is_empty()
|
||||
|| digits.len() > 4
|
||||
|| digits.starts_with('0')
|
||||
|| !digits.bytes().all(|b| b.is_ascii_digit())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
digits.parse().ok()
|
||||
}
|
||||
|
||||
/// How a strict `- [X<n>] <text>` line parsed.
|
||||
pub(crate) enum ItemLine<'a> {
|
||||
/// Not an item line of this kind.
|
||||
No,
|
||||
Malformed,
|
||||
IdOutOfRange,
|
||||
Item {
|
||||
id: u32,
|
||||
text: &'a str,
|
||||
},
|
||||
}
|
||||
|
||||
/// Parse a `- [<letter><n>] <text>` line strictly. Any bullet line whose content starts `[<letter>` (any case,
|
||||
/// any indentation, any bullet) counts as an attempt and must match exactly.
|
||||
pub(crate) fn item_line(line: &str, letter: char) -> ItemLine<'_> {
|
||||
let t = line.trim_start();
|
||||
let Some(rest) = t.strip_prefix(['-', '*', '+']) else {
|
||||
return ItemLine::No;
|
||||
};
|
||||
let rest = rest.trim_start();
|
||||
let mut cs = rest.chars();
|
||||
if cs.next() != Some('[') || !cs.next().is_some_and(|c| c.eq_ignore_ascii_case(&letter)) {
|
||||
return ItemLine::No;
|
||||
}
|
||||
let prefix = format!("- [{letter}");
|
||||
let Some(rest) = line.strip_prefix(prefix.as_str()) else {
|
||||
return ItemLine::Malformed;
|
||||
};
|
||||
let digits_len = rest.bytes().take_while(u8::is_ascii_digit).count();
|
||||
let (digits, rest) = rest.split_at(digits_len);
|
||||
if digits.is_empty() {
|
||||
return ItemLine::Malformed;
|
||||
}
|
||||
let Some(text) = rest.strip_prefix("] ") else {
|
||||
return ItemLine::Malformed;
|
||||
};
|
||||
match parse_id(digits) {
|
||||
Some(id) => ItemLine::Item { id, text },
|
||||
None => ItemLine::IdOutOfRange,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum UrlKind {
|
||||
/// `scheme://...`
|
||||
Scheme,
|
||||
/// `www.example.com...` without a scheme.
|
||||
Www,
|
||||
/// `example.com/...` or `example.com` with a common top-level domain.
|
||||
Bare,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct FoundUrl {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub kind: UrlKind,
|
||||
}
|
||||
|
||||
impl FoundUrl {
|
||||
pub fn as_str<'a>(&self, text: &'a str) -> &'a str {
|
||||
&text[self.start..self.end]
|
||||
}
|
||||
}
|
||||
|
||||
fn is_url_stop(c: char) -> bool {
|
||||
c.is_whitespace()
|
||||
|| matches!(
|
||||
c,
|
||||
'<' | '>'
|
||||
| '"'
|
||||
| '\''
|
||||
| '['
|
||||
| ']'
|
||||
| '{'
|
||||
| '}'
|
||||
| '|'
|
||||
| '\\'
|
||||
| '^'
|
||||
| '`'
|
||||
| '('
|
||||
| ')'
|
||||
| '“'
|
||||
| '”'
|
||||
| '‘'
|
||||
| '’'
|
||||
| '«'
|
||||
| '»'
|
||||
)
|
||||
}
|
||||
|
||||
fn is_edge_punct(c: char) -> bool {
|
||||
matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | '*' | '_' | '~' | '…')
|
||||
}
|
||||
|
||||
const COMMON_TLDS: &[&str] = &[
|
||||
"com", "net", "org", "io", "dev", "app", "cz", "sk", "de", "eu", "uk", "us", "me", "co", "ai",
|
||||
"gg", "tv", "xyz", "info", "biz", "page", "site", "online", "tech", "store", "blog", "fr",
|
||||
"nl", "pl", "at", "ch", "it", "es", "ru", "cn", "jp", "ly", "to", "sh", "so", "gl", "im", "fm",
|
||||
"ws", "link", "click", "live", "cloud", "news", "shop", "social", "gov", "edu",
|
||||
];
|
||||
|
||||
fn looks_like_host(host: &str) -> Option<&str> {
|
||||
let host = host.rsplit('@').next().unwrap_or(host);
|
||||
let labels: Vec<&str> = host.split('.').collect();
|
||||
if labels.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
if !labels
|
||||
.iter()
|
||||
.all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let tld = labels[labels.len() - 1];
|
||||
if tld.len() < 2 || tld.len() > 24 || !tld.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||
return None;
|
||||
}
|
||||
Some(tld)
|
||||
}
|
||||
|
||||
/// Find URLs: any `scheme://`, any `www.` token, and bare `host.tld/path` or `host.<common tld>` tokens.
|
||||
/// Trailing sentence punctuation is not part of a URL.
|
||||
pub(crate) fn find_urls(text: &str) -> Vec<FoundUrl> {
|
||||
let mut out = Vec::new();
|
||||
let mut tok_start: Option<usize> = None;
|
||||
let handle = |s: usize, e: usize, out: &mut Vec<FoundUrl>| {
|
||||
let tok = &text[s..e];
|
||||
// Trim edge punctuation.
|
||||
let lead = tok.len() - tok.trim_start_matches(is_edge_punct).len();
|
||||
let trimmed = tok
|
||||
.trim_start_matches(is_edge_punct)
|
||||
.trim_end_matches(is_edge_punct);
|
||||
if trimmed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (s, e) = (s + lead, s + lead + trimmed.len());
|
||||
if let Some(p) = trimmed.find("://") {
|
||||
let scheme_start = trimmed[..p]
|
||||
.char_indices()
|
||||
.rev()
|
||||
.take_while(|&(_, c)| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))
|
||||
.last()
|
||||
.map_or(p, |(i, _)| i);
|
||||
out.push(FoundUrl {
|
||||
start: s + scheme_start,
|
||||
end: e,
|
||||
kind: UrlKind::Scheme,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if trimmed.len() >= 4
|
||||
&& trimmed.is_char_boundary(4)
|
||||
&& trimmed[..4].eq_ignore_ascii_case("www.")
|
||||
{
|
||||
out.push(FoundUrl {
|
||||
start: s,
|
||||
end: e,
|
||||
kind: UrlKind::Www,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let (host, has_path) = match trimmed.find('/') {
|
||||
Some(i) => (&trimmed[..i], true),
|
||||
None => (trimmed, false),
|
||||
};
|
||||
if let Some(tld) = looks_like_host(host) {
|
||||
if has_path || COMMON_TLDS.contains(&tld.to_ascii_lowercase().as_str()) {
|
||||
out.push(FoundUrl {
|
||||
start: s,
|
||||
end: e,
|
||||
kind: UrlKind::Bare,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
for (i, c) in text.char_indices() {
|
||||
if is_url_stop(c) {
|
||||
if let Some(s) = tok_start.take() {
|
||||
handle(s, i, &mut out);
|
||||
}
|
||||
} else if tok_start.is_none() {
|
||||
tok_start = Some(i);
|
||||
}
|
||||
}
|
||||
if let Some(s) = tok_start {
|
||||
handle(s, text.len(), &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn toggle_slash(u: &str) -> String {
|
||||
match u.strip_suffix('/') {
|
||||
Some(x) => x.to_string(),
|
||||
None => format!("{u}/"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a found URL is one of the allowed ones (a trailing `/` does not matter; bare forms are read as https).
|
||||
pub(crate) fn url_allowed(url: &str, kind: UrlKind, allowed: &BTreeSet<String>) -> bool {
|
||||
let full = match kind {
|
||||
UrlKind::Scheme => url.to_string(),
|
||||
UrlKind::Www | UrlKind::Bare => format!("https://{url}"),
|
||||
};
|
||||
allowed.contains(&full) || allowed.contains(&toggle_slash(&full))
|
||||
}
|
||||
|
||||
/// If `chars[at]` is `[` and a `]` follows on the same line within 64 characters with no `[` in between,
|
||||
/// the index just after the `]` and the content between the brackets.
|
||||
pub(crate) fn bracket_group(
|
||||
chars: &[(usize, char)],
|
||||
at: usize,
|
||||
) -> Option<(usize, std::ops::Range<usize>)> {
|
||||
if chars.get(at).map(|x| x.1) != Some('[') {
|
||||
return None;
|
||||
}
|
||||
let content_start = chars[at].0 + 1;
|
||||
for (j, &(pos, c)) in chars.iter().enumerate().take(at + 66).skip(at + 1) {
|
||||
match c {
|
||||
']' => return Some((j + 1, content_start..pos)),
|
||||
'[' | '\n' | '\r' => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Content of a bracket group that is meant as a claim reference (well-formed or not).
|
||||
pub(crate) fn is_ref_like(content: &str) -> bool {
|
||||
if content.contains('#') {
|
||||
return true;
|
||||
}
|
||||
let mut cs = content.chars();
|
||||
matches!(cs.next(), Some('F' | 'f')) && {
|
||||
let rest = cs.as_str().trim();
|
||||
!rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,13 +49,19 @@ fn parses_the_sample_file() {
|
||||
assert_eq!(f.id, "tabula");
|
||||
assert_eq!(f.front.name, "Tabula");
|
||||
assert_eq!(f.front.one_liner, "Notes that stay on your own computer.");
|
||||
assert_eq!(f.front.audience, "People who want notes without an account.");
|
||||
assert_eq!(
|
||||
f.front.audience,
|
||||
"People who want notes without an account."
|
||||
);
|
||||
assert_eq!(f.front.price, "(assumption) one-time purchase");
|
||||
assert!(canon::is_assumption_value(&f.front.price));
|
||||
assert!(!canon::is_assumption_value(&f.front.name));
|
||||
assert_eq!(f.front.clicks, "New note in 1 click.");
|
||||
assert_eq!(f.front.status, Status::Released);
|
||||
assert_eq!(f.front.aula.as_deref(), Some("https://aula.marek-novak.cz/tabula/"));
|
||||
assert_eq!(
|
||||
f.front.aula.as_deref(),
|
||||
Some("https://aula.marek-novak.cz/tabula/")
|
||||
);
|
||||
assert_eq!(f.front.site, None);
|
||||
assert_eq!(f.facts.len(), 3);
|
||||
let f1 = f.fact(1).unwrap();
|
||||
@@ -63,7 +69,10 @@ fn parses_the_sample_file() {
|
||||
assert!(!f1.assumption);
|
||||
assert_eq!(f1.line, 16);
|
||||
let f2 = f.fact(2).unwrap();
|
||||
assert_eq!(f2.text, "It syncs between your devices without a cloud account.");
|
||||
assert_eq!(
|
||||
f2.text,
|
||||
"It syncs between your devices without a cloud account."
|
||||
);
|
||||
assert!(f2.assumption);
|
||||
assert_eq!(f2.line, 17);
|
||||
assert!(f.fact(4).is_none());
|
||||
@@ -84,14 +93,21 @@ fn urls_are_front_matter_plus_https_in_facts() {
|
||||
|
||||
#[test]
|
||||
fn http_urls_in_facts_are_not_allowed() {
|
||||
let text = with_front(FRONT, "- [F1] See http://example.com/x and https://example.com/y.\n");
|
||||
let text = with_front(
|
||||
FRONT,
|
||||
"- [F1] See http://example.com/x and https://example.com/y.\n",
|
||||
);
|
||||
let f = canon::parse("tabula", &text).unwrap();
|
||||
assert_eq!(f.urls(), vec!["https://example.com/y".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn site_and_status_values() {
|
||||
for (s, st) in [("released", Status::Released), ("beta", Status::Beta), ("planned", Status::Planned)] {
|
||||
for (s, st) in [
|
||||
("released", Status::Released),
|
||||
("beta", Status::Beta),
|
||||
("planned", Status::Planned),
|
||||
] {
|
||||
let front = FRONT.replace("status: beta", &format!("status: {s}"));
|
||||
let text = with_front(&format!("{front}site: https://tabula.example/\n"), "");
|
||||
let f = canon::parse("tabula", &text).unwrap();
|
||||
@@ -104,30 +120,56 @@ fn site_and_status_values() {
|
||||
#[test]
|
||||
fn rejects_bad_status() {
|
||||
let front = FRONT.replace("status: beta", "status: Released");
|
||||
assert_eq!(code("tabula", &with_front(&front, "")), (8, CanonCode::BadStatus("Released".into())));
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")),
|
||||
(8, CanonCode::BadStatus("Released".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_unknown_duplicate_and_empty_keys() {
|
||||
let front = FRONT.replace("price: free\n", "");
|
||||
assert_eq!(code("tabula", &with_front(&front, "")).1, CanonCode::MissingKey("price".into()));
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")).1,
|
||||
CanonCode::MissingKey("price".into())
|
||||
);
|
||||
|
||||
let front = format!("{FRONT}colour: brass\n");
|
||||
assert_eq!(code("tabula", &with_front(&front, "")), (9, CanonCode::UnknownKey("colour".into())));
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")),
|
||||
(9, CanonCode::UnknownKey("colour".into()))
|
||||
);
|
||||
|
||||
let front = format!("{FRONT}name: Other\n");
|
||||
assert_eq!(code("tabula", &with_front(&front, "")), (9, CanonCode::DuplicateKey("name".into())));
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")),
|
||||
(9, CanonCode::DuplicateKey("name".into()))
|
||||
);
|
||||
|
||||
let front = FRONT.replace("price: free", "price:");
|
||||
assert_eq!(code("tabula", &with_front(&front, "")).1, CanonCode::EmptyValue("price".into()));
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")).1,
|
||||
CanonCode::EmptyValue("price".into())
|
||||
);
|
||||
|
||||
let front = FRONT.replace("price: free", "price: ");
|
||||
assert_eq!(code("tabula", &with_front(&front, "")).1, CanonCode::EmptyValue("price".into()));
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")).1,
|
||||
CanonCode::EmptyValue("price".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_flat_front_matter() {
|
||||
for bad in ["just text", " indented: yes", "list:\n - a", "", "# comment", "Name: Tabula", "key:value"] {
|
||||
for bad in [
|
||||
"just text",
|
||||
" indented: yes",
|
||||
"list:\n - a",
|
||||
"",
|
||||
"# comment",
|
||||
"Name: Tabula",
|
||||
"key:value",
|
||||
] {
|
||||
let front = format!("{FRONT}{bad}\n");
|
||||
let (line, c) = code("tabula", &with_front(&front, ""));
|
||||
assert_eq!(line, 9, "{bad:?}");
|
||||
@@ -140,19 +182,38 @@ fn rejects_non_flat_front_matter() {
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_or_unclosed_front_matter() {
|
||||
assert_eq!(code("tabula", "# Tabula\n- [F1] x\n"), (1, CanonCode::NoFrontMatter));
|
||||
assert_eq!(
|
||||
code("tabula", "# Tabula\n- [F1] x\n"),
|
||||
(1, CanonCode::NoFrontMatter)
|
||||
);
|
||||
assert_eq!(code("tabula", ""), (1, CanonCode::NoFrontMatter));
|
||||
assert_eq!(code("tabula", " ---\n"), (1, CanonCode::NoFrontMatter));
|
||||
assert_eq!(code("tabula", &format!("---\n{FRONT}")).1, CanonCode::UnclosedFrontMatter);
|
||||
assert_eq!(
|
||||
code("tabula", &format!("---\n{FRONT}")).1,
|
||||
CanonCode::UnclosedFrontMatter
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id_must_match_stem_and_be_valid() {
|
||||
assert_eq!(
|
||||
code("other", &with_front(FRONT, "")),
|
||||
(1, CanonCode::IdMismatch { id: "tabula".into(), stem: "other".into() })
|
||||
(
|
||||
2,
|
||||
CanonCode::IdMismatch {
|
||||
id: "tabula".into(),
|
||||
stem: "other".into()
|
||||
}
|
||||
)
|
||||
);
|
||||
for bad in ["Tabula", "-tabula", "tabula-", "tab_ula", "tab ula", "a234567890123456789012345678901234"] {
|
||||
for bad in [
|
||||
"Tabula",
|
||||
"-tabula",
|
||||
"tabula-",
|
||||
"tab_ula",
|
||||
"tab ula",
|
||||
"a234567890123456789012345678901234",
|
||||
] {
|
||||
let front = FRONT.replace("id: tabula", &format!("id: {bad}"));
|
||||
let c = code(bad, &with_front(&front, "")).1;
|
||||
assert_eq!(c, CanonCode::BadId(bad.trim().into()), "{bad:?}");
|
||||
@@ -167,9 +228,18 @@ fn id_must_match_stem_and_be_valid() {
|
||||
|
||||
#[test]
|
||||
fn urls_in_front_matter_must_be_https() {
|
||||
for bad in ["http://aula.example/", "aula.example", "https://a b", "https://"] {
|
||||
for bad in [
|
||||
"http://aula.example/",
|
||||
"aula.example",
|
||||
"https://a b",
|
||||
"https://",
|
||||
] {
|
||||
let text = with_front(&format!("{FRONT}aula: {bad}\n"), "");
|
||||
assert_eq!(code("tabula", &text).1, CanonCode::BadUrl(bad.into()), "{bad:?}");
|
||||
assert_eq!(
|
||||
code("tabula", &text).1,
|
||||
CanonCode::BadUrl(bad.into()),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +260,7 @@ fn rejects_malformed_fact_lines() {
|
||||
] {
|
||||
let text = with_front(FRONT, &format!("\n{bad}\n"));
|
||||
let (line, c) = code("tabula", &text);
|
||||
assert_eq!(line, 10, "{bad:?}");
|
||||
assert_eq!(line, 11, "{bad:?}");
|
||||
assert!(
|
||||
matches!(c, CanonCode::MalformedFact | CanonCode::EmptyFact),
|
||||
"{bad:?} gave {c:?}"
|
||||
@@ -202,21 +272,33 @@ fn rejects_malformed_fact_lines() {
|
||||
fn fact_ids_in_range_without_leading_zeros() {
|
||||
let ok = with_front(FRONT, "- [F1] a\n- [F9999] b\n");
|
||||
let f = canon::parse("tabula", &ok).unwrap();
|
||||
assert_eq!(f.facts.iter().map(|x| x.id).collect::<Vec<_>>(), vec![1, 9999]);
|
||||
for bad in ["- [F0] zero", "- [F10000] big", "- [F01] lead", "- [F99999999999999999999] huge"] {
|
||||
assert_eq!(
|
||||
f.facts.iter().map(|x| x.id).collect::<Vec<_>>(),
|
||||
vec![1, 9999]
|
||||
);
|
||||
for bad in [
|
||||
"- [F0] zero",
|
||||
"- [F10000] big",
|
||||
"- [F01] lead",
|
||||
"- [F99999999999999999999] huge",
|
||||
] {
|
||||
let text = with_front(FRONT, &format!("{bad}\n"));
|
||||
assert_eq!(code("tabula", &text), (9, CanonCode::FactIdOutOfRange), "{bad:?}");
|
||||
assert_eq!(
|
||||
code("tabula", &text),
|
||||
(10, CanonCode::FactIdOutOfRange),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_facts_and_empty_facts() {
|
||||
let text = with_front(FRONT, "- [F1] a\n## Limits\n- [F1] b\n");
|
||||
assert_eq!(code("tabula", &text), (11, CanonCode::DuplicateFact(1)));
|
||||
assert_eq!(code("tabula", &text), (12, CanonCode::DuplicateFact(1)));
|
||||
let text = with_front(FRONT, "- [F1] \n");
|
||||
assert_eq!(code("tabula", &text), (9, CanonCode::EmptyFact));
|
||||
assert_eq!(code("tabula", &text), (10, CanonCode::EmptyFact));
|
||||
let text = with_front(FRONT, "- [F1] (assumption)\n");
|
||||
assert_eq!(code("tabula", &text), (9, CanonCode::EmptyFact));
|
||||
assert_eq!(code("tabula", &text), (10, CanonCode::EmptyFact));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -227,7 +309,11 @@ fn assumption_marker() {
|
||||
- [F4] Inside (assumption) the text.\n- [F5] Trailing spaces (assumption) \n",
|
||||
);
|
||||
let f = canon::parse("tabula", &text).unwrap();
|
||||
let got: Vec<(&str, bool)> = f.facts.iter().map(|x| (x.text.as_str(), x.assumption)).collect();
|
||||
let got: Vec<(&str, bool)> = f
|
||||
.facts
|
||||
.iter()
|
||||
.map(|x| (x.text.as_str(), x.assumption))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
vec![
|
||||
@@ -242,7 +328,10 @@ fn assumption_marker() {
|
||||
|
||||
#[test]
|
||||
fn other_body_lines_are_ignored() {
|
||||
let text = with_front(FRONT, "# T\n\nSome prose [F7] here.\n- plain bullet\n> - [F9] quoted\n- [F1] fact\n");
|
||||
let text = with_front(
|
||||
FRONT,
|
||||
"# T\n\nSome prose [F7] here.\n- plain bullet\n> - [F9] quoted\n- [F1] fact\n",
|
||||
);
|
||||
let f = canon::parse("tabula", &text).unwrap();
|
||||
assert_eq!(f.facts.len(), 1);
|
||||
}
|
||||
@@ -256,17 +345,31 @@ fn size_limit_is_64_kib() {
|
||||
assert_eq!(text.len(), canon::MAX_FILE_BYTES);
|
||||
assert!(canon::parse("tabula", &text).is_ok());
|
||||
text.push('\n');
|
||||
assert_eq!(code("tabula", &text), (0, CanonCode::TooLarge { bytes: canon::MAX_FILE_BYTES + 1 }));
|
||||
assert_eq!(
|
||||
code("tabula", &text),
|
||||
(
|
||||
0,
|
||||
CanonCode::TooLarge {
|
||||
bytes: canon::MAX_FILE_BYTES + 1
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_line_is_fine_under_the_limit_and_rejected_over_it() {
|
||||
let long = "a".repeat(60 * 1024);
|
||||
let text = with_front(FRONT, &format!("- [F1] {long}\n"));
|
||||
assert_eq!(canon::parse("tabula", &text).unwrap().facts[0].text.len(), long.len());
|
||||
assert_eq!(
|
||||
canon::parse("tabula", &text).unwrap().facts[0].text.len(),
|
||||
long.len()
|
||||
);
|
||||
let long = "a".repeat(70 * 1024);
|
||||
let text = with_front(FRONT, &format!("- [F1] {long}\n"));
|
||||
assert!(matches!(code("tabula", &text).1, CanonCode::TooLarge { .. }));
|
||||
assert!(matches!(
|
||||
code("tabula", &text).1,
|
||||
CanonCode::TooLarge { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -282,7 +385,7 @@ fn bom_and_crlf_are_tolerated() {
|
||||
#[test]
|
||||
fn lone_cr_nul_and_hidden_characters_are_rejected() {
|
||||
let text = with_front(FRONT, "- [F1] a\rb\n");
|
||||
assert_eq!(code("tabula", &text), (9, CanonCode::LoneCarriageReturn));
|
||||
assert_eq!(code("tabula", &text), (10, CanonCode::LoneCarriageReturn));
|
||||
for (ch, cp) in [
|
||||
('\0', 0u32),
|
||||
('\u{7}', 7),
|
||||
@@ -297,11 +400,18 @@ fn lone_cr_nul_and_hidden_characters_are_rejected() {
|
||||
('\u{e0041}', 0xe0041),
|
||||
] {
|
||||
let text = with_front(FRONT, &format!("- [F1] a{ch}b\n"));
|
||||
assert_eq!(code("tabula", &text), (9, CanonCode::ForbiddenCharacter { codepoint: cp }), "{cp:X}");
|
||||
assert_eq!(
|
||||
code("tabula", &text),
|
||||
(10, CanonCode::ForbiddenCharacter { codepoint: cp }),
|
||||
"{cp:X}"
|
||||
);
|
||||
}
|
||||
// In the front matter too.
|
||||
let front = FRONT.replace("name: Tabula", "name: Tab\u{202e}ula");
|
||||
assert_eq!(code("tabula", &with_front(&front, "")), (3, CanonCode::ForbiddenCharacter { codepoint: 0x202e }));
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")),
|
||||
(3, CanonCode::ForbiddenCharacter { codepoint: 0x202e })
|
||||
);
|
||||
// Tabs and ordinary non-ASCII text are fine.
|
||||
let text = with_front(FRONT, "- [F1] Poznámky\tžluťoučký kůň 📝\n");
|
||||
assert!(canon::parse("tabula", &text).is_ok());
|
||||
@@ -311,13 +421,26 @@ fn lone_cr_nul_and_hidden_characters_are_rejected() {
|
||||
fn canon_set() {
|
||||
let mut c = Canon::new();
|
||||
c.insert(canon::parse("tabula", TABULA).unwrap()).unwrap();
|
||||
let err = c.insert(canon::parse("tabula", TABULA).unwrap()).unwrap_err();
|
||||
let err = c
|
||||
.insert(canon::parse("tabula", TABULA).unwrap())
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code, CanonCode::DuplicateApp("tabula".into()));
|
||||
c.insert(CanonFile::adhoc("release", "Tabula", vec![(1, "Tabula 1.2 is out.".into())])).unwrap();
|
||||
assert_eq!(c.apps().map(|f| f.id.as_str()).collect::<Vec<_>>(), vec!["release", "tabula"]);
|
||||
c.insert(CanonFile::adhoc(
|
||||
"release",
|
||||
"Tabula",
|
||||
vec![(1, "Tabula 1.2 is out.".into())],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
c.apps().map(|f| f.id.as_str()).collect::<Vec<_>>(),
|
||||
vec!["release", "tabula"]
|
||||
);
|
||||
assert!(c.get("tabula").is_some());
|
||||
assert!(c.get("nope").is_none());
|
||||
assert_eq!(c.fact("tabula", 1).unwrap().text, "Tabula keeps notes on your own computer.");
|
||||
assert_eq!(
|
||||
c.fact("tabula", 1).unwrap().text,
|
||||
"Tabula keeps notes on your own computer."
|
||||
);
|
||||
assert!(c.fact("tabula", 9).is_none());
|
||||
assert!(c.fact("nope", 1).is_none());
|
||||
let urls = c.allowed_urls();
|
||||
@@ -331,11 +454,17 @@ fn adhoc_release_file() {
|
||||
let f = CanonFile::adhoc(
|
||||
"release",
|
||||
"Tabula",
|
||||
vec![(1, "Tabula 1.2 is out.".into()), (2, "Faster search. (assumption)".into())],
|
||||
vec![
|
||||
(1, "Tabula 1.2 is out.".into()),
|
||||
(2, "Faster search. (assumption)".into()),
|
||||
],
|
||||
);
|
||||
assert_eq!(f.id, "release");
|
||||
assert_eq!(f.front.name, "Tabula");
|
||||
assert_eq!(f.facts.len(), 2);
|
||||
assert!(f.facts.iter().all(|x| !x.assumption), "release facts count as confirmed");
|
||||
assert!(
|
||||
f.facts.iter().all(|x| !x.assumption),
|
||||
"release facts count as confirmed"
|
||||
);
|
||||
assert_eq!(f.fact(2).unwrap().text, "Faster search. (assumption)");
|
||||
}
|
||||
|
||||
@@ -26,23 +26,29 @@ fn canon() -> Canon {
|
||||
c.insert(CanonFile::adhoc(
|
||||
"release",
|
||||
"Tabula",
|
||||
vec![(1, "Tabula 1.2 is out.".into()), (2, "Search is faster.".into())],
|
||||
vec![
|
||||
(1, "Tabula 1.2 is out.".into()),
|
||||
(2, "Search is faster.".into()),
|
||||
],
|
||||
))
|
||||
.unwrap();
|
||||
c
|
||||
}
|
||||
|
||||
fn r(app: &str, fact: u32) -> Ref {
|
||||
Ref { app: app.into(), fact }
|
||||
Ref {
|
||||
app: app.into(),
|
||||
fact,
|
||||
}
|
||||
}
|
||||
|
||||
fn unsourced(text: &str) -> bool {
|
||||
let rep = claims::check(text, &canon());
|
||||
!rep.ok() && rep.problems.iter().all(|p| matches!(p, Problem::Unsourced { .. }))
|
||||
}
|
||||
|
||||
fn passes(text: &str) -> bool {
|
||||
claims::check(text, &canon()).ok()
|
||||
!rep.ok()
|
||||
&& rep
|
||||
.problems
|
||||
.iter()
|
||||
.all(|p| matches!(p, Problem::Unsourced { .. }))
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -54,7 +60,10 @@ fn sourced_sentences_pass_and_refs_are_collected() {
|
||||
&c,
|
||||
);
|
||||
assert!(rep.ok(), "{:?}", rep.problems);
|
||||
assert_eq!(rep.refs, vec![r("release", 1), r("tabula", 1), r("tabula", 7)]);
|
||||
assert_eq!(
|
||||
rep.refs,
|
||||
vec![r("release", 1), r("tabula", 1), r("tabula", 7)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -136,22 +145,41 @@ fn a_plain_phrase_with_anything_extra_needs_a_ref() {
|
||||
#[test]
|
||||
fn every_sentence_is_checked_separately() {
|
||||
let c = canon();
|
||||
let rep = claims::check("Tabula keeps notes local [tabula#F1]. It runs on Linux. Try it today.", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::Unsourced { sentence: "It runs on Linux.".into() }]);
|
||||
let rep = claims::check(
|
||||
"Tabula keeps notes local [tabula#F1]. It runs on Linux. Try it today.",
|
||||
&c,
|
||||
);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::Unsourced {
|
||||
sentence: "It runs on Linux.".into()
|
||||
}]
|
||||
);
|
||||
// Lines are sentences too.
|
||||
let rep = claims::check("Tabula 1.2 [release#F1]\nFaster search", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::Unsourced { sentence: "Faster search".into() }]);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::Unsourced {
|
||||
sentence: "Faster search".into()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimals_and_urls_do_not_split_sentences() {
|
||||
let c = canon();
|
||||
assert_eq!(claims::sentences("Tabula 1.2 is out. Try it."), vec!["Tabula 1.2 is out.", "Try it."]);
|
||||
assert_eq!(
|
||||
claims::sentences("Tabula 1.2 is out. Try it."),
|
||||
vec!["Tabula 1.2 is out.", "Try it."]
|
||||
);
|
||||
assert_eq!(
|
||||
claims::sentences("See https://aula.marek-novak.cz/tabula/?a=1. Thanks!"),
|
||||
vec!["See https://aula.marek-novak.cz/tabula/?a=1.", "Thanks!"]
|
||||
);
|
||||
assert_eq!(claims::sentences("A. [tabula#F1] B"), vec!["A. [tabula#F1]", "B"]);
|
||||
assert_eq!(
|
||||
claims::sentences("A. [tabula#F1] B"),
|
||||
vec!["A. [tabula#F1]", "B"]
|
||||
);
|
||||
assert!(claims::check("Tabula 1.2 is out. [release#F1]", &c).ok());
|
||||
}
|
||||
|
||||
@@ -159,17 +187,32 @@ fn decimals_and_urls_do_not_split_sentences() {
|
||||
fn bad_refs_are_rejected() {
|
||||
let c = canon();
|
||||
let rep = claims::check("Tabula keeps notes local. [tabula#F99]", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::MissingFact { r: r("tabula", 99) }]);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::MissingFact { r: r("tabula", 99) }]
|
||||
);
|
||||
let rep = claims::check("Notes, done. [notapp#F1]", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::UnknownApp { r: r("notapp", 1) }]);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::UnknownApp { r: r("notapp", 1) }]
|
||||
);
|
||||
let rep = claims::check("It syncs everywhere. [tabula#F2]", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::Unconfirmed { r: r("tabula", 2) }]);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::Unconfirmed { r: r("tabula", 2) }]
|
||||
);
|
||||
// A bad ref fails even on a plain sentence.
|
||||
let rep = claims::check("Try it today. [tabula#F99]", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::MissingFact { r: r("tabula", 99) }]);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::MissingFact { r: r("tabula", 99) }]
|
||||
);
|
||||
// One good ref does not excuse a bad one.
|
||||
let rep = claims::check("Local notes. [tabula#F1][tabula#F2]", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::Unconfirmed { r: r("tabula", 2) }]);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::Unconfirmed { r: r("tabula", 2) }]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -194,7 +237,9 @@ fn malformed_refs_are_rejected() {
|
||||
let text = format!("Tabula keeps notes on your own computer. {bad}");
|
||||
let rep = claims::check(&text, &c);
|
||||
assert!(
|
||||
rep.problems.iter().any(|p| matches!(p, Problem::MalformedRef { .. })),
|
||||
rep.problems
|
||||
.iter()
|
||||
.any(|p| matches!(p, Problem::MalformedRef { .. })),
|
||||
"{bad:?}: {:?}",
|
||||
rep.problems
|
||||
);
|
||||
@@ -208,26 +253,53 @@ fn urls_must_come_from_the_canon() {
|
||||
assert!(claims::check("Get it here: https://aula.marek-novak.cz/tabula/", &c).ok());
|
||||
assert!(claims::check("Get it here: https://aula.marek-novak.cz/tabula", &c).ok());
|
||||
assert!(claims::check("Read more: https://aula.marek-novak.cz/tabula/windows.", &c).ok());
|
||||
assert!(claims::check("Read more: (https://aula.marek-novak.cz/tabula/windows)", &c).ok());
|
||||
assert!(
|
||||
claims::check(
|
||||
"Read more: (https://aula.marek-novak.cz/tabula/windows)",
|
||||
&c
|
||||
)
|
||||
.ok()
|
||||
);
|
||||
for (text, url) in [
|
||||
("Get it here: https://evil.example/tabula", "https://evil.example/tabula"),
|
||||
("Get it here: http://aula.marek-novak.cz/tabula/", "http://aula.marek-novak.cz/tabula/"),
|
||||
("Get it here: https://aula.marek-novak.cz/tabula/x", "https://aula.marek-novak.cz/tabula/x"),
|
||||
(
|
||||
"Get it here: https://evil.example/tabula",
|
||||
"https://evil.example/tabula",
|
||||
),
|
||||
(
|
||||
"Get it here: http://aula.marek-novak.cz/tabula/",
|
||||
"http://aula.marek-novak.cz/tabula/",
|
||||
),
|
||||
(
|
||||
"Get it here: https://aula.marek-novak.cz/tabula/x",
|
||||
"https://aula.marek-novak.cz/tabula/x",
|
||||
),
|
||||
("Get it here: www.evil.example", "www.evil.example"),
|
||||
("Get it here: evil.com", "evil.com"),
|
||||
("Get it here: evil.example/download", "evil.example/download"),
|
||||
(
|
||||
"Get it here: evil.example/download",
|
||||
"evil.example/download",
|
||||
),
|
||||
("Get it here: ftp://evil.example", "ftp://evil.example"),
|
||||
] {
|
||||
let rep = claims::check(text, &c);
|
||||
assert!(
|
||||
rep.problems.contains(&Problem::UrlNotInCanon { url: url.into() }),
|
||||
rep.problems
|
||||
.contains(&Problem::UrlNotInCanon { url: url.into() }),
|
||||
"{text:?}: {:?}",
|
||||
rep.problems
|
||||
);
|
||||
}
|
||||
// A URL in a sourced sentence is still checked.
|
||||
let rep = claims::check("It runs on Windows, see https://evil.example/ [tabula#F3]", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::UrlNotInCanon { url: "https://evil.example/".into() }]);
|
||||
let rep = claims::check(
|
||||
"It runs on Windows, see https://evil.example/ [tabula#F3]",
|
||||
&c,
|
||||
);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::UrlNotInCanon {
|
||||
url: "https://evil.example/".into()
|
||||
}]
|
||||
);
|
||||
// A bare form of an allowed URL is fine.
|
||||
assert!(claims::check("Get it here: aula.marek-novak.cz/tabula/", &c).ok());
|
||||
}
|
||||
@@ -236,9 +308,15 @@ fn urls_must_come_from_the_canon() {
|
||||
fn hidden_characters_are_rejected() {
|
||||
let c = canon();
|
||||
let rep = claims::check("Try it today.\u{202e}", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::HiddenCharacter { codepoint: 0x202e }]);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::HiddenCharacter { codepoint: 0x202e }]
|
||||
);
|
||||
let rep = claims::check("Try it\0 today.", &c);
|
||||
assert!(rep.problems.contains(&Problem::HiddenCharacter { codepoint: 0 }));
|
||||
assert!(
|
||||
rep.problems
|
||||
.contains(&Problem::HiddenCharacter { codepoint: 0 })
|
||||
);
|
||||
// CRLF and tabs are ordinary whitespace.
|
||||
assert!(claims::check("Try it today.\r\nThanks!\t", &c).ok());
|
||||
}
|
||||
@@ -251,12 +329,37 @@ fn reasons_are_plain_english() {
|
||||
&c,
|
||||
);
|
||||
let reasons: Vec<String> = rep.problems.iter().map(Problem::reason).collect();
|
||||
assert!(reasons.iter().any(|s| s.contains("It runs on Linux.") && s.contains("no source")), "{reasons:?}");
|
||||
assert!(reasons.iter().any(|s| s.contains("tabula#F99") && s.contains("does not exist")), "{reasons:?}");
|
||||
assert!(reasons.iter().any(|s| s.contains("unknown app") && s.contains("x")), "{reasons:?}");
|
||||
assert!(reasons.iter().any(|s| s.contains("unconfirmed fact") && s.contains("tabula#F2")), "{reasons:?}");
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("It runs on Linux.") && s.contains("no source")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("tabula#F99") && s.contains("does not exist")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("unknown app") && s.contains("x")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("unconfirmed fact") && s.contains("tabula#F2")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert!(reasons.iter().any(|s| s.contains("[F3]")), "{reasons:?}");
|
||||
assert!(reasons.iter().any(|s| s.contains("https://evil.example/") && s.contains("not in the canon")), "{reasons:?}");
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("https://evil.example/") && s.contains("not in the canon")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
Problem::HiddenCharacter { codepoint: 0x202e }.reason(),
|
||||
"Hidden or direction-changing character U+202E."
|
||||
@@ -267,21 +370,38 @@ fn reasons_are_plain_english() {
|
||||
fn problems_are_not_repeated() {
|
||||
let c = canon();
|
||||
let rep = claims::check("A. [tabula#F99] B. [tabula#F99]", &c);
|
||||
assert_eq!(rep.problems, vec![Problem::MissingFact { r: r("tabula", 99) }]);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::MissingFact { r: r("tabula", 99) }]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_refs_for_display() {
|
||||
assert_eq!(
|
||||
claims::strip_refs("Tabula keeps notes local [tabula#F1]. One click.[tabula#F7][tabula#F1] Done [release#F1]"),
|
||||
claims::strip_refs(
|
||||
"Tabula keeps notes local [tabula#F1]. One click.[tabula#F7][tabula#F1] Done [release#F1]"
|
||||
),
|
||||
"Tabula keeps notes local. One click. Done"
|
||||
);
|
||||
assert_eq!(claims::strip_refs("Tabula [tabula#F1] keeps notes."), "Tabula keeps notes.");
|
||||
assert_eq!(
|
||||
claims::strip_refs("Tabula [tabula#F1] keeps notes."),
|
||||
"Tabula keeps notes."
|
||||
);
|
||||
assert_eq!(claims::strip_refs("A.[tabula#F1]B"), "A. B");
|
||||
assert_eq!(claims::strip_refs("Line one [tabula#F1]\nLine two"), "Line one\nLine two");
|
||||
assert_eq!(claims::strip_refs("Keep [beta] and [Tabula#F1]."), "Keep [beta] and [Tabula#F1].");
|
||||
assert_eq!(
|
||||
claims::strip_refs("Line one [tabula#F1]\nLine two"),
|
||||
"Line one\nLine two"
|
||||
);
|
||||
assert_eq!(
|
||||
claims::strip_refs("Keep [beta] and [Tabula#F1]."),
|
||||
"Keep [beta] and [Tabula#F1]."
|
||||
);
|
||||
assert_eq!(claims::strip_refs(""), "");
|
||||
assert_eq!(claims::strip_refs("Žluťoučký [tabula#F1]kůň"), "Žluťoučký kůň");
|
||||
assert_eq!(
|
||||
claims::strip_refs("Žluťoučký [tabula#F1]kůň"),
|
||||
"Žluťoučký kůň"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -292,3 +412,23 @@ fn stripped_text_of_a_passing_text_has_no_refs() {
|
||||
let stripped = claims::strip_refs(text);
|
||||
assert!(claims::check(&stripped, &c).refs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn states_fact_is_fail_closed() {
|
||||
let c = canon();
|
||||
assert!(!claims::states_fact("Try it today.", &c));
|
||||
assert!(!claims::states_fact("Here's what's new [tabula#F1].", &c));
|
||||
assert!(claims::states_fact("Tabula is great.", &c));
|
||||
assert!(claims::states_fact("It is what it is.", &c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_text_is_checked_without_trouble() {
|
||||
let c = canon();
|
||||
let text = "Local notes [tabula#F1]. ".repeat(2000);
|
||||
let rep = claims::check(&text, &c);
|
||||
assert!(rep.ok());
|
||||
assert_eq!(rep.refs, vec![r("tabula", 1)]);
|
||||
let line = "a".repeat(100_000);
|
||||
assert!(!claims::check(&line, &c).ok());
|
||||
}
|
||||
|
||||
@@ -17,13 +17,19 @@ Prose is ignored.
|
||||
";
|
||||
|
||||
fn values(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
|
||||
pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_templates_with_slots_in_order() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
assert_eq!(hs.iter().map(|h| h.id.as_str()).collect::<Vec<_>>(), vec!["H1", "H2", "H3", "H4", "H5"]);
|
||||
assert_eq!(
|
||||
hs.iter().map(|h| h.id.as_str()).collect::<Vec<_>>(),
|
||||
vec!["H1", "H2", "H3", "H4", "H5"]
|
||||
);
|
||||
assert_eq!(hs[0].text, "Tired of {pain}? {app} fixes it.");
|
||||
assert_eq!(hs[0].slots, vec!["pain", "app"]);
|
||||
assert_eq!(hs[1].slots, vec!["number", "audience", "app"]);
|
||||
@@ -38,18 +44,30 @@ fn slots_are_unique() {
|
||||
|
||||
#[test]
|
||||
fn every_fixed_slot_is_allowed() {
|
||||
let line = format!("- [H1] {}\n", hooks::SLOTS.map(|s| format!("{{{s}}}")).join(" "));
|
||||
let line = format!(
|
||||
"- [H1] {}\n",
|
||||
hooks::SLOTS.map(|s| format!("{{{s}}}")).join(" ")
|
||||
);
|
||||
let hs = hooks::parse(&line).unwrap();
|
||||
assert_eq!(hs[0].slots, hooks::SLOTS.to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_slots_are_errors() {
|
||||
for (bad, slot) in [("{price}", "price"), ("{App}", "App"), ("{}", ""), ("{ app }", " app "), ("{url}", "url")] {
|
||||
for (bad, slot) in [
|
||||
("{price}", "price"),
|
||||
("{App}", "App"),
|
||||
("{}", ""),
|
||||
("{ app }", " app "),
|
||||
("{url}", "url"),
|
||||
] {
|
||||
let md = format!("# x\n- [H1] Hello {bad}\n");
|
||||
assert_eq!(
|
||||
hooks::parse(&md),
|
||||
Err(HookError::UnknownSlot { line: 2, slot: slot.into() }),
|
||||
Err(HookError::UnknownSlot {
|
||||
line: 2,
|
||||
slot: slot.into()
|
||||
}),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
@@ -59,35 +77,76 @@ fn unknown_slots_are_errors() {
|
||||
fn unbalanced_braces_are_errors() {
|
||||
for bad in ["{app", "app}", "{{app}}", "{a{pp}", "}{"] {
|
||||
let md = format!("- [H1] Hi {bad}\n");
|
||||
assert_eq!(hooks::parse(&md), Err(HookError::UnbalancedBrace { line: 1 }), "{bad:?}");
|
||||
assert_eq!(
|
||||
hooks::parse(&md),
|
||||
Err(HookError::UnbalancedBrace { line: 1 }),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_duplicate_and_empty_lines() {
|
||||
for bad in ["- [H] x", "- [Hx] x", "- [H1]x", "- [H1 x", "- [h1] x", " - [H1] x", "- [H1] x"] {
|
||||
assert_eq!(hooks::parse(&format!("{bad}\n")), Err(HookError::Malformed { line: 1 }), "{bad:?}");
|
||||
for bad in [
|
||||
"- [H] x",
|
||||
"- [Hx] x",
|
||||
"- [H1]x",
|
||||
"- [H1 x",
|
||||
"- [h1] x",
|
||||
" - [H1] x",
|
||||
"- [H1] x",
|
||||
] {
|
||||
assert_eq!(
|
||||
hooks::parse(&format!("{bad}\n")),
|
||||
Err(HookError::Malformed { line: 1 }),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
for bad in ["- [H0] x", "- [H01] x", "- [H10000] x"] {
|
||||
assert_eq!(hooks::parse(&format!("{bad}\n")), Err(HookError::IdOutOfRange { line: 1 }), "{bad:?}");
|
||||
assert_eq!(
|
||||
hooks::parse(&format!("{bad}\n")),
|
||||
Err(HookError::IdOutOfRange { line: 1 }),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1] a\n- [H1] b\n"),
|
||||
Err(HookError::Duplicate { line: 2, id: "H1".into() })
|
||||
Err(HookError::Duplicate {
|
||||
line: 2,
|
||||
id: "H1".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1] \n"),
|
||||
Err(HookError::Empty { line: 1 })
|
||||
);
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1]\n"),
|
||||
Err(HookError::Malformed { line: 1 })
|
||||
);
|
||||
assert_eq!(hooks::parse("- [H1] \n"), Err(HookError::Empty { line: 1 }));
|
||||
assert_eq!(hooks::parse("- [H1]\n"), Err(HookError::Malformed { line: 1 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input() {
|
||||
let big = format!("- [H1] {}\n", "a".repeat(hooks::MAX_FILE_BYTES));
|
||||
assert!(matches!(hooks::parse(&big), Err(HookError::TooLarge { .. })));
|
||||
assert!(matches!(
|
||||
hooks::parse(&big),
|
||||
Err(HookError::TooLarge { .. })
|
||||
));
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1] a\u{202e}b\n"),
|
||||
Err(HookError::ForbiddenCharacter { line: 1, codepoint: 0x202e })
|
||||
Err(HookError::ForbiddenCharacter {
|
||||
line: 1,
|
||||
codepoint: 0x202e
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
hooks::parse("x\n- [H1] a\0b\n"),
|
||||
Err(HookError::ForbiddenCharacter {
|
||||
line: 2,
|
||||
codepoint: 0
|
||||
})
|
||||
);
|
||||
assert_eq!(hooks::parse("x\n- [H1] a\0b\n"), Err(HookError::ForbiddenCharacter { line: 2, codepoint: 0 }));
|
||||
let crlf = HOOKS.replace('\n', "\r\n");
|
||||
assert_eq!(hooks::parse(&crlf).unwrap(), hooks::parse(HOOKS).unwrap());
|
||||
let bom = format!("\u{feff}{HOOKS}");
|
||||
@@ -99,7 +158,10 @@ fn hostile_input() {
|
||||
fn fill_replaces_every_slot() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
let v = values(&[("pain", "lost notes"), ("app", "Tabula"), ("unused", "x")]);
|
||||
assert_eq!(hs[0].fill(&v).unwrap(), "Tired of lost notes? Tabula fixes it.");
|
||||
assert_eq!(
|
||||
hs[0].fill(&v).unwrap(),
|
||||
"Tired of lost notes? Tabula fixes it."
|
||||
);
|
||||
assert_eq!(hs[4].fill(&BTreeMap::new()).unwrap(), "Stop losing notes.");
|
||||
}
|
||||
|
||||
@@ -107,14 +169,22 @@ fn fill_replaces_every_slot() {
|
||||
fn fill_missing_value_is_an_error() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
let v = values(&[("app", "Tabula")]);
|
||||
assert_eq!(hs[0].fill(&v), Err(HookError::MissingValue { slot: "pain".into() }));
|
||||
assert_eq!(
|
||||
hs[0].fill(&v),
|
||||
Err(HookError::MissingValue {
|
||||
slot: "pain".into()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_does_not_re_expand_braces_in_values() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
let v = values(&[("pain", "{app}"), ("app", "{pain} {x}")]);
|
||||
assert_eq!(hs[0].fill(&v).unwrap(), "Tired of {app}? {pain} {x} fixes it.");
|
||||
assert_eq!(
|
||||
hs[0].fill(&v).unwrap(),
|
||||
"Tired of {app}? {pain} {x} fixes it."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -122,19 +192,39 @@ fn genome_from_text() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
assert_eq!(
|
||||
hs[0].genome,
|
||||
Genome { opening: Opening::Question, words: 6, has_number: false, lead_verb: None }
|
||||
Genome {
|
||||
opening: Opening::Question,
|
||||
words: 6,
|
||||
has_number: false,
|
||||
lead_verb: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
hs[1].genome,
|
||||
Genome { opening: Opening::Number, words: 5, has_number: true, lead_verb: None }
|
||||
Genome {
|
||||
opening: Opening::Number,
|
||||
words: 5,
|
||||
has_number: true,
|
||||
lead_verb: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
hs[2].genome,
|
||||
Genome { opening: Opening::Command, words: 4, has_number: false, lead_verb: Some("try".into()) }
|
||||
Genome {
|
||||
opening: Opening::Command,
|
||||
words: 4,
|
||||
has_number: false,
|
||||
lead_verb: Some("try".into())
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
hs[3].genome,
|
||||
Genome { opening: Opening::Statement, words: 5, has_number: false, lead_verb: None }
|
||||
Genome {
|
||||
opening: Opening::Statement,
|
||||
words: 5,
|
||||
has_number: false,
|
||||
lead_verb: None
|
||||
}
|
||||
);
|
||||
assert_eq!(hs[4].genome.opening, Opening::Command);
|
||||
assert_eq!(hs[4].genome.lead_verb.as_deref(), Some("stop"));
|
||||
@@ -151,8 +241,24 @@ fn genome_of_filled_text() {
|
||||
let g = Genome::of("Your notes, on your computer. Ever wondered why?");
|
||||
assert_eq!(g.opening, Opening::Statement);
|
||||
let g = Genome::of("");
|
||||
assert_eq!(g, Genome { opening: Opening::Statement, words: 0, has_number: false, lead_verb: None });
|
||||
assert_eq!(
|
||||
g,
|
||||
Genome {
|
||||
opening: Opening::Statement,
|
||||
words: 0,
|
||||
has_number: false,
|
||||
lead_verb: None
|
||||
}
|
||||
);
|
||||
let g = Genome::of("Meet Tabula 2.");
|
||||
assert_eq!(g.opening, Opening::Command);
|
||||
assert!(g.has_number);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lone_carriage_return_is_an_error() {
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1] a\rb\n"),
|
||||
Err(HookError::LoneCarriageReturn { line: 1 })
|
||||
);
|
||||
}
|
||||
|
||||
@@ -87,11 +87,27 @@ fn value() -> impl Strategy<Value = String> {
|
||||
|
||||
fn gen_file() -> impl Strategy<Value = (String, Vec<GenFact>, [String; 5], Status)> {
|
||||
let id = "[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?";
|
||||
let facts = prop::collection::btree_map(1u32..=9999, (fact_text(), any::<bool>()), 0..40).prop_map(|m| {
|
||||
m.into_iter().map(|(id, (text, assumption))| GenFact { id, text, assumption }).collect::<Vec<_>>()
|
||||
let facts = prop::collection::btree_map(1u32..=9999, (fact_text(), any::<bool>()), 0..40)
|
||||
.prop_map(|m| {
|
||||
m.into_iter()
|
||||
.map(|(id, (text, assumption))| GenFact {
|
||||
id,
|
||||
text,
|
||||
assumption,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
let status = prop_oneof![Just(Status::Released), Just(Status::Beta), Just(Status::Planned)];
|
||||
(id, facts, [value(), value(), value(), value(), value()], status)
|
||||
let status = prop_oneof![
|
||||
Just(Status::Released),
|
||||
Just(Status::Beta),
|
||||
Just(Status::Planned)
|
||||
];
|
||||
(
|
||||
id,
|
||||
facts,
|
||||
[value(), value(), value(), value(), value()],
|
||||
status,
|
||||
)
|
||||
}
|
||||
|
||||
fn render(id: &str, facts: &[GenFact], v: &[String; 5], status: Status, shuffle: u64) -> String {
|
||||
@@ -114,7 +130,12 @@ fn render(id: &str, facts: &[GenFact], v: &[String; 5], status: Status, shuffle:
|
||||
if i % 7 == 3 {
|
||||
s.push_str("\n## More\n\nSome prose.\n");
|
||||
}
|
||||
s.push_str(&format!("- [F{}] {}{}\n", f.id, f.text, if f.assumption { " (assumption)" } else { "" }));
|
||||
s.push_str(&format!(
|
||||
"- [F{}] {}{}\n",
|
||||
f.id,
|
||||
f.text,
|
||||
if f.assumption { " (assumption)" } else { "" }
|
||||
));
|
||||
}
|
||||
s
|
||||
}
|
||||
@@ -140,7 +161,8 @@ proptest! {
|
||||
hooks::SLOTS.iter().map(|s| (s.to_string(), "{app}".to_string())).collect();
|
||||
for h in hs {
|
||||
let filled = h.fill(&v).unwrap();
|
||||
prop_assert!(!filled.contains("{feature}"));
|
||||
let slot = format!("{{{}}}", "feature");
|
||||
prop_assert!(!filled.contains(&slot));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user