1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
//! Traversal — materialize the spanning containment tree from a root document.
//!
//! This is the discovery walk the whole crate exists for: start at a document,
//! follow the spanning relation's links declared *in* each document, and the
//! workspace structure unfolds. The walk is resilient by design — a missing or
//! unparseable target becomes a marked node, not an error — because a
//! traversal that dies on the first broken link cannot power `tree`, `check`,
//! or any editor view of an imperfect (i.e. real) workspace.
use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use crate::document::Document;
use crate::error::Result;
use crate::fs::Storage;
use crate::index::IndexStore;
use crate::link::{self, Link};
use crate::meta::Value;
use crate::workspace::{Target, Workspace};
/// Why a node appears in the tree the way it does.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NodeKind {
/// A document that was read and parsed.
Doc,
/// A spanning target that does not exist on disk.
Missing,
/// A target already on the path from the root — a containment cycle. Not
/// descended into.
Cycle,
/// A file that exists but could not be read or parsed; the message says why.
Unreadable(String),
/// An `id:<id>` target the registry does not currently resolve
/// (unknown, tombstoned, or no registry attached).
UnresolvedId(crate::identity::Id),
/// A nominal (alias) target whose name several documents claim — a
/// containment link that cannot be resolved to one child.
AmbiguousAlias(String),
}
/// One node of the materialized spanning tree.
#[derive(Debug, Clone)]
pub struct Node {
/// Workspace-relative, normalized path.
pub path: PathBuf,
/// The document's `title` field, when present.
pub title: Option<String>,
/// The label the *parent's* link carried (`[label](path)`), when any.
pub label: Option<String>,
/// How this node was resolved.
pub kind: NodeKind,
/// Spanning children, in declaration order.
pub children: Vec<Node>,
}
impl<FS: Storage, Id, Ix: IndexStore> Workspace<FS, Id, Ix> {
/// Materialize the spanning tree rooted at `start` (a workspace-relative
/// path). Missing, unreadable, cyclic, unresolved-ID, and ambiguous-alias
/// targets become marked nodes. `id:<id>` targets resolve through the
/// registry; nominal (`[[My File]]`) targets resolve through the title
/// index, built once for the whole walk so spanning alias links (a
/// `contents: alias` vocabulary) descend like any other.
pub async fn tree(&self, start: impl AsRef<Path>) -> Result<Node> {
let start = link::normalize(start);
// The title index is built lazily — only if a nominal (`[[alias]]`) link
// is actually encountered. A path/id workspace never needs it, so it never
// pays for a full-workspace scan (which, at the root of a larger repo,
// would read every file under `target/`, vendored trees, and the rest).
let mut titles: Option<crate::title::TitleIndex> = None;
let mut trail: Vec<PathBuf> = Vec::new();
let root = start.clone();
self.tree_node(start, None, &root, &mut titles, &mut trail)
.await
}
/// Read and parse the workspace-relative document at `path`, returning the
/// raw text alongside. The building block traversal, validation, and
/// mutation share.
pub(crate) async fn load(&self, path: &Path) -> Result<(String, Document)> {
// Clamp reads to the workspace root: `path` may originate in a document's
// own metadata (a `contents`/`part_of` target), so a hostile or careless
// `../../../etc/passwd` must be refused here rather than opened. The
// traversal turns this error into an `Unreadable` node; a direct caller
// sees the `Escape` error itself.
if link::escapes_root(path) {
return Err(crate::error::Error::Escape(path.to_path_buf()));
}
let text = self.fs().read_to_string(&self.root().join(path)).await?;
let doc = Document::parse(path, &text)?;
Ok((text, doc))
}
fn tree_node<'a>(
&'a self,
path: PathBuf,
label: Option<String>,
root: &'a Path,
titles: &'a mut Option<crate::title::TitleIndex>,
trail: &'a mut Vec<PathBuf>,
) -> Pin<Box<dyn Future<Output = Result<Node>> + 'a>> {
Box::pin(async move {
if trail.contains(&path) {
return Ok(Node {
path,
title: None,
label,
kind: NodeKind::Cycle,
children: Vec::new(),
});
}
match self.fs().try_exists(&self.root().join(&path)).await {
Ok(true) => {}
Ok(false) => {
return Ok(Node {
path,
title: None,
label,
kind: NodeKind::Missing,
children: Vec::new(),
});
}
Err(e) => {
return Ok(Node {
path,
title: None,
label,
kind: NodeKind::Unreadable(e.to_string()),
children: Vec::new(),
});
}
}
let doc = match self.load(&path).await {
Ok((_, doc)) => doc,
Err(e) => {
return Ok(Node {
path,
title: None,
label,
kind: NodeKind::Unreadable(e.to_string()),
children: Vec::new(),
});
}
};
let title = doc
.meta
.get("title")
.and_then(Value::as_str)
.map(str::to_owned);
trail.push(path.clone());
let mut children = Vec::new();
for raw in self.relations().children(&doc.meta) {
let child = Link::parse(&raw);
// Build the title index on first sight of a nominal link, never
// before — this is the only place the tree walk can need it.
if titles.is_none() && crate::title::is_alias_shaped(&child.target) {
*titles = Some(self.title_index_scoped(root).await?);
}
let child_path = match self.resolve_link_with(&path, &child, titles.as_ref()) {
Target::External => continue,
Target::UnresolvedId(id) => {
children.push(Node {
path: PathBuf::from(child.target.clone()),
title: None,
label: child.label,
kind: NodeKind::UnresolvedId(id),
children: Vec::new(),
});
continue;
}
Target::AmbiguousAlias(name) => {
children.push(Node {
path: PathBuf::from(name.clone()),
title: None,
label: child.label,
kind: NodeKind::AmbiguousAlias(name),
children: Vec::new(),
});
continue;
}
Target::Path(p) => p,
};
children.push(
self.tree_node(child_path, child.label, root, titles, trail)
.await?,
);
// (titles carried by &mut, so a nominal link deeper in the tree
// reuses the index built above rather than rescanning.)
}
trail.pop();
Ok(Node {
path,
title,
label,
kind: NodeKind::Doc,
children,
})
})
}
}
// These tests use YAML frontmatter fixtures, so they run under the `yaml` feature.
#[cfg(all(test, feature = "yaml"))]
mod tests {
use super::*;
use crate::exec::block_on;
use crate::fs::StdFs;
fn write(dir: &Path, rel: &str, text: &str) {
let p = dir.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
fn tempdir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("prov-tree-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn walks_the_spanning_tree_with_labels_and_titles() {
let dir = tempdir("walk");
write(
&dir,
"index.md",
"---\ntitle: Root\ncontents:\n- '[A](notes/a.md)'\n- missing.md\n---\n",
);
write(
&dir,
"notes/a.md",
"---\ntitle: A\npart_of: ../index.md\n---\n",
);
let ws = Workspace::builder(StdFs).root(&dir).build();
let root = block_on(ws.tree("index.md")).unwrap();
assert_eq!(root.title.as_deref(), Some("Root"));
assert_eq!(root.children.len(), 2);
assert_eq!(root.children[0].path, PathBuf::from("notes/a.md"));
assert_eq!(root.children[0].label.as_deref(), Some("A"));
assert_eq!(root.children[0].kind, NodeKind::Doc);
assert_eq!(root.children[1].kind, NodeKind::Missing);
}
#[test]
fn spanning_alias_links_resolve_through_the_title_index() {
// A workspace whose containment links are nominal `[[Title]]` aliases:
// the walk must resolve them through the title index and descend, and
// flag a name several documents share as ambiguous.
let dir = tempdir("alias");
write(
&dir,
"index.md",
"---\ntitle: Root\ncontents:\n- '[[Alpha]]'\n- '[[Dup]]'\n- '[[Ghost]]'\n---\n",
);
write(&dir, "notes/alpha.md", "---\ntitle: Alpha\n---\n");
write(&dir, "one.md", "---\ntitle: Dup\n---\n");
write(&dir, "two.md", "---\ntitle: Dup\n---\n");
let ws = Workspace::builder(StdFs).root(&dir).build();
let root = block_on(ws.tree("index.md")).unwrap();
assert_eq!(root.children.len(), 3);
// `[[Alpha]]` → the unique document titled Alpha, descended into.
assert_eq!(root.children[0].kind, NodeKind::Doc);
assert_eq!(root.children[0].path, PathBuf::from("notes/alpha.md"));
// `[[Dup]]` → two documents claim the title, so it cannot resolve.
assert_eq!(
root.children[1].kind,
NodeKind::AmbiguousAlias("Dup".into())
);
// `[[Ghost]]` → no document claims it; falls through to a missing path.
assert_eq!(root.children[2].kind, NodeKind::Missing);
}
#[test]
fn cycles_are_marked_not_followed() {
let dir = tempdir("cycle");
write(&dir, "a.md", "---\ncontents:\n- b.md\n---\n");
write(&dir, "b.md", "---\ncontents:\n- a.md\n---\n");
let ws = Workspace::builder(StdFs).root(&dir).build();
let root = block_on(ws.tree("a.md")).unwrap();
let b = &root.children[0];
assert_eq!(b.kind, NodeKind::Doc);
assert_eq!(b.children[0].kind, NodeKind::Cycle);
assert_eq!(b.children[0].path, PathBuf::from("a.md"));
}
}