1use camino::{Utf8Path, Utf8PathBuf};
15use serde::{Deserialize, Serialize};
16
17pub const REGISTRY_FILE: &str = "registry.yaml";
19pub const SOURCES_DIR: &str = "sources";
21pub const REGISTRY_SCHEMA: u32 = 1;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
26#[serde(rename_all = "kebab-case")]
27pub enum Status {
28 Pending,
30 Mapped,
32 Written,
34 Verified,
36 Dropped,
38}
39
40impl Status {
41 #[must_use]
43 pub const fn as_str(self) -> &'static str {
44 match self {
45 Self::Pending => "pending",
46 Self::Mapped => "mapped",
47 Self::Written => "written",
48 Self::Verified => "verified",
49 Self::Dropped => "dropped",
50 }
51 }
52
53 #[must_use]
55 pub const fn finished(self) -> bool {
56 matches!(self, Self::Verified | Self::Dropped)
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "kebab-case")]
63pub enum Kind {
64 Decision,
66 Spec,
68 Guide,
70 Metadata,
72 Document,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "kebab-case")]
79pub enum Placement {
80 Archived,
82 InPlace,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(deny_unknown_fields)]
89pub struct Event {
90 pub at: String,
92 pub status: Status,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub reason: Option<String>,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct Source {
103 pub id: String,
105 pub path: Utf8PathBuf,
107 pub sha256: String,
109 pub kind: Kind,
111 pub placement: Placement,
113 #[serde(default)]
115 pub tags: Vec<String>,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub group: Option<String>,
119 pub status: Status,
121 #[serde(default)]
123 pub history: Vec<Event>,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(deny_unknown_fields)]
129pub struct Group {
130 pub id: String,
132 #[serde(default)]
134 pub sources: Vec<String>,
135 #[serde(default)]
137 pub destinations: Vec<Utf8PathBuf>,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(deny_unknown_fields)]
143pub struct Registry {
144 pub schema_version: u32,
146 pub id: String,
148 pub base_commit: String,
150 pub sources: Vec<Source>,
152 #[serde(default)]
154 pub groups: Vec<Group>,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
159pub enum RegistryError {
160 #[error("the registry does not parse: {0}")]
162 Shape(String),
163 #[error("the registry names no source or group `{0}`")]
165 Unknown(String),
166 #[error("a source is dropped with its reason: pass --reason")]
168 NoReason,
169 #[error("{0}")]
171 Misplaced(String),
172 #[error("`{0}` is not a slug of lowercase letters, digits, and hyphens")]
174 NotASlug(String),
175}
176
177#[derive(Debug, Clone, Default, PartialEq, Eq)]
179pub struct Marking {
180 pub group: Option<String>,
182 pub tags: Vec<String>,
184 pub destinations: Vec<Utf8PathBuf>,
186 pub reason: Option<String>,
188}
189
190#[must_use]
192pub fn is_slug(value: &str) -> bool {
193 !value.is_empty()
194 && !value.starts_with('-')
195 && !value.ends_with('-')
196 && value
197 .bytes()
198 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
199}
200
201#[must_use]
203pub fn slug_of(path: &Utf8Path) -> String {
204 let mut out = String::new();
205 for character in path.as_str().chars() {
206 if character.is_ascii_alphanumeric() {
207 out.push(character.to_ascii_lowercase());
208 } else if !out.ends_with('-') && !out.is_empty() {
209 out.push('-');
210 }
211 }
212 out.trim_end_matches('-').to_string()
213}
214
215#[must_use]
218pub fn kind_of(path: &Utf8Path, metadata: bool) -> Kind {
219 if metadata {
220 return Kind::Metadata;
221 }
222 let name = path.file_name().unwrap_or_default();
223 let within = |names: &[&str]| {
224 path.parent().is_some_and(|parent| {
225 parent
226 .components()
227 .any(|part| names.contains(&part.as_str().to_ascii_lowercase().as_str()))
228 })
229 };
230 let shaped = |prefix: &str| {
231 name.starts_with(prefix) && path.extension().is_some_and(|extension| extension == "md")
232 };
233 if shaped("ADR-") || within(&["decisions", "adr", "adrs"]) {
234 Kind::Decision
235 } else if shaped("SPEC-") || within(&["specs"]) {
236 Kind::Spec
237 } else if within(&["guides"]) {
238 Kind::Guide
239 } else {
240 Kind::Document
241 }
242}
243
244impl Registry {
245 pub fn parse(text: &str) -> Result<Self, RegistryError> {
252 let parsed: Self =
253 yaml_serde::from_str(text).map_err(|error| RegistryError::Shape(error.to_string()))?;
254 if parsed.schema_version != REGISTRY_SCHEMA {
255 return Err(RegistryError::Shape(format!(
256 "schema_version {} is not {REGISTRY_SCHEMA}",
257 parsed.schema_version
258 )));
259 }
260 Ok(parsed)
261 }
262
263 pub fn render(&self) -> Result<String, RegistryError> {
269 yaml_serde::to_string(self).map_err(|error| RegistryError::Shape(error.to_string()))
270 }
271
272 pub fn mark(
284 &mut self,
285 target: &str,
286 status: Status,
287 marking: &Marking,
288 at: &str,
289 ) -> Result<Vec<String>, RegistryError> {
290 if status == Status::Dropped && marking.reason.is_none() {
291 return Err(RegistryError::NoReason);
292 }
293 for slug in marking.group.iter().chain(&marking.tags) {
294 if !is_slug(slug) {
295 return Err(RegistryError::NotASlug(slug.clone()));
296 }
297 }
298 let event = Event {
299 at: at.to_string(),
300 status,
301 reason: marking.reason.clone(),
302 };
303 if let Some(index) = self.groups.iter().position(|group| group.id == target) {
304 if marking.group.is_some() || !marking.tags.is_empty() {
305 return Err(RegistryError::Misplaced(format!(
306 "`{target}` is a group; --group and --tag file a single source"
307 )));
308 }
309 for destination in &marking.destinations {
310 if !self.groups[index].destinations.contains(destination) {
311 self.groups[index].destinations.push(destination.clone());
312 }
313 }
314 let members = self.groups[index].sources.clone();
315 for source in &mut self.sources {
316 if members.contains(&source.id) {
317 source.status = status;
318 source.history.push(event.clone());
319 }
320 }
321 return Ok(members);
322 }
323 let index = self
324 .sources
325 .iter()
326 .position(|source| source.id == target || source.path.as_str() == target)
327 .ok_or_else(|| RegistryError::Unknown(target.to_string()))?;
328 if !marking.destinations.is_empty() {
329 return Err(RegistryError::Misplaced(format!(
330 "`{target}` is a source; --destination belongs to its group"
331 )));
332 }
333 let id = self.sources[index].id.clone();
334 if let Some(group) = &marking.group {
335 for existing in &mut self.groups {
336 existing.sources.retain(|member| *member != id);
337 }
338 match self
339 .groups
340 .iter_mut()
341 .find(|existing| existing.id == *group)
342 {
343 Some(existing) => existing.sources.push(id.clone()),
344 None => self.groups.push(Group {
345 id: group.clone(),
346 sources: vec![id.clone()],
347 destinations: Vec::new(),
348 }),
349 }
350 self.sources[index].group = Some(group.clone());
351 }
352 let source = &mut self.sources[index];
353 for tag in &marking.tags {
354 if !source.tags.contains(tag) {
355 source.tags.push(tag.clone());
356 }
357 }
358 source.status = status;
359 source.history.push(event);
360 Ok(vec![id])
361 }
362
363 #[must_use]
369 pub fn unfinished(&self, exists: impl Fn(&Utf8Path) -> bool) -> Vec<String> {
370 let mut reasons = Vec::new();
371 for source in &self.sources {
372 if !source.status.finished() {
373 reasons.push(format!("{} is {}", source.id, source.status.as_str()));
374 continue;
375 }
376 if source.status == Status::Dropped {
377 continue;
378 }
379 let group = source
380 .group
381 .as_ref()
382 .and_then(|id| self.groups.iter().find(|group| group.id == *id));
383 match group {
384 None => reasons.push(format!("{} is verified and filed in no group", source.id)),
385 Some(group) if group.destinations.is_empty() => reasons.push(format!(
386 "{} is verified and its group {} names no destination",
387 source.id, group.id
388 )),
389 Some(group) => {
390 for destination in &group.destinations {
391 if !exists(destination) {
392 reasons.push(format!(
393 "{}: the destination {destination} does not exist",
394 group.id
395 ));
396 }
397 }
398 }
399 }
400 }
401 reasons.sort();
402 reasons.dedup();
403 reasons
404 }
405}
406
407#[cfg(test)]
408mod tests {
409 use super::*;
410
411 fn registry() -> Registry {
412 let source = |id: &str, path: &str| Source {
413 id: id.to_string(),
414 path: Utf8PathBuf::from(path),
415 sha256: "00".to_string(),
416 kind: Kind::Decision,
417 placement: Placement::Archived,
418 tags: Vec::new(),
419 group: None,
420 status: Status::Pending,
421 history: Vec::new(),
422 };
423 Registry {
424 schema_version: REGISTRY_SCHEMA,
425 id: "20261009T213000Z".to_string(),
426 base_commit: "4f1c2e0".to_string(),
427 sources: vec![
428 source("docs-adr-0003-md", "docs/adr/0003.md"),
429 source("docs-adr-0007-md", "docs/adr/0007.md"),
430 ],
431 groups: Vec::new(),
432 }
433 }
434
435 #[test]
436 fn a_path_reads_as_one_slug() {
437 assert_eq!(
438 slug_of(Utf8Path::new("docs/adr/0007-Use Postgres.md")),
439 "docs-adr-0007-use-postgres-md"
440 );
441 }
442
443 #[test]
444 fn a_kind_is_read_from_the_name_and_the_home() {
445 assert_eq!(
446 kind_of(Utf8Path::new("docs/adr/0007.md"), false),
447 Kind::Decision
448 );
449 assert_eq!(kind_of(Utf8Path::new("x/SPEC-a.md"), false), Kind::Spec);
450 assert_eq!(
451 kind_of(Utf8Path::new("docs/guides/a.md"), false),
452 Kind::Guide
453 );
454 assert_eq!(kind_of(Utf8Path::new("README.md"), true), Kind::Metadata);
455 assert_eq!(
456 kind_of(Utf8Path::new("docs/intro.md"), false),
457 Kind::Document
458 );
459 }
460
461 #[test]
463 fn mark_appends_history_and_never_rewrites_an_earlier_entry() {
464 let mut registry = registry();
465 let filing = Marking {
466 group: Some("storage".to_string()),
467 tags: vec!["storage".to_string()],
468 ..Marking::default()
469 };
470 registry
471 .mark("docs-adr-0003-md", Status::Mapped, &filing, "t1")
472 .unwrap();
473 registry
474 .mark("docs/adr/0007.md", Status::Mapped, &filing, "t2")
475 .unwrap();
476 let first = registry.sources[0].history.clone();
477 let destinations = Marking {
478 destinations: vec![Utf8PathBuf::from("_docs/decisions/ADR-store-state.md")],
479 ..Marking::default()
480 };
481 let marked = registry
482 .mark("storage", Status::Verified, &destinations, "t3")
483 .unwrap();
484 assert_eq!(marked, ["docs-adr-0003-md", "docs-adr-0007-md"]);
485 assert_eq!(registry.sources[0].history[..1], first[..]);
486 assert_eq!(registry.sources[0].history.len(), 2);
487 assert_eq!(registry.groups[0].sources.len(), 2);
488 assert_eq!(registry.groups[0].destinations.len(), 1);
489 }
490
491 #[test]
492 fn a_drop_needs_its_reason_and_a_refusal_changes_nothing() {
493 let mut registry = registry();
494 let before = registry.clone();
495 assert_eq!(
496 registry.mark(
497 "docs-adr-0003-md",
498 Status::Dropped,
499 &Marking::default(),
500 "t"
501 ),
502 Err(RegistryError::NoReason)
503 );
504 assert!(
505 registry
506 .mark("nope", Status::Mapped, &Marking::default(), "t")
507 .is_err()
508 );
509 assert_eq!(registry, before);
510 let reason = Marking {
511 reason: Some("superseded by 0007".to_string()),
512 ..Marking::default()
513 };
514 registry
515 .mark("docs-adr-0003-md", Status::Dropped, &reason, "t")
516 .unwrap();
517 let text = registry.render().unwrap();
518 assert_eq!(Registry::parse(&text).unwrap(), registry);
519 }
520
521 #[test]
523 fn close_waits_for_every_source_and_every_destination() {
524 let mut registry = registry();
525 assert_eq!(registry.unfinished(|_| true).len(), 2);
526 let filing = Marking {
527 group: Some("storage".to_string()),
528 ..Marking::default()
529 };
530 registry
531 .mark("docs-adr-0003-md", Status::Verified, &filing, "t")
532 .unwrap();
533 registry
534 .mark("docs-adr-0007-md", Status::Verified, &filing, "t")
535 .unwrap();
536 assert!(
537 !registry.unfinished(|_| true).is_empty(),
538 "no destination yet"
539 );
540 let destinations = Marking {
541 destinations: vec![Utf8PathBuf::from("ADR-x.md")],
542 ..Marking::default()
543 };
544 registry
545 .mark("storage", Status::Verified, &destinations, "t")
546 .unwrap();
547 assert!(
548 !registry.unfinished(|_| false).is_empty(),
549 "the file is absent"
550 );
551 assert!(registry.unfinished(|_| true).is_empty());
552 }
553
554 #[test]
556 fn a_group_with_no_live_source_does_not_block_close() {
557 let mut registry = registry();
558 let into = |group: &str| Marking {
559 group: Some(group.to_string()),
560 ..Marking::default()
561 };
562 let aimed = |path: &str| Marking {
563 destinations: vec![Utf8PathBuf::from(path)],
564 ..Marking::default()
565 };
566 registry
569 .mark("docs-adr-0003-md", Status::Mapped, &into("first"), "t")
570 .unwrap();
571 registry
572 .mark("first", Status::Mapped, &aimed("gone.md"), "t")
573 .unwrap();
574 registry
575 .mark("docs-adr-0003-md", Status::Verified, &into("kept"), "t")
576 .unwrap();
577 registry
578 .mark("kept", Status::Verified, &aimed("kept.md"), "t")
579 .unwrap();
580 registry
581 .mark("docs-adr-0007-md", Status::Mapped, &into("dropped"), "t")
582 .unwrap();
583 registry
584 .mark("dropped", Status::Mapped, &aimed("never.md"), "t")
585 .unwrap();
586 let reason = Marking {
587 reason: Some("said elsewhere".to_string()),
588 ..Marking::default()
589 };
590 registry
591 .mark("docs-adr-0007-md", Status::Dropped, &reason, "t")
592 .unwrap();
593 assert!(
594 registry
595 .unfinished(|path| path == Utf8Path::new("kept.md"))
596 .is_empty()
597 );
598 }
599}