1use std::collections::BTreeMap;
51
52use camino::Utf8Path;
53use serde::{Deserialize, Serialize};
54
55use crate::domain::gate_id::GateId;
56use crate::domain::path_filter::{Layer, PathFilter, PathFilterError, Pattern};
57
58pub use crate::domain::paths::CONFIG_PATH;
59
60#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
62#[serde(deny_unknown_fields)]
63pub struct GateFilters {
64 #[serde(default)]
66 pub include: Vec<String>,
67 #[serde(default)]
69 pub exclude: Vec<String>,
70}
71
72#[derive(Debug, Default, Clone, Copy, Deserialize, PartialEq, Eq)]
74#[serde(rename_all = "lowercase")]
75pub enum WritingSource {
76 #[default]
78 Builtin,
79 Project,
81 None,
83}
84
85#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
87#[serde(deny_unknown_fields)]
88pub struct WritingStyle {
89 #[serde(default)]
91 pub source: WritingSource,
92 #[serde(default)]
95 pub path: Option<String>,
96}
97
98impl WritingStyle {
99 pub fn parse_flag(value: &str) -> Result<Self, ConfigError> {
107 let selection = match value.trim() {
108 "builtin" => Self::default(),
109 "none" => Self {
110 source: WritingSource::None,
111 path: None,
112 },
113 other => match other.strip_prefix("project:") {
114 Some(path) => Self {
115 source: WritingSource::Project,
116 path: Some(path.trim().to_string()),
117 },
118 None => {
119 return Err(ConfigError::WritingStyle(format!(
120 "`{other}` is not a selection; write `builtin`, `none`, or `project:<path>`"
121 )));
122 }
123 },
124 };
125 selection.check()?;
126 Ok(selection)
127 }
128
129 fn check(&self) -> Result<(), ConfigError> {
131 match (self.source, self.path.as_deref()) {
132 (WritingSource::Project, None | Some("")) => Err(ConfigError::WritingStyle(
133 "`source: project` names no `path`".to_string(),
134 )),
135 (WritingSource::Builtin | WritingSource::None, Some(path)) if !path.is_empty() => {
136 Err(ConfigError::WritingStyle(format!(
137 "`path: {path}` is set and the source is not `project`, so nothing reads it"
138 )))
139 }
140 (WritingSource::Project, Some(path)) => {
141 let candidate = Utf8Path::new(path);
142 if candidate.is_absolute() {
143 return Err(ConfigError::WritingStyle(format!(
144 "`path: {path}` is absolute; name the document relative to the repository"
145 )));
146 }
147 if candidate.components().any(|part| part.as_str() == "..") {
148 return Err(ConfigError::WritingStyle(format!(
149 "`path: {path}` leaves the repository"
150 )));
151 }
152 Ok(())
153 }
154 _ => Ok(()),
155 }
156 }
157
158 #[must_use]
161 pub fn route(&self) -> Option<String> {
162 match self.source {
163 WritingSource::Builtin => Some("`sdd method writing-style`".to_string()),
164 WritingSource::Project => self.path.as_ref().map(|path| format!("`{path}`")),
165 WritingSource::None => None,
166 }
167 }
168
169 #[must_use]
171 pub fn render(&self) -> String {
172 let source = match self.source {
173 WritingSource::Builtin => "builtin",
174 WritingSource::Project => "project",
175 WritingSource::None => "none",
176 };
177 let path = self
178 .path
179 .as_deref()
180 .filter(|path| !path.is_empty())
181 .map_or_else(|| "null".to_string(), quoted);
182 format!("writing_style:\n source: {source}\n path: {path}\n")
183 }
184}
185
186#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
188#[serde(rename_all = "lowercase")]
189pub enum AcquisitionSource {
190 Host,
192}
193
194#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
196#[serde(deny_unknown_fields)]
197pub struct Acquisition {
198 pub source: AcquisitionSource,
200 pub minimum: String,
202}
203
204impl Acquisition {
205 #[must_use]
207 pub fn host_at_this_release() -> Self {
208 Self {
209 source: AcquisitionSource::Host,
210 minimum: crate::domain::version::CanonVersion::current().to_string(),
211 }
212 }
213
214 fn check(&self) -> Result<(), ConfigError> {
216 self.minimum
217 .parse::<crate::domain::version::CanonVersion>()
218 .map(|_| ())
219 .map_err(|_| {
220 ConfigError::Acquisition(format!(
221 "`minimum: {}` is not a release version such as `0.13.2`",
222 self.minimum
223 ))
224 })
225 }
226
227 #[must_use]
229 pub fn render(&self) -> String {
230 let source = match self.source {
231 AcquisitionSource::Host => "host",
232 };
233 format!(
234 "acquisition:\n source: {source}\n minimum: {}\n",
235 quoted(&self.minimum)
236 )
237 }
238}
239
240#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
242#[serde(deny_unknown_fields)]
243pub struct InstanceConfig {
244 #[serde(default)]
250 pub reserved: Vec<String>,
251 #[serde(default)]
254 pub gates: BTreeMap<String, GateFilters>,
255 #[serde(default)]
258 pub writing_style: WritingStyle,
259 #[serde(default)]
262 pub acquisition: Option<Acquisition>,
263 #[serde(default)]
266 pub migration: Option<String>,
267}
268
269#[derive(Debug, thiserror::Error)]
271pub enum ConfigError {
272 #[error("{CONFIG_PATH} does not parse: {0}")]
274 Shape(String),
275 #[error(
277 "{CONFIG_PATH} names the gate `{0}`, which this version does not deliver: `sdd gate --list` names every one"
278 )]
279 UnknownGate(String),
280 #[error("{CONFIG_PATH}: {0}")]
282 Pattern(#[from] PathFilterError),
283 #[error("{CONFIG_PATH}: writing_style: {0}")]
285 WritingStyle(String),
286 #[error("{CONFIG_PATH}: acquisition: {0}")]
288 Acquisition(String),
289 #[error(
291 "{CONFIG_PATH}: migration: `{0}` is not a migration id such as `20261009T213000Z` or `20261009T213000Z-2` (setup:an-open-migration-is-declared)"
292 )]
293 Migration(String),
294}
295
296impl InstanceConfig {
297 pub fn parse(text: &str) -> Result<Self, ConfigError> {
306 let parsed: Self =
307 yaml_serde::from_str(text).map_err(|error| ConfigError::Shape(error.to_string()))?;
308 for key in parsed.gates.keys() {
309 if resolve_id(key).is_none() {
310 return Err(ConfigError::UnknownGate(key.clone()));
311 }
312 }
313 parsed.check_patterns()?;
318 parsed.writing_style.check()?;
319 if let Some(acquisition) = &parsed.acquisition {
320 acquisition.check()?;
321 }
322 if let Some(id) = &parsed.migration
323 && !is_migration_id(id)
324 {
325 return Err(ConfigError::Migration(id.clone()));
326 }
327 Ok(parsed)
328 }
329
330 pub fn read(repo_root: &Utf8Path) -> Result<Self, ConfigError> {
340 let path = repo_root.join(CONFIG_PATH);
341 match std::fs::read_to_string(&path) {
342 Ok(text) => Self::parse(&text),
343 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
344 Err(error) => Err(ConfigError::Shape(error.to_string())),
345 }
346 }
347
348 fn check_patterns(&self) -> Result<(), ConfigError> {
354 let every = self.reserved.iter().chain(
355 self.gates
356 .values()
357 .flat_map(|filters| filters.include.iter().chain(&filters.exclude)),
358 );
359 for glob in every {
360 PathFilter::build(Vec::new(), vec![Pattern::new(glob.clone(), Layer::Project)])?;
361 }
362 Ok(())
363 }
364
365 #[must_use]
367 pub fn for_gate(&self, id: GateId) -> Option<&GateFilters> {
368 self.gates.get(&id.to_string())
369 }
370}
371
372fn resolve_id(key: &str) -> Option<GateId> {
374 GateId::ALL.iter().copied().find(|id| id.to_string() == key)
375}
376
377pub fn resolve(
387 registry_include: &[String],
388 registry_exclude: &[String],
389 declared: Option<&GateFilters>,
390 flag_include: &[String],
391 flag_exclude: &[String],
392 reserved: &[String],
393) -> Result<PathFilter, ConfigError> {
394 let includes: Vec<Pattern> = declared.filter(|d| !d.include.is_empty()).map_or_else(
397 || {
398 registry_include
399 .iter()
400 .map(|glob| Pattern::new(glob.clone(), Layer::Registry))
401 .collect()
402 },
403 |declared| {
404 declared
405 .include
406 .iter()
407 .map(|glob| Pattern::new(glob.clone(), Layer::Project))
408 .collect()
409 },
410 );
411 let includes = includes
412 .into_iter()
413 .chain(
414 flag_include
415 .iter()
416 .map(|glob| Pattern::new(glob.clone(), Layer::Flag)),
417 )
418 .collect();
419
420 let excludes: Vec<Pattern> = registry_exclude
423 .iter()
424 .map(|glob| Pattern::new(glob.clone(), Layer::Registry))
425 .chain(
426 declared
427 .into_iter()
428 .flat_map(|d| &d.exclude)
429 .map(|glob| Pattern::new(glob.clone(), Layer::Project)),
430 )
431 .chain(
432 flag_exclude
433 .iter()
434 .map(|glob| Pattern::new(glob.clone(), Layer::Flag)),
435 )
436 .chain(
437 reserved
438 .iter()
439 .map(|glob| Pattern::new(glob.clone(), Layer::Reserved)),
440 )
441 .collect();
442
443 Ok(PathFilter::build(includes, excludes)?)
444}
445
446fn quoted(glob: &str) -> String {
454 format!("'{}'", glob.replace('\'', "''"))
455}
456
457#[must_use]
462pub fn with_writing_style(text: &str, selection: &WritingStyle) -> String {
463 with_block(
464 text,
465 "writing_style:",
466 &selection.render(),
467 "# Where the writing style comes from: `builtin` routes authors to\n\
468 # `sdd method writing-style`, `project` routes them to the document\n\
469 # `path` names, and `none` installs no route and imposes no conversion\n\
470 # obligation.\n",
471 )
472}
473
474#[must_use]
478pub fn with_acquisition(text: &str, decision: &Acquisition) -> String {
479 with_block(
480 text,
481 "acquisition:",
482 &decision.render(),
483 "# How every host obtains sdd. `source: host` means each host installs\n\
484 # it itself, at `minimum` or newer, because no manager file records a\n\
485 # pin for this repository.\n",
486 )
487}
488
489#[must_use]
495pub fn is_migration_id(id: &str) -> bool {
496 let (stamp, counter) = id
497 .split_once('-')
498 .map_or((id, None), |(stamp, n)| (stamp, Some(n)));
499 let bytes = stamp.as_bytes();
500 let digits = |range: std::ops::Range<usize>| bytes[range].iter().all(u8::is_ascii_digit);
501 let stamped =
502 bytes.len() == 16 && digits(0..8) && bytes[8] == b'T' && digits(9..15) && bytes[15] == b'Z';
503 let numbered = counter.is_none_or(|n| {
504 !n.is_empty()
505 && !n.starts_with('0')
506 && n.bytes().all(|b| b.is_ascii_digit())
507 && n.parse::<u32>().is_ok_and(|n| n >= 2)
508 });
509 stamped && numbered
510}
511
512const MIGRATION_COMMENT: &str = "# The migration this repository holds open. Its archive and registry\n\
514 # live under this id in the state root of sdd, and `sdd migrate close`\n\
515 # removes this key.\n";
516
517#[must_use]
521pub fn with_migration(text: &str, id: &str) -> String {
522 with_block(
523 text,
524 "migration:",
525 &format!("{}\n", migration_line(id)),
526 MIGRATION_COMMENT,
527 )
528}
529
530#[must_use]
534pub fn migration_line(id: &str) -> String {
535 format!("migration: {}", quoted(id))
536}
537
538#[must_use]
542pub fn without_migration(text: &str) -> String {
543 let lines: Vec<&str> = text.lines().collect();
544 let Some(key) = lines.iter().position(|line| line.starts_with("migration:")) else {
545 return text.to_string();
546 };
547 let mut end = key + 1;
548 while end < lines.len() && (lines[end].starts_with(' ') || lines[end].starts_with('\t')) {
549 end += 1;
550 }
551 let comment: Vec<&str> = MIGRATION_COMMENT.lines().collect();
552 let mut start = key;
553 if key >= comment.len() && lines[key - comment.len()..key] == comment[..] {
554 start = key - comment.len();
555 if start > 0 && lines[start - 1].is_empty() {
556 start -= 1;
557 }
558 }
559 let mut out = String::new();
560 for line in lines[..start].iter().chain(&lines[end..]) {
561 out.push_str(line);
562 out.push('\n');
563 }
564 out
565}
566
567fn with_block(text: &str, key: &str, block: &str, comment: &str) -> String {
570 let mut out = String::new();
571 let mut wrote = false;
572 let mut skipping = false;
573 for line in text.lines() {
574 if skipping {
575 if line.starts_with(' ') || line.starts_with('\t') {
576 continue;
577 }
578 skipping = false;
579 }
580 if !wrote && line.starts_with(key) {
581 out.push_str(block);
582 wrote = true;
583 skipping = true;
584 continue;
585 }
586 out.push_str(line);
587 out.push('\n');
588 }
589 if !wrote {
590 if !out.is_empty() && !out.ends_with("\n\n") {
591 out.push('\n');
592 }
593 out.push_str(comment);
594 out.push_str(block);
595 }
596 out
597}
598
599#[must_use]
606pub fn with_reserved(text: &str, paths: &[String]) -> String {
607 if paths.is_empty() {
608 return text.to_string();
609 }
610 let existing = InstanceConfig::parse(text).unwrap_or_default().reserved;
611 let mut added: Vec<&String> = paths
612 .iter()
613 .filter(|path| !existing.contains(path))
614 .collect();
615 added.dedup();
616 if added.is_empty() {
617 return text.to_string();
618 }
619
620 let entries: String = existing
621 .iter()
622 .map(|path| format!(" - {}\n", quoted(path)))
623 .chain(added.iter().map(|path| format!(" - {}\n", quoted(path))))
624 .collect();
625
626 let mut out = String::new();
627 let mut wrote = false;
628 let mut skipping = false;
629 for line in text.lines() {
630 if skipping {
631 if line.starts_with(" - ") || line.trim().is_empty() && !wrote {
633 continue;
634 }
635 skipping = false;
636 }
637 if !wrote && (line.starts_with("reserved:")) {
638 out.push_str("reserved:\n");
639 out.push_str(&entries);
640 wrote = true;
641 skipping = true;
642 continue;
643 }
644 out.push_str(line);
645 out.push('\n');
646 }
647 if !wrote {
648 out.push_str("reserved:\n");
649 out.push_str(&entries);
650 }
651 out
652}
653
654#[cfg(test)]
655mod tests {
656 use super::*;
657 use crate::domain::path_filter::Decision;
658
659 fn config(text: &str) -> InstanceConfig {
660 InstanceConfig::parse(text).expect("the fixture parses")
661 }
662
663 #[test]
664 fn an_absent_file_is_the_empty_declaration() {
665 let dir = tempfile::tempdir().expect("a scratch directory");
666 let root = camino::Utf8PathBuf::from_path_buf(dir.path().to_path_buf())
667 .expect("the scratch path is UTF-8");
668 let read = InstanceConfig::read(&root).expect("an absent file is not an error");
669 assert_eq!(read, InstanceConfig::default());
670 }
671
672 #[test]
673 fn an_empty_file_is_the_empty_declaration() {
674 assert_eq!(config("{}\n"), InstanceConfig::default());
675 }
676
677 #[test]
678 fn a_malformed_key_is_an_error_naming_the_key() {
679 let error = InstanceConfig::parse("reserved: AGENTS.md\n")
680 .expect_err("a scalar where a list belongs is refused");
681 assert!(
682 error.to_string().contains("reserved"),
683 "the error does not name the key: {error}"
684 );
685 }
686
687 #[test]
688 fn an_open_migration_round_trips_to_the_bytes_it_started_from() {
689 let seed = "# What the gates judge.\nreserved: []\n";
690 let open = with_migration(seed, "20261009T213000Z");
691 assert_eq!(config(&open).migration.as_deref(), Some("20261009T213000Z"));
692 assert_eq!(without_migration(&open), seed);
693 assert_eq!(without_migration(seed), seed);
694 assert!(InstanceConfig::parse("migration: '20261009T213000Z-2'\n").is_ok());
695 assert!(InstanceConfig::parse("migration: '20261009T213000Z-12'\n").is_ok());
696 for refused in [
697 "../x",
698 "20261009T213000Z-1",
699 "20261009T213000Z-0",
700 "20261009T213000Z-02",
701 "20261009T213000Z-",
702 "20261009T213000",
703 "2026100XT213000Z",
704 "20261009T213000Z/..",
705 "20261009T14020é",
706 "20261009T1402é0Z",
707 "20261009T213000Z-é",
708 "ééééééééééééééé",
709 ] {
710 let error =
711 InstanceConfig::parse(&format!("migration: '{refused}'\n")).expect_err(refused);
712 assert!(
713 error
714 .to_string()
715 .contains("setup:an-open-migration-is-declared"),
716 "{error}"
717 );
718 }
719 }
720
721 #[test]
722 fn a_host_decision_parses_renders_and_reads_back() {
723 let decision = Acquisition {
724 source: AcquisitionSource::Host,
725 minimum: "0.13.2".to_string(),
726 };
727 let text = with_acquisition("reserved: []\n", &decision);
728 assert!(text.contains("# How every host obtains sdd."), "{text}");
729 assert_eq!(config(&text).acquisition, Some(decision.clone()));
730 let moved = Acquisition {
732 minimum: "0.14.0".to_string(),
733 ..decision
734 };
735 let again = with_acquisition(&text, &moved);
736 assert_eq!(again.matches("acquisition:").count(), 1, "{again}");
737 assert_eq!(config(&again).acquisition, Some(moved));
738 }
739
740 #[test]
741 fn an_acquisition_this_version_cannot_read_is_refused() {
742 assert!(InstanceConfig::parse("acquisition:\n source: host\n minimum: soon\n").is_err());
743 assert!(
744 InstanceConfig::parse("acquisition:\n source: brew\n minimum: '0.1.0'\n").is_err()
745 );
746 assert!(InstanceConfig::parse("acquisition:\n source: host\n").is_err());
747 }
748
749 #[test]
750 fn an_unknown_key_is_refused() {
751 assert!(InstanceConfig::parse("reservd:\n - a.md\n").is_err());
752 }
753
754 #[test]
755 fn an_unknown_gate_id_is_an_error_naming_the_key() {
756 let error = InstanceConfig::parse("gates:\n no-such-gate:\n exclude: [a]\n")
757 .expect_err("an unknown gate is refused");
758 assert!(matches!(error, ConfigError::UnknownGate(ref key) if key == "no-such-gate"));
759 }
760
761 #[test]
762 fn a_known_gate_id_parses() {
763 let parsed = config("gates:\n no-personal-path:\n exclude:\n - vendor/**\n");
764 assert_eq!(
765 parsed
766 .for_gate(GateId::NoPersonalPath)
767 .map(|f| f.exclude.clone()),
768 Some(vec!["vendor/**".to_string()])
769 );
770 }
771
772 #[test]
773 fn a_path_leaving_the_repository_is_refused() {
774 let error = resolve(&[], &[], None, &[], &[], &["../outside/**".to_string()])
775 .expect_err("a pattern that climbs out is refused");
776 assert!(matches!(error, ConfigError::Pattern(_)));
777 }
778
779 #[test]
780 fn a_project_include_replaces_the_registry_include() {
781 let filter = resolve(
782 &["_docs/**/*.md".to_string()],
783 &[],
784 Some(&GateFilters {
785 include: vec!["method/**/*.md".to_string()],
786 exclude: Vec::new(),
787 }),
788 &[],
789 &[],
790 &[],
791 )
792 .expect("resolves");
793 assert_eq!(
794 filter.decide(Utf8Path::new("method/gates.md")),
795 Decision::Read
796 );
797 assert_eq!(
798 filter.decide(Utf8Path::new("_docs/specs/SPEC-a.md")),
799 Decision::NotIncluded,
800 "the registry include survived a project include that replaces it"
801 );
802 }
803
804 #[test]
805 fn every_exclude_layer_extends() {
806 let filter = resolve(
807 &[],
808 &["a.md".to_string()],
809 Some(&GateFilters {
810 include: Vec::new(),
811 exclude: vec!["b.md".to_string()],
812 }),
813 &[],
814 &["c.md".to_string()],
815 &["d.md".to_string()],
816 )
817 .expect("resolves");
818 for path in ["a.md", "b.md", "c.md", "d.md"] {
819 assert!(
820 matches!(filter.decide(Utf8Path::new(path)), Decision::Skipped(_)),
821 "{path} survived its exclude layer"
822 );
823 }
824 }
825
826 #[test]
827 fn reserved_wins_over_a_gate_entry_that_includes_it() {
828 let filter = resolve(
829 &[],
830 &[],
831 Some(&GateFilters {
832 include: vec!["AGENTS.md".to_string()],
833 exclude: Vec::new(),
834 }),
835 &[],
836 &[],
837 &["AGENTS.md".to_string()],
838 )
839 .expect("resolves");
840 match filter.decide(Utf8Path::new("AGENTS.md")) {
841 Decision::Skipped(pattern) => assert_eq!(pattern.layer, Layer::Reserved),
842 other => panic!("reserved did not win: {other:?}"),
843 }
844 }
845
846 #[test]
847 fn reserving_a_path_keeps_every_comment() {
848 let seed = "# why this file exists\nreserved: []\n\n# per gate\ngates: {}\n";
849 let out = with_reserved(seed, &["AGENTS.md".to_string()]);
850 assert!(
851 out.contains("# why this file exists"),
852 "a comment was lost:\n{out}"
853 );
854 assert!(out.contains("# per gate"), "a comment was lost:\n{out}");
855 assert!(
856 out.contains(" - 'AGENTS.md'"),
857 "the path is missing:\n{out}"
858 );
859 assert_eq!(
860 InstanceConfig::parse(&out).expect("still parses").reserved,
861 vec!["AGENTS.md".to_string()]
862 );
863 }
864
865 #[test]
866 fn reserving_a_recorded_path_changes_nothing() {
867 let text = "reserved:\n - 'AGENTS.md'\ngates: {}\n";
868 assert_eq!(with_reserved(text, &["AGENTS.md".to_string()]), text);
869 }
870
871 #[test]
872 fn a_glob_is_written_as_a_yaml_scalar_that_reads_back() {
873 for glob in ["**/generated.md", "[ab]/x.md", "{a,b}/x.md", "it's/x.md"] {
876 let out = with_reserved("reserved: []\ngates: {}\n", &[glob.to_string()]);
877 assert_eq!(
878 InstanceConfig::parse(&out)
879 .unwrap_or_else(|e| panic!("{glob} did not read back: {e}"))
880 .reserved,
881 vec![glob.to_string()],
882 "for {glob}"
883 );
884 }
885 }
886
887 #[test]
888 fn a_refused_pattern_fails_at_the_declaration_boundary() {
889 let error = InstanceConfig::parse("reserved:\n - '!negated'\ngates: {}\n")
891 .expect_err("a negation is refused at parse");
892 assert!(matches!(error, ConfigError::Pattern(_)));
893 assert!(
894 InstanceConfig::parse("gates:\n no-personal-path:\n exclude: ['a[']\n").is_err()
895 );
896 }
897
898 #[test]
899 fn reserving_adds_beside_what_is_recorded() {
900 let text = "reserved:\n - AGENTS.md\ngates: {}\n";
901 let out = with_reserved(text, &["vendor/**".to_string()]);
902 assert_eq!(
903 InstanceConfig::parse(&out).expect("parses").reserved,
904 vec!["AGENTS.md".to_string(), "vendor/**".to_string()]
905 );
906 }
907
908 #[test]
909 fn an_absent_key_is_builtin() {
910 assert_eq!(
911 config("reserved: []\ngates: {}\n").writing_style,
912 WritingStyle::default()
913 );
914 assert_eq!(
915 config("writing_style:\n source: builtin\n path: null\n")
916 .writing_style
917 .route(),
918 Some("`sdd method writing-style`".to_string())
919 );
920 }
921
922 #[test]
923 fn project_without_a_path_is_an_error_naming_the_key() {
924 let error = InstanceConfig::parse("writing_style:\n source: project\n")
925 .expect_err("a project source needs a path");
926 assert!(matches!(error, ConfigError::WritingStyle(_)));
927 assert!(error.to_string().contains("writing_style"), "{error}");
928 assert!(error.to_string().contains("path"), "{error}");
929 }
930
931 #[test]
932 fn a_path_without_the_project_source_is_an_error() {
933 for source in ["builtin", "none"] {
934 let error = InstanceConfig::parse(&format!(
935 "writing_style:\n source: {source}\n path: docs/style.md\n"
936 ))
937 .expect_err("a path nothing reads is refused");
938 assert!(error.to_string().contains("nothing reads it"), "{error}");
939 }
940 }
941
942 #[test]
943 fn a_writing_style_path_leaving_the_repository_is_refused() {
944 for path in ["/etc/style.md", "../style.md", "docs/../../style.md"] {
945 assert!(
946 WritingStyle::parse_flag(&format!("project:{path}")).is_err(),
947 "{path} was accepted"
948 );
949 }
950 assert_eq!(
951 WritingStyle::parse_flag("project:docs/STYLE.md")
952 .unwrap()
953 .route(),
954 Some("`docs/STYLE.md`".to_string())
955 );
956 assert_eq!(WritingStyle::parse_flag("none").unwrap().route(), None);
957 assert!(WritingStyle::parse_flag("house").is_err());
958 }
959
960 #[test]
961 fn a_selection_is_written_into_the_declaration_and_reads_back() {
962 let seed = "reserved: []\n\n# how to write\nwriting_style:\n source: builtin\n path: null\n\ngates: {}\n";
963 let selection = WritingStyle::parse_flag("project:docs/STYLE.md").unwrap();
964 let out = with_writing_style(seed, &selection);
965 assert!(out.contains("# how to write"), "a comment was lost:\n{out}");
966 assert!(out.contains("gates: {}"), "a later key was lost:\n{out}");
967 assert_eq!(config(&out).writing_style, selection);
968
969 let older = "reserved: []\ngates: {}\n";
971 let out = with_writing_style(older, &WritingStyle::parse_flag("none").unwrap());
972 assert_eq!(config(&out).writing_style.source, WritingSource::None);
973 assert!(config(&out).reserved.is_empty());
974 }
975
976 #[test]
977 fn no_layer_can_reopen_an_exclusion() {
978 let error = resolve(&[], &[], None, &[], &["!a.md".to_string()], &[])
982 .expect_err("a negation is refused");
983 assert!(matches!(error, ConfigError::Pattern(_)));
984 }
985}