drft-cli 0.7.0

A structural integrity checker for linked file systems
Documentation
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
use anyhow::{Context, Result};
use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Compile a list of glob patterns into a GlobSet. Returns None if patterns is empty.
/// Uses literal_separator so `*` matches a single path component (like shell globs)
/// and `**` matches across directory boundaries.
pub fn compile_globs(patterns: &[String]) -> Result<Option<GlobSet>> {
    if patterns.is_empty() {
        return Ok(None);
    }
    let mut builder = GlobSetBuilder::new();
    for pattern in patterns {
        builder.add(GlobBuilder::new(pattern).literal_separator(true).build()?);
    }
    Ok(Some(builder.build()?))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleSeverity {
    Error,
    Warn,
    Off,
}

// ── Parser config ──────────────────────────────────────────────

/// Configuration for a single parser under `[parsers]`.
/// Supports shorthand (`markdown = true`) and expanded table form
/// (`[parsers.markdown]` with fields). Parser-specific options go
/// under `[parsers.<name>.options]` and are passed through to the parser.
#[derive(Debug, Clone, Serialize)]
pub struct ParserConfig {
    /// Which File nodes to send to this parser. None = all File nodes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub files: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout: Option<u64>,
    /// Arbitrary options passed through to the parser (not interpreted by drft).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<toml::Value>,
}

/// Serde helper: untagged enum to parse shorthand or table forms.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RawParserValue {
    /// `markdown = true`
    Bool(bool),
    /// `markdown = ["frontmatter", "wikilink"]` (v0.3 shorthand for types)
    Types(Vec<String>),
    /// `[parsers.markdown]` with fields
    Table {
        files: Option<Vec<String>>,
        command: Option<String>,
        timeout: Option<u64>,
        options: Option<toml::Value>,
        // v0.3 keys — accepted as migration aliases
        glob: Option<String>,
        types: Option<Vec<String>>,
    },
}

impl From<RawParserValue> for Option<ParserConfig> {
    fn from(val: RawParserValue) -> Self {
        match val {
            RawParserValue::Bool(false) => None,
            RawParserValue::Bool(true) => Some(ParserConfig {
                files: None,
                command: None,
                timeout: None,
                options: None,
            }),
            RawParserValue::Types(types) => {
                // v0.3 shorthand: `markdown = ["frontmatter"]` → options.types
                let options = toml::Value::Table(toml::map::Map::from_iter([(
                    "types".to_string(),
                    toml::Value::Array(types.into_iter().map(toml::Value::String).collect()),
                )]));
                Some(ParserConfig {
                    files: None,
                    command: None,
                    timeout: None,
                    options: Some(options),
                })
            }
            RawParserValue::Table {
                files,
                command,
                timeout,
                options,
                glob,
                types,
            } => {
                // Migrate v0.3 `glob` → `files`
                let files = if files.is_some() {
                    files
                } else if let Some(glob) = glob {
                    eprintln!("warn: parser 'glob' is deprecated — rename to 'files' (v0.4)");
                    Some(vec![glob])
                } else {
                    None
                };

                // Migrate v0.3 bare `types` → options.types
                let options = if let Some(types) = types {
                    eprintln!(
                        "warn: parser 'types' is deprecated — move to [parsers.<name>.options] (v0.4)"
                    );
                    let types_val =
                        toml::Value::Array(types.into_iter().map(toml::Value::String).collect());
                    match options {
                        Some(toml::Value::Table(mut tbl)) => {
                            tbl.entry("types").or_insert(types_val);
                            Some(toml::Value::Table(tbl))
                        }
                        None => {
                            let tbl = toml::map::Map::from_iter([("types".to_string(), types_val)]);
                            Some(toml::Value::Table(tbl))
                        }
                        other => other, // options exists but isn't a table — leave it
                    }
                } else {
                    options
                };

                Some(ParserConfig {
                    files,
                    command,
                    timeout,
                    options,
                })
            }
        }
    }
}

// ── Rule config ────────────────────────────────────────────────

/// Configuration for a single rule under `[rules]`.
/// Supports shorthand (`cycle = "warn"`) and table form (`[rules.orphan]`).
#[derive(Debug, Clone)]
pub struct RuleConfig {
    pub severity: RuleSeverity,
    /// Scope which nodes the rule evaluates (default: all).
    pub files: Vec<String>,
    /// Exclude nodes from diagnostics (default: none).
    pub ignore: Vec<String>,
    /// Scope which parser edges the rule evaluates (default: all).
    pub parsers: Vec<String>,
    pub command: Option<String>,
    /// Arbitrary structured data passed through to the rule. drft doesn't interpret it.
    pub options: Option<toml::Value>,
    pub(crate) files_compiled: Option<GlobSet>,
    pub(crate) ignore_compiled: Option<GlobSet>,
}

impl Serialize for RuleConfig {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        // Count how many fields to serialize (skip empty/default fields for cleaner output)
        let mut len = 1; // severity always present
        if !self.files.is_empty() {
            len += 1;
        }
        if !self.ignore.is_empty() {
            len += 1;
        }
        if !self.parsers.is_empty() {
            len += 1;
        }
        if self.command.is_some() {
            len += 1;
        }
        if self.options.is_some() {
            len += 1;
        }
        let mut map = serializer.serialize_map(Some(len))?;
        map.serialize_entry("severity", &self.severity)?;
        if !self.files.is_empty() {
            map.serialize_entry("files", &self.files)?;
        }
        if !self.ignore.is_empty() {
            map.serialize_entry("ignore", &self.ignore)?;
        }
        if !self.parsers.is_empty() {
            map.serialize_entry("parsers", &self.parsers)?;
        }
        if let Some(ref command) = self.command {
            map.serialize_entry("command", command)?;
        }
        if let Some(ref options) = self.options {
            map.serialize_entry("options", options)?;
        }
        map.end()
    }
}

impl RuleConfig {
    pub fn new(
        severity: RuleSeverity,
        files: Vec<String>,
        ignore: Vec<String>,
        parsers: Vec<String>,
        command: Option<String>,
        options: Option<toml::Value>,
    ) -> Result<Self> {
        let files_compiled = compile_globs(&files).context("failed to compile files globs")?;
        let ignore_compiled = compile_globs(&ignore).context("failed to compile ignore globs")?;
        Ok(Self {
            severity,
            files,
            ignore,
            parsers,
            command,
            options,
            files_compiled,
            ignore_compiled,
        })
    }

    pub fn is_path_in_scope(&self, path: &str) -> bool {
        match self.files_compiled {
            Some(ref glob_set) => glob_set.is_match(path),
            None => true, // no files = all in scope
        }
    }

    pub fn is_path_ignored(&self, path: &str) -> bool {
        if let Some(ref glob_set) = self.ignore_compiled {
            glob_set.is_match(path)
        } else {
            false
        }
    }
}

/// Serde helper: untagged enum for shorthand or table forms.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RawRuleValue {
    /// `cycle = "warn"`
    Severity(RuleSeverity),
    /// `[rules.orphan]` with fields
    Table {
        #[serde(default = "default_warn")]
        severity: RuleSeverity,
        #[serde(default)]
        files: Vec<String>,
        #[serde(default)]
        ignore: Vec<String>,
        #[serde(default)]
        parsers: Vec<String>,
        command: Option<String>,
        options: Option<toml::Value>,
    },
}

fn default_warn() -> RuleSeverity {
    RuleSeverity::Warn
}

// ── Config ─────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct Config {
    /// Glob patterns declaring which filesystem paths become File nodes.
    /// Default: `["*.md"]`.
    pub include: Vec<String>,
    /// Glob patterns removed from the graph (applied after `include`).
    /// Also respects `.gitignore`.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub exclude: Vec<String>,
    pub parsers: HashMap<String, ParserConfig>,
    pub rules: HashMap<String, RuleConfig>,
    /// Directory containing the drft.toml this config was loaded from.
    #[serde(skip)]
    pub config_dir: Option<std::path::PathBuf>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct RawConfig {
    include: Option<Vec<String>>,
    exclude: Option<Vec<String>>,
    parsers: Option<HashMap<String, RawParserValue>>,
    rules: Option<HashMap<String, RawRuleValue>>,
    // v0.3 key — accepted as alias for `exclude`
    ignore: Option<Vec<String>>,
    // v0.2 keys — detected for migration warnings
    manifest: Option<toml::Value>,
    custom_rules: Option<toml::Value>,
    custom_analyses: Option<toml::Value>,
    custom_metrics: Option<toml::Value>,
    ignore_rules: Option<toml::Value>,
}

/// Names of all built-in rules (for unknown-rule warnings).
const BUILTIN_RULES: &[&str] = &[
    "directed-cycle",
    "fragmentation",
    "orphan-node",
    "schema-violation",
    "stale",
    "symlink-edge",
    "unresolved-edge",
];

impl Config {
    pub fn defaults() -> Self {
        // When no drft.toml exists, default to markdown parser enabled
        let mut parsers = HashMap::new();
        parsers.insert(
            "markdown".to_string(),
            ParserConfig {
                files: None,
                command: None,
                timeout: None,
                options: None,
            },
        );

        let rules = [
            ("directed-cycle", RuleSeverity::Warn),
            ("fragmentation", RuleSeverity::Warn),
            ("orphan-node", RuleSeverity::Warn),
            ("stale", RuleSeverity::Warn),
            ("symlink-edge", RuleSeverity::Warn),
            ("unresolved-edge", RuleSeverity::Warn),
        ]
        .into_iter()
        .map(|(k, v)| {
            (
                k.to_string(),
                RuleConfig::new(v, Vec::new(), Vec::new(), Vec::new(), None, None)
                    .expect("default rule config"),
            )
        })
        .collect();

        Config {
            include: vec!["**/*.md".to_string()],
            exclude: Vec::new(),
            parsers,
            rules,
            config_dir: None,
        }
    }

    pub fn load(root: &Path) -> Result<Self> {
        let config_path = Self::find_config(root);
        let config_path = match config_path {
            Some(p) => p,
            None => anyhow::bail!("no drft.toml found (run `drft init` to create one)"),
        };

        let content = std::fs::read_to_string(&config_path)
            .with_context(|| format!("failed to read {}", config_path.display()))?;

        let raw: RawConfig = toml::from_str(&content)
            .with_context(|| format!("failed to parse {}", config_path.display()))?;

        // Warn about v0.2 config keys
        if raw.manifest.is_some() {
            eprintln!("warn: drft.toml uses v0.2 'manifest' key — use 'include' instead");
        }
        if raw.custom_rules.is_some() {
            eprintln!(
                "warn: drft.toml uses v0.2 [custom-rules] — migrate to [rules] with 'command' field"
            );
        }
        if raw.custom_analyses.is_some() {
            eprintln!(
                "warn: drft.toml uses v0.2 [custom-analyses] — custom analyses are no longer supported"
            );
        }
        if raw.custom_metrics.is_some() {
            eprintln!(
                "warn: drft.toml uses v0.2 [custom-metrics] — custom metrics are no longer supported"
            );
        }
        if raw.ignore_rules.is_some() {
            eprintln!(
                "warn: drft.toml uses v0.2 [ignore-rules] — migrate to per-rule 'ignore' field"
            );
        }

        let mut config = Self::defaults();
        config.config_dir = config_path.parent().map(|p| p.to_path_buf());

        if let Some(include) = raw.include {
            config.include = include;
        }

        // `ignore` is the v0.3 name for `exclude` — accept with warning
        if raw.ignore.is_some() && raw.exclude.is_some() {
            anyhow::bail!(
                "drft.toml has both 'ignore' and 'exclude' — remove 'ignore' (renamed to 'exclude' in v0.4)"
            );
        }
        if let Some(ignore) = raw.ignore {
            eprintln!("warn: drft.toml uses 'ignore' — rename to 'exclude' (v0.4)");
            config.exclude = ignore;
        }
        if let Some(exclude) = raw.exclude {
            config.exclude = exclude;
        }

        // Parse parsers
        if let Some(raw_parsers) = raw.parsers {
            config.parsers.clear();
            for (name, value) in raw_parsers {
                if let Some(parser_config) = Option::<ParserConfig>::from(value) {
                    config.parsers.insert(name, parser_config);
                }
            }
        }

        // Parse rules (unified: built-in severities + table form + custom rules)
        if let Some(raw_rules) = raw.rules {
            for (name, value) in raw_rules {
                let rule_config = match value {
                    RawRuleValue::Severity(severity) => {
                        RuleConfig::new(severity, Vec::new(), Vec::new(), Vec::new(), None, None)?
                    }
                    RawRuleValue::Table {
                        severity,
                        files,
                        ignore,
                        parsers,
                        command,
                        options,
                    } => RuleConfig::new(severity, files, ignore, parsers, command, options)
                        .with_context(|| format!("invalid globs in rules.{name}"))?,
                };

                // Warn about unknown built-in rules (but allow custom rules with command)
                if rule_config.command.is_none() && !BUILTIN_RULES.contains(&name.as_str()) {
                    eprintln!("warn: unknown rule \"{name}\" in drft.toml (ignored)");
                }

                // Warn about unknown parser references in rule parsers
                for parser_name in &rule_config.parsers {
                    if !config.parsers.contains_key(parser_name) {
                        eprintln!(
                            "warn: unknown parser \"{parser_name}\" in rules.{name}.parsers in drft.toml"
                        );
                    }
                }

                config.rules.insert(name, rule_config);
            }
        }

        Ok(config)
    }

    /// Find drft.toml in `root`. No directory walking — if it's not here, use defaults.
    fn find_config(root: &Path) -> Option<std::path::PathBuf> {
        let candidate = root.join("drft.toml");
        candidate.exists().then_some(candidate)
    }

    pub fn rule_severity(&self, name: &str) -> RuleSeverity {
        self.rules
            .get(name)
            .map(|r| r.severity)
            .unwrap_or(RuleSeverity::Off)
    }

    /// Check if a path is in scope for a specific rule (passes `files` filter).
    pub fn is_rule_in_scope(&self, rule: &str, path: &str) -> bool {
        self.rules
            .get(rule)
            .is_none_or(|r| r.is_path_in_scope(path))
    }

    /// Check if a path should be ignored for a specific rule.
    pub fn is_rule_ignored(&self, rule: &str, path: &str) -> bool {
        self.rules
            .get(rule)
            .is_some_and(|r| r.is_path_ignored(path))
    }

    /// Get a rule's options (the `[rules.<name>.options]` section).
    pub fn rule_options(&self, name: &str) -> Option<&toml::Value> {
        self.rules.get(name).and_then(|r| r.options.as_ref())
    }

    /// Get parser names a rule is scoped to (empty = all parsers).
    pub fn rule_parsers(&self, name: &str) -> &[String] {
        self.rules
            .get(name)
            .map(|r| r.parsers.as_slice())
            .unwrap_or(&[])
    }

    /// Get custom rules (rules with a command field).
    pub fn custom_rules(&self) -> impl Iterator<Item = (&str, &RuleConfig)> {
        self.rules
            .iter()
            .filter(|(_, r)| r.command.is_some())
            .map(|(name, config)| (name.as_str(), config))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn errors_when_no_config() {
        let dir = TempDir::new().unwrap();
        let result = Config::load(dir.path());
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("no drft.toml found"),
        );
    }

    #[test]
    fn loads_rule_severities() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[rules]\nunresolved-edge = \"error\"\norphan-node = \"warn\"\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert_eq!(config.rule_severity("unresolved-edge"), RuleSeverity::Error);
        assert_eq!(config.rule_severity("orphan-node"), RuleSeverity::Warn);
        assert_eq!(config.rule_severity("directed-cycle"), RuleSeverity::Warn);
    }

    #[test]
    fn loads_rule_with_ignore() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[rules.orphan-node]\nseverity = \"warn\"\nignore = [\"README.md\", \"index.md\"]\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert_eq!(config.rule_severity("orphan-node"), RuleSeverity::Warn);
        assert!(config.is_rule_ignored("orphan-node", "README.md"));
        assert!(config.is_rule_ignored("orphan-node", "index.md"));
        assert!(!config.is_rule_ignored("orphan-node", "other.md"));
        assert!(!config.is_rule_ignored("unresolved-edge", "README.md"));
    }

    #[test]
    fn loads_rule_with_options() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            r#"
[rules.schema-violation]
severity = "warn"

[rules.schema-violation.options]
required = ["title"]

[rules.schema-violation.options.schemas."observations/*.md"]
required = ["title", "date", "status"]
"#,
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        let opts = config.rule_options("schema-violation").unwrap();
        let required = opts.get("required").unwrap().as_array().unwrap();
        assert_eq!(required.len(), 1);
        assert_eq!(required[0].as_str().unwrap(), "title");
        let schemas = opts.get("schemas").unwrap().as_table().unwrap();
        assert!(schemas.contains_key("observations/*.md"));
    }

    #[test]
    fn shorthand_rule_has_no_options() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[rules]\nunresolved-edge = \"error\"\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert!(config.rule_options("unresolved-edge").is_none());
    }

    #[test]
    fn loads_parser_shorthand_bool() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("drft.toml"), "[parsers]\nmarkdown = true\n").unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert!(config.parsers.contains_key("markdown"));
        let p = &config.parsers["markdown"];
        assert!(p.files.is_none());
        assert!(p.options.is_none());
        assert!(p.command.is_none());
    }

    #[test]
    fn loads_parser_shorthand_types_migrates_to_options() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[parsers]\nmarkdown = [\"frontmatter\", \"wikilink\"]\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        let p = &config.parsers["markdown"];
        // v0.3 shorthand types → options.types
        let opts = p.options.as_ref().unwrap();
        let types = opts.get("types").unwrap().as_array().unwrap();
        assert_eq!(types.len(), 2);
        assert_eq!(types[0].as_str().unwrap(), "frontmatter");
        assert_eq!(types[1].as_str().unwrap(), "wikilink");
    }

    #[test]
    fn loads_parser_table_with_files() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[parsers.tsx]\nfiles = [\"*.tsx\", \"*.ts\"]\ncommand = \"./parse.sh\"\ntimeout = 10000\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        let p = &config.parsers["tsx"];
        assert_eq!(
            p.files.as_deref(),
            Some(&["*.tsx".to_string(), "*.ts".to_string()][..])
        );
        assert_eq!(p.command.as_deref(), Some("./parse.sh"));
        assert_eq!(p.timeout, Some(10000));
    }

    #[test]
    fn loads_parser_glob_migrates_to_files() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[parsers.tsx]\nglob = \"*.tsx\"\ncommand = \"./parse.sh\"\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        let p = &config.parsers["tsx"];
        assert_eq!(p.files.as_deref(), Some(&["*.tsx".to_string()][..]));
    }

    #[test]
    fn loads_parser_options() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[parsers.markdown]\nfiles = [\"*.md\"]\n\n[parsers.markdown.options]\ntypes = [\"inline\"]\nextract_metadata = true\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        let p = &config.parsers["markdown"];
        let opts = p.options.as_ref().unwrap();
        assert!(opts.get("types").is_some());
        assert_eq!(opts.get("extract_metadata").unwrap().as_bool(), Some(true));
    }

    #[test]
    fn parser_false_disables() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[parsers]\nmarkdown = false\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert!(!config.parsers.contains_key("markdown"));
    }

    #[test]
    fn loads_custom_rule() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[rules.my-check]\ncommand = \"./check.sh\"\nseverity = \"warn\"\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        let custom_rules: Vec<_> = config.custom_rules().collect();
        assert_eq!(custom_rules.len(), 1);
        assert_eq!(custom_rules[0].0, "my-check");
        assert_eq!(custom_rules[0].1.command.as_deref(), Some("./check.sh"));
    }

    #[test]
    fn loads_include_exclude() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "include = [\"*.md\", \"*.yaml\"]\nexclude = [\"drafts/*\"]\n",
        )
        .unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert_eq!(config.include, vec!["*.md", "*.yaml"]);
        assert_eq!(config.exclude, vec!["drafts/*"]);
    }

    #[test]
    fn ignore_migrates_to_exclude() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("drft.toml"), "ignore = [\"drafts/*\"]\n").unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert_eq!(config.exclude, vec!["drafts/*"]);
    }

    #[test]
    fn ignore_and_exclude_conflicts() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "ignore = [\"a/*\"]\nexclude = [\"b/*\"]\n",
        )
        .unwrap();
        assert!(Config::load(dir.path()).is_err());
    }

    #[test]
    fn invalid_toml_returns_error() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("drft.toml"), "not valid toml {{{{").unwrap();
        assert!(Config::load(dir.path()).is_err());
    }

    #[test]
    fn child_without_config_errors() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("drft.toml"),
            "[rules]\norphan-node = \"error\"\n",
        )
        .unwrap();

        let child = dir.path().join("child");
        fs::create_dir(&child).unwrap();

        let result = Config::load(&child);
        assert!(result.is_err());
    }
}