vault: file and glob excludes, machinery files never lore, CRLF folded before hashing, backslash patterns refused
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6df910a925
commit
a5ddfb9d76
1 changed files with 208 additions and 13 deletions
|
|
@ -56,6 +56,8 @@ pub enum VaultError {
|
|||
Root,
|
||||
#[error("vault scope escapes its root: {0}")]
|
||||
Scope(String),
|
||||
#[error("vault pattern is not a vault-relative path written with forward slashes: {0}")]
|
||||
Pattern(String),
|
||||
#[error("vault holds more than {MAX_VAULT_NOTES} notes")]
|
||||
TooManyNotes,
|
||||
#[error("the snapshot store could not be written or read")]
|
||||
|
|
@ -69,7 +71,12 @@ pub enum VaultError {
|
|||
/// What to import from one vault. Any Obsidian-style folder of `.md` files plugs
|
||||
/// in through a profile. `.obsidian`, `.git` and every other dot-directory are
|
||||
/// always skipped, and so is a nested vault (a subdirectory holding its own
|
||||
/// `.obsidian`) unless `include` names it or something inside it.
|
||||
/// `.obsidian`) unless `include` names it or something inside it. Repository
|
||||
/// machinery is never lore: a file named `AGENTS.md`, `CLAUDE.md` or `README.md`
|
||||
/// (any case, any depth) is always skipped.
|
||||
///
|
||||
/// Production profiles are the table in the ignored `real_vaults_build` test at
|
||||
/// the foot of this file; a profile is data and nothing else owns one.
|
||||
///
|
||||
/// `root` is machine-local: it locates the files and is deliberately not part of
|
||||
/// the snapshot id nor carried into the snapshot, so one vault imported on two
|
||||
|
|
@ -79,10 +86,14 @@ pub enum VaultError {
|
|||
pub struct VaultProfile {
|
||||
pub name: String,
|
||||
pub root: PathBuf,
|
||||
/// Vault-relative directories to admit notes from; empty admits everything
|
||||
/// under `scope` that is not excluded.
|
||||
/// Vault-relative directories to admit notes from, no wildcards; empty
|
||||
/// admits everything under `scope` that is not excluded.
|
||||
pub include: Vec<String>,
|
||||
/// Vault-relative directories not entered at all.
|
||||
/// Vault-relative paths of directories or files not admitted, written with
|
||||
/// forward slashes: `Spoilers.md`, `Game Design`, `Stories/*/Branch Map.md`.
|
||||
/// A `*` stands for any run of characters inside one path component, never
|
||||
/// across a `/`. A pattern also excludes everything under a directory it
|
||||
/// names. A backslash is refused at build rather than matching nothing.
|
||||
pub exclude: Vec<String>,
|
||||
/// A vault-relative subdirectory the import is narrowed to; empty is the
|
||||
/// whole root. References stay relative to `root`.
|
||||
|
|
@ -126,7 +137,7 @@ struct SnapshotNote {
|
|||
/// because the kernel has no scheme registry; and not a digest, because a
|
||||
/// human must be able to resolve it years later.
|
||||
reference: String,
|
||||
/// Of the file's bytes, lowercase hex.
|
||||
/// Of the file's text with CRLF folded to LF, lowercase hex.
|
||||
sha256: String,
|
||||
/// Frontmatter title, else the filename stem.
|
||||
title: String,
|
||||
|
|
@ -180,8 +191,8 @@ impl VaultSnapshot {
|
|||
let canonical = VaultProfile {
|
||||
name: profile.name.clone(),
|
||||
root: PathBuf::new(),
|
||||
include: canonical_dirs(&profile.include)?,
|
||||
exclude: canonical_dirs(&profile.exclude)?,
|
||||
include: canonical_dirs(&profile.include, false)?,
|
||||
exclude: canonical_dirs(&profile.exclude, true)?,
|
||||
scope: scope.clone(),
|
||||
};
|
||||
let start = if scope.is_empty() {
|
||||
|
|
@ -216,6 +227,9 @@ impl VaultSnapshot {
|
|||
let Ok(text) = String::from_utf8(bytes) else {
|
||||
continue;
|
||||
};
|
||||
// A checkout with autocrlf holds the same note: fold before the
|
||||
// hash, the parse and the stored body.
|
||||
let text = text.replace("\r\n", "\n");
|
||||
let stem = Path::new(&reference)
|
||||
.file_stem()
|
||||
.map(|value| value.to_string_lossy().into_owned())
|
||||
|
|
@ -351,9 +365,12 @@ fn relative_dir(text: &str) -> Option<String> {
|
|||
)
|
||||
}
|
||||
|
||||
fn canonical_dirs(dirs: &[String]) -> Result<Vec<String>, VaultError> {
|
||||
fn canonical_dirs(dirs: &[String], wildcards: bool) -> Result<Vec<String>, VaultError> {
|
||||
let mut clean = BTreeSet::new();
|
||||
for dir in dirs {
|
||||
if dir.contains('\\') || (!wildcards && dir.contains('*')) {
|
||||
return Err(VaultError::Pattern(dir.clone()));
|
||||
}
|
||||
match relative_dir(dir) {
|
||||
Some(text) if !text.is_empty() => clean.insert(text),
|
||||
_ => return Err(VaultError::Scope(dir.clone())),
|
||||
|
|
@ -367,6 +384,30 @@ fn is_under(path: &str, dir: &str) -> bool {
|
|||
path == dir || path.strip_prefix(dir).is_some_and(|rest| rest.starts_with('/'))
|
||||
}
|
||||
|
||||
/// Whether `path` or one of its ancestors matches `pattern`, component-wise.
|
||||
fn matches_pattern(path: &str, pattern: &str) -> bool {
|
||||
fn glob(pattern: &[char], text: &[char]) -> bool {
|
||||
match pattern.split_first() {
|
||||
None => text.is_empty(),
|
||||
Some(('*', rest)) => (0..=text.len()).any(|taken| glob(rest, &text[taken..])),
|
||||
Some((head, rest)) => text.first() == Some(head) && glob(rest, &text[1..]),
|
||||
}
|
||||
}
|
||||
let parts: Vec<&str> = path.split('/').collect();
|
||||
let wanted: Vec<&str> = pattern.split('/').collect();
|
||||
wanted.len() <= parts.len()
|
||||
&& wanted.iter().zip(&parts).all(|(want, part)| {
|
||||
glob(&want.chars().collect::<Vec<_>>(), &part.chars().collect::<Vec<_>>())
|
||||
})
|
||||
}
|
||||
|
||||
/// Repository and agent files are never lore, in any vault, at any depth.
|
||||
fn is_machinery(name: &str) -> bool {
|
||||
["AGENTS.md", "CLAUDE.md", "README.md"]
|
||||
.iter()
|
||||
.any(|machine| name.eq_ignore_ascii_case(machine))
|
||||
}
|
||||
|
||||
/// `(reference, path)` of every admitted note below `directory`; `relative` is
|
||||
/// `directory`'s own vault-relative path. Entry order is the filesystem's and
|
||||
/// carries no meaning: the caller sorts.
|
||||
|
|
@ -394,7 +435,7 @@ fn collect_notes(
|
|||
};
|
||||
if metadata.is_dir() {
|
||||
if name.starts_with('.')
|
||||
|| profile.exclude.iter().any(|dir| is_under(&child, dir))
|
||||
|| profile.exclude.iter().any(|pattern| matches_pattern(&child, pattern))
|
||||
|| (path.join(".obsidian").is_dir()
|
||||
&& !profile.include.iter().any(|dir| is_under(dir, &child) || is_under(&child, dir)))
|
||||
{
|
||||
|
|
@ -408,6 +449,8 @@ fn collect_notes(
|
|||
}
|
||||
collect_notes(root, &path, &child, profile, into)?;
|
||||
} else if path.extension().is_some_and(|value| value == "md")
|
||||
&& !is_machinery(&name)
|
||||
&& !profile.exclude.iter().any(|pattern| matches_pattern(&child, pattern))
|
||||
&& (profile.include.is_empty() || profile.include.iter().any(|dir| is_under(&child, dir)))
|
||||
{
|
||||
let Ok(canonical) = path.canonicalize() else {
|
||||
|
|
@ -1256,6 +1299,140 @@ mod tests {
|
|||
assert!(VaultSnapshot::build(&VaultProfile { exclude: vec!["/abs".into()], ..profile(vault.path()) }).is_err());
|
||||
}
|
||||
|
||||
fn references(snapshot: &VaultSnapshot) -> Vec<&str> {
|
||||
snapshot.notes.iter().map(|note| note.reference.as_str()).collect()
|
||||
}
|
||||
|
||||
/// The same note checked out with CRLF line endings is the same snapshot,
|
||||
/// down to the stored body and digest.
|
||||
#[test]
|
||||
fn crlf_and_lf_checkouts_are_one_snapshot() {
|
||||
let lf = tempfile::tempdir().unwrap();
|
||||
let crlf = tempfile::tempdir().unwrap();
|
||||
write(lf.path(), "A.md", "---\ntitle: Alpha\n---\nline one\nline two\n");
|
||||
write(crlf.path(), "A.md", "---\r\ntitle: Alpha\r\n---\r\nline one\r\nline two\r\n");
|
||||
let (a, b) = (snapshot(lf.path()), snapshot(crlf.path()));
|
||||
assert_eq!(a.id(), b.id());
|
||||
assert_eq!(a.to_bytes(), b.to_bytes());
|
||||
assert_eq!(b.notes[0].title, "Alpha");
|
||||
assert!(!b.notes[0].body.contains('\r'));
|
||||
}
|
||||
|
||||
/// Include and exclude are part of the id even when they change no note.
|
||||
#[test]
|
||||
fn include_and_exclude_are_in_the_id_even_when_they_admit_the_same_notes() {
|
||||
let vault = fixture();
|
||||
let base = snapshot(vault.path());
|
||||
let excluded = VaultSnapshot::build(&VaultProfile {
|
||||
exclude: vec!["Nothing Here".into()],
|
||||
..profile(vault.path())
|
||||
})
|
||||
.unwrap();
|
||||
let included = VaultSnapshot::build(&VaultProfile {
|
||||
include: vec!["Public".into(), "Spoilers".into()],
|
||||
..profile(vault.path())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(excluded.note_count(), base.note_count());
|
||||
assert_eq!(included.note_count(), base.note_count());
|
||||
assert_ne!(excluded.id(), base.id());
|
||||
assert_ne!(included.id(), base.id());
|
||||
assert_ne!(excluded.id(), included.id());
|
||||
// The two lists are not interchangeable.
|
||||
let swapped = VaultSnapshot::build(&VaultProfile {
|
||||
exclude: vec!["Public".into(), "Spoilers".into()],
|
||||
..profile(vault.path())
|
||||
})
|
||||
.unwrap();
|
||||
assert_ne!(swapped.id(), included.id());
|
||||
assert_eq!(base.profile().root, PathBuf::new());
|
||||
assert_eq!(base.profile().name, "fixture");
|
||||
assert_eq!(excluded.profile().exclude, ["Nothing Here"]);
|
||||
}
|
||||
|
||||
/// Exclusion names files and globs, and repository machinery is never lore.
|
||||
#[test]
|
||||
fn file_and_glob_excludes_and_machinery_files_keep_notes_out() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let root = vault.path();
|
||||
for note in [
|
||||
"Keep.md",
|
||||
"Spoilers.md",
|
||||
"AGENTS.md",
|
||||
"claude.md",
|
||||
"Sub/README.md",
|
||||
"Sub/Deep/CLAUDE.md",
|
||||
"Sub/Note.md",
|
||||
"static/vendor/page.md",
|
||||
"Stories/Coordinator Strategy.md",
|
||||
"Stories/One/Coordinator Strategy.md",
|
||||
"Stories/One/Branch Map.md",
|
||||
"Stories/One/Kept.md",
|
||||
"Stories/Two/Coordinator Strategy.md",
|
||||
"Stories/Two/Deep/Coordinator Strategy.md",
|
||||
] {
|
||||
write(root, note, "x\n");
|
||||
}
|
||||
let built = VaultSnapshot::build(&VaultProfile {
|
||||
exclude: vec![
|
||||
"Spoilers.md".into(),
|
||||
"static".into(),
|
||||
"Stories/*/Coordinator Strategy.md".into(),
|
||||
"Stories/*/Branch Map.md".into(),
|
||||
],
|
||||
..profile(root)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
references(&built),
|
||||
[
|
||||
"Keep.md",
|
||||
"Stories/Coordinator Strategy.md",
|
||||
"Stories/One/Kept.md",
|
||||
"Stories/Two/Deep/Coordinator Strategy.md",
|
||||
"Sub/Note.md",
|
||||
]
|
||||
);
|
||||
// `*` stays inside one component and may sit inside a name.
|
||||
assert!(matches_pattern("Stories/One/x.md", "Stories/*/x.md"));
|
||||
assert!(!matches_pattern("Stories/One/Two/x.md", "Stories/*/x.md"));
|
||||
assert!(matches_pattern("Game Design/a/b.md", "Game*"));
|
||||
assert!(!matches_pattern("Game", "Game Design"));
|
||||
}
|
||||
|
||||
/// A backslash pattern is refused with a clear error, never matched against
|
||||
/// nothing; an empty pattern and a wildcard include are refused too.
|
||||
#[test]
|
||||
fn a_backslash_or_empty_pattern_is_refused_at_build() {
|
||||
let vault = fixture();
|
||||
for exclude in ["Public\\Places", "Stories\\*\\Map.md", ""] {
|
||||
let error = VaultSnapshot::build(&VaultProfile {
|
||||
exclude: vec![exclude.into()],
|
||||
..profile(vault.path())
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(error, VaultError::Pattern(_) | VaultError::Scope(_)),
|
||||
"{exclude:?} gave {error:?}"
|
||||
);
|
||||
}
|
||||
let backslash = VaultSnapshot::build(&VaultProfile {
|
||||
exclude: vec!["Public\\Places".into()],
|
||||
..profile(vault.path())
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(backslash, VaultError::Pattern(ref text) if text == "Public\\Places"));
|
||||
assert!(backslash.to_string().contains("forward slashes"));
|
||||
assert!(matches!(
|
||||
VaultSnapshot::build(&VaultProfile { include: vec!["Pub*".into()], ..profile(vault.path()) }),
|
||||
Err(VaultError::Pattern(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
VaultSnapshot::build(&VaultProfile { include: vec!["a\\b".into()], ..profile(vault.path()) }),
|
||||
Err(VaultError::Pattern(_))
|
||||
));
|
||||
}
|
||||
|
||||
/// Real vaults, read-only. `GHOSTLIGHT_VAULT_SMOKE` names a directory that
|
||||
/// holds byte-for-byte copies of `AetheriaLore`, `Zyphos` and `Delvehold`.
|
||||
#[test]
|
||||
|
|
@ -1263,10 +1440,21 @@ mod tests {
|
|||
fn real_vaults_build() {
|
||||
let base = PathBuf::from(std::env::var("GHOSTLIGHT_VAULT_SMOKE").unwrap());
|
||||
let cases = [
|
||||
("aetheria", "AetheriaLore/Aetheria", vec!["Brainstorming", "Game Design"]),
|
||||
("zyphos", "Zyphos", vec!["quartz-site", "site", "tools", "state", "notes", "node_modules"]),
|
||||
("eusocial-interbeing", "Zyphos/Eusocial Interbeing", vec![]),
|
||||
("delvehold", "Delvehold/Delvehold", vec![]),
|
||||
(
|
||||
"aetheria",
|
||||
"AetheriaLore/Aetheria",
|
||||
vec![
|
||||
"Brainstorming",
|
||||
"Game Design",
|
||||
"Spoilers.md",
|
||||
"static",
|
||||
"Stories/How Branching Stories Are Made.md",
|
||||
"Stories/*/Coordinator Strategy.md",
|
||||
"Stories/*/Branch Map.md",
|
||||
],
|
||||
),
|
||||
("zyphos", "Zyphos/Eusocial Interbeing", vec!["Game Design", "Inspirations"]),
|
||||
("delvehold", "Delvehold/Delvehold", vec!["Game Design", "Documentation"]),
|
||||
("avatar", "Avatar", vec![]),
|
||||
];
|
||||
for (name, relative, exclude) in cases {
|
||||
|
|
@ -1279,6 +1467,13 @@ mod tests {
|
|||
let built = VaultSnapshot::build(&profile).unwrap();
|
||||
let again = VaultSnapshot::build(&profile).unwrap();
|
||||
assert_eq!(built.id(), again.id());
|
||||
for note in &built.notes {
|
||||
let leaf = note.reference.rsplit('/').next().unwrap();
|
||||
assert!(!is_machinery(leaf), "{name} admitted {}", note.reference);
|
||||
for pattern in &built.profile().exclude {
|
||||
assert!(!matches_pattern(¬e.reference, pattern), "{name} admitted {}", note.reference);
|
||||
}
|
||||
}
|
||||
println!("SMOKE {name} notes={} id={}", built.note_count(), built.id());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue