vdev 0.3.12

CLI utilities for Vector (vector.dev) development and CI workflows
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
use std::{
    fmt, fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result, anyhow, bail};
use semver::Version;
pub const DEPRECATION_DIR: &str = "deprecation.d";
pub const DEPRECATIONS_JSON: &str = "website/data/deprecations.json";

/// A concrete semver version identifying when a deprecation was announced.
/// Accepted forms: `"0.56"` (major.minor) or `"0.56.0"` (major.minor.patch).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct DeprecationVersion(pub Version);

impl fmt::Display for DeprecationVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl DeprecationVersion {
    /// Returns true when this version's major.minor matches the release.
    /// Patch is ignored so `0.56` (stored as 0.56.0) matches any 0.56.x release.
    pub fn matches_release(&self, release: &Version) -> bool {
        self.0.major == release.major && self.0.minor == release.minor
    }
}

impl<'de> serde::Deserialize<'de> for DeprecationVersion {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        let s = s.trim();
        // Accept both "0.56" (major.minor) and "0.56.0" (major.minor.patch).
        // Normalize the two-part form by appending ".0".
        let normalized = if s.chars().filter(|&c| c == '.').count() == 1 {
            std::borrow::Cow::Owned(format!("{s}.0"))
        } else {
            std::borrow::Cow::Borrowed(s)
        };
        let v = Version::parse(&normalized)
            .map_err(|e| serde::de::Error::custom(format!("invalid version '{s}': {e}")))?;
        if !v.pre.is_empty() || !v.build.is_empty() {
            return Err(serde::de::Error::custom(format!(
                "invalid version '{s}': prerelease and build metadata are not allowed; use plain X.Y or X.Y.Z"
            )));
        }
        Ok(DeprecationVersion(v))
    }
}

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Frontmatter {
    what: String,
    deprecated_since: DeprecationVersion,
}

/// A parsed and validated deprecation entry from `deprecation.d/`.
#[derive(Debug, Clone)]
pub struct DeprecationEntry {
    pub filename: String,
    pub what: String,
    /// The release in which this deprecation was first announced.
    pub deprecated_since: DeprecationVersion,
    /// Optional body text (everything after the closing `---` of the frontmatter).
    pub description: String,
}

/// The result of partitioning deprecation entries relative to a specific release.
pub struct DeprecationPartition {
    /// Entries whose `deprecated_since` matches the release (announced for the first time now).
    pub announcing: Vec<DeprecationEntry>,
    /// Entries whose `deprecated_since` predates the release (announced in an earlier release).
    pub planned: Vec<DeprecationEntry>,
    /// Entries whose `deprecated_since` post-dates the release (announced in a future release).
    pub future: Vec<DeprecationEntry>,
}

/// Partition a list of deprecation entries into three buckets relative to `release`.
pub fn partition_by_release(
    entries: Vec<DeprecationEntry>,
    release: &Version,
) -> DeprecationPartition {
    let mut announcing = Vec::new();
    let mut planned = Vec::new();
    let mut future = Vec::new();
    for e in entries {
        if e.deprecated_since.matches_release(release) {
            announcing.push(e);
        } else if e.deprecated_since.0 < *release {
            planned.push(e);
        } else {
            future.push(e);
        }
    }
    DeprecationPartition {
        announcing,
        planned,
        future,
    }
}

/// Read and parse all deprecation fragments from the given directory.
/// Returns entries sorted by filename.
///
/// Rejects:
///   * the directory itself being a symlink (treated as missing)
///   * duplicate `what` values across fragments
pub fn read_deprecation_fragments(dir: &Path) -> Result<Vec<DeprecationEntry>> {
    // Use symlink_metadata so a symlinked `deprecation.d` doesn't pull in
    // out-of-tree content.
    let Ok(meta) = fs::symlink_metadata(dir) else {
        return Ok(Vec::new());
    };
    if !meta.file_type().is_dir() {
        return Ok(Vec::new());
    }
    let mut paths: Vec<PathBuf> = fs::read_dir(dir)?
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| is_deprecation_fragment(p))
        .collect();
    paths.sort();
    let entries: Vec<DeprecationEntry> = paths
        .into_iter()
        .map(|p| parse_deprecation_fragment(&p))
        .collect::<Result<_>>()?;

    // Reject duplicate `what` across pending fragments. A feature has one
    // identity; two fragments with the same `what` would publish the same
    // deprecation twice.
    let mut seen: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();
    for e in &entries {
        if let Some(prev) = seen.insert(e.what.as_str(), e.filename.as_str()) {
            bail!(
                "Duplicate deprecation fragments for `what`: '{}' (in {} and {})",
                e.what,
                prev,
                e.filename
            );
        }
    }
    Ok(entries)
}

fn is_deprecation_fragment(path: &Path) -> bool {
    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    if name == "README.md" {
        return false;
    }
    if !std::path::Path::new(name)
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
    {
        return false;
    }
    // Reject symlinks and non-regular files so a `.md -> /dev/zero` or
    // out-of-tree symlink can't hang or exfiltrate.
    fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file())
}

fn parse_deprecation_fragment(path: &Path) -> Result<DeprecationEntry> {
    let filename = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("")
        .to_string();

    let raw =
        fs::read_to_string(path).with_context(|| format!("Failed to read {}", path.display()))?;

    let (frontmatter_str, body) = split_frontmatter(&raw, path)?;

    let fm: Frontmatter = serde_yaml::from_str(frontmatter_str)
        .with_context(|| format!("Failed to parse YAML frontmatter in {}", path.display()))?;

    if fm.what.trim().is_empty() {
        bail!(
            "Deprecation fragment {}: `what` field must not be empty",
            path.display()
        );
    }

    Ok(DeprecationEntry {
        filename,
        what: fm.what.trim().to_string(),
        deprecated_since: fm.deprecated_since,
        description: body.trim().to_string(),
    })
}

/// Split the raw file contents into the frontmatter string and the body.
/// The file must begin with `---`, and have a closing `---` on its own line.
fn split_frontmatter<'a>(content: &'a str, path: &Path) -> Result<(&'a str, &'a str)> {
    let content = content.trim_start();
    // Advance past the opening `---` (and optional trailing whitespace on that line)
    let after_open = content
        .strip_prefix("---")
        .ok_or_else(|| {
            anyhow!(
                "Deprecation fragment {} must begin with YAML frontmatter (---)",
                path.display()
            )
        })?
        .trim_start_matches([' ', '\t'])
        .trim_start_matches('\n');

    let (frontmatter, rest) = after_open.split_once("\n---").ok_or_else(|| {
        anyhow!(
            "Deprecation fragment {} has unclosed frontmatter",
            path.display()
        )
    })?;
    let rest = rest.trim_start_matches(['\r', '\n']);
    let body = rest.trim_start_matches(['\r', '\n']);

    Ok((frontmatter, body))
}

/// A deprecation that has been enacted (feature removed).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EnactedEntry {
    pub what: String,
    pub deprecated_since: String,
    pub removed_in: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct DeprecationsJson {
    deprecations_pending: Vec<PendingJsonEntry>,
    deprecations_enacted: Vec<EnactedEntry>,
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct PendingJsonEntry {
    what: String,
    deprecated_since: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    description: String,
}

/// Read only the enacted entries from `DEPRECATIONS_JSON`.
pub fn read_enacted(repo_root: &Path) -> Result<Vec<EnactedEntry>> {
    Ok(read_json(repo_root)?.deprecations_enacted)
}

fn read_json(repo_root: &Path) -> Result<DeprecationsJson> {
    let path = repo_root.join(DEPRECATIONS_JSON);
    if !path.exists() {
        return Ok(DeprecationsJson {
            deprecations_pending: Vec::new(),
            deprecations_enacted: Vec::new(),
        });
    }
    let raw =
        fs::read_to_string(&path).with_context(|| format!("Failed to read {}", path.display()))?;
    serde_json::from_str(&raw).with_context(|| format!("Failed to parse {}", path.display()))
}

fn write_json(repo_root: &Path, data: &DeprecationsJson) -> Result<()> {
    let path = repo_root.join(DEPRECATIONS_JSON);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let out = serde_json::to_string_pretty(data)? + "\n";
    fs::write(&path, out).with_context(|| format!("Failed to write {}", path.display()))
}

/// Append an enacted entry and regenerate the pending section from deprecation.d/.
///
/// Idempotent only on a byte-for-byte duplicate: silently skips the append
/// so that re-running `enact` after a partial failure (e.g. the fragment
/// delete failed) can complete cleanly. Any mismatch in `removed_in`,
/// `deprecated_since`, or `description` is rejected — those signal a stale
/// or edited fragment versus the recorded entry, and silently keeping the
/// older record would lose the new data.
pub fn append_enacted(repo_root: &Path, entry: EnactedEntry) -> Result<()> {
    let dir = repo_root.join(DEPRECATION_DIR);
    let pending = read_deprecation_fragments(&dir)?;
    let mut data = read_json(repo_root)?;
    if let Some(existing) = data
        .deprecations_enacted
        .iter()
        .find(|e| e.what == entry.what)
    {
        if existing.removed_in != entry.removed_in {
            bail!(
                "Conflicting enacted entry for '{}': already recorded as removed in {}, refusing to record as removed in {}",
                entry.what,
                existing.removed_in,
                entry.removed_in
            );
        }
        if existing.deprecated_since != entry.deprecated_since
            || existing.description != entry.description
        {
            bail!(
                "Mismatched enacted entry for '{}': the existing record in {} differs from the fragment data \
                 (deprecated_since or description). \
                 Either revert the fragment edit or update the enacted JSON by hand.",
                entry.what,
                existing.removed_in,
            );
        }
        // Byte-for-byte duplicate; rewrite pending so a partial failure can
        // recover, but don't push the entry again.
    } else {
        data.deprecations_enacted.push(entry);
    }
    data.deprecations_pending = pending_excluding_enacted(&pending, &data.deprecations_enacted);
    write_json(repo_root, &data)
}

/// Filter pending fragments so they exclude any `what` already in `enacted`.
/// Keeps the JSON consistent if `enact` was interrupted between the JSON
/// write and the fragment delete: the next `generate` / `check` will still
/// produce a JSON without the enacted-and-still-on-disk fragment in
/// `deprecations_pending`.
fn pending_excluding_enacted(
    pending: &[DeprecationEntry],
    enacted: &[EnactedEntry],
) -> Vec<PendingJsonEntry> {
    let enacted_what: std::collections::HashSet<&str> =
        enacted.iter().map(|e| e.what.as_str()).collect();
    pending
        .iter()
        .filter(|e| !enacted_what.contains(e.what.as_str()))
        .map(|e| PendingJsonEntry {
            what: e.what.clone(),
            deprecated_since: e.deprecated_since.to_string(),
            description: e.description.clone(),
        })
        .collect()
}

/// Validate the enacted entries in `DEPRECATIONS_JSON`:
///   * both versions must be valid semver
///   * `removed_in` must be in a later major.minor than `deprecated_since`
///     (matching the deprecation policy and the `enact` command's rule)
///   * no duplicate `what` values (a feature can't be removed twice, even
///     in different releases)
pub fn validate_enacted(repo_root: &Path) -> Result<usize> {
    let enacted = read_enacted(repo_root)?;
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    for e in &enacted {
        let dep = parse_strict_release(&e.deprecated_since).with_context(|| {
            format!(
                "Enacted entry '{}' has invalid deprecated_since '{}'",
                e.what, e.deprecated_since
            )
        })?;
        let rem = parse_strict_release(&e.removed_in).with_context(|| {
            format!(
                "Enacted entry '{}' has invalid removed_in '{}'",
                e.what, e.removed_in
            )
        })?;
        if !later_minor(&rem, &dep) {
            bail!(
                "Enacted entry '{}' has removed_in ({}) that is not in a later minor release than deprecated_since ({}); the deprecation policy requires at least one minor release between announcement and removal.",
                e.what,
                e.removed_in,
                e.deprecated_since
            );
        }
        if !seen.insert(e.what.clone()) {
            bail!(
                "Duplicate enacted entry for '{}'; the same feature cannot be recorded as removed more than once.",
                e.what
            );
        }
    }
    Ok(enacted.len())
}

/// True when `a` is in a later major.minor release than `b`. Equal or smaller
/// major.minor (regardless of patch) returns false.
pub fn later_minor(a: &Version, b: &Version) -> bool {
    (a.major, a.minor) > (b.major, b.minor)
}

/// Parse a release version string strictly: only plain `X.Y.Z` is allowed
/// (no prerelease or build metadata). Mirrors the rule that release tags
/// follow `vX.Y.Z`.
pub fn parse_strict_release(s: &str) -> Result<Version> {
    let v = Version::parse(s)?;
    if !v.pre.is_empty() || !v.build.is_empty() {
        bail!("version '{s}' has prerelease or build metadata; only plain X.Y.Z is allowed");
    }
    Ok(v)
}

/// Render the JSON that `sync_deprecations_cue` would write, without
/// touching disk. Returns the serialized string (with trailing newline) so
/// callers can compare against the on-disk file.
pub fn rendered_json(repo_root: &Path) -> Result<String> {
    let dir = repo_root.join(DEPRECATION_DIR);
    let pending = read_deprecation_fragments(&dir)?;
    let mut data = read_json(repo_root)?;
    data.deprecations_pending = pending_excluding_enacted(&pending, &data.deprecations_enacted);
    Ok(serde_json::to_string_pretty(&data)? + "\n")
}

/// Regenerate `DEPRECATIONS_JSON` from `deprecation.d/` (pending) plus the
/// existing enacted entries already in the file.
pub fn sync_deprecations_cue(repo_root: &Path) -> Result<()> {
    let dir = repo_root.join(DEPRECATION_DIR);
    let pending = read_deprecation_fragments(&dir)?;
    let mut data = read_json(repo_root)?;
    data.deprecations_pending = pending_excluding_enacted(&pending, &data.deprecations_enacted);
    write_json(repo_root, &data)
}

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

    #[test]
    fn parse_full_entry() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("foo_opt.md"),
            "---\nwhat: The foo option\ndeprecated_since: \"0.57.0\"\n---\n\nDetailed explanation.\n",
        )
        .unwrap();
        let entries = read_deprecation_fragments(tmp.path()).unwrap();
        assert_eq!(entries.len(), 1);
        let e = &entries[0];
        assert_eq!(e.what, "The foo option");
        assert_eq!(
            e.deprecated_since,
            DeprecationVersion(Version::new(0, 57, 0))
        );
        assert_eq!(e.description, "Detailed explanation.");
    }

    #[test]
    fn rejects_missing_frontmatter() {
        let tmp = tempdir().unwrap();
        fs::write(tmp.path().join("bad.md"), "No frontmatter here.\n").unwrap();
        assert!(read_deprecation_fragments(tmp.path()).is_err());
    }

    #[test]
    fn rejects_empty_what() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("empty.md"),
            "---\nwhat: \"   \"\ndeprecated_since: \"0.60.0\"\n---\n",
        )
        .unwrap();
        assert!(read_deprecation_fragments(tmp.path()).is_err());
    }

    #[test]
    fn skips_readme() {
        let tmp = tempdir().unwrap();
        fs::write(tmp.path().join("README.md"), "# ignored").unwrap();
        let entries = read_deprecation_fragments(tmp.path()).unwrap();
        assert!(entries.is_empty());
    }

    #[test]
    fn parse_two_part_version() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("short.md"),
            "---\nwhat: Short version\ndeprecated_since: \"0.56\"\n---\n",
        )
        .unwrap();
        let entries = read_deprecation_fragments(tmp.path()).unwrap();
        assert_eq!(
            entries[0].deprecated_since,
            DeprecationVersion(Version::new(0, 56, 0))
        );
    }

    #[test]
    fn matches_release_ignores_patch() {
        let v = DeprecationVersion(Version::new(0, 56, 0));
        assert!(v.matches_release(&Version::new(0, 56, 0)));
        assert!(v.matches_release(&Version::new(0, 56, 1)));
        assert!(!v.matches_release(&Version::new(0, 57, 0)));
    }

    #[test]
    fn partition_two_buckets() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("new.md"),
            "---\nwhat: New announcement\ndeprecated_since: \"0.56\"\n---\n",
        )
        .unwrap();
        fs::write(
            tmp.path().join("old.md"),
            "---\nwhat: Previously announced\ndeprecated_since: \"0.53\"\n---\n",
        )
        .unwrap();
        let entries = read_deprecation_fragments(tmp.path()).unwrap();
        let p = partition_by_release(entries, &Version::new(0, 56, 0));
        assert_eq!(p.announcing.len(), 1);
        assert_eq!(p.announcing[0].what, "New announcement");
        assert_eq!(p.planned.len(), 1);
        assert_eq!(p.planned[0].what, "Previously announced");
        assert!(p.future.is_empty());
    }

    #[test]
    fn partition_separates_future_from_planned() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("future.md"),
            "---\nwhat: Future plan\ndeprecated_since: \"0.99\"\n---\n",
        )
        .unwrap();
        fs::write(
            tmp.path().join("old.md"),
            "---\nwhat: Old plan\ndeprecated_since: \"0.10\"\n---\n",
        )
        .unwrap();
        let entries = read_deprecation_fragments(tmp.path()).unwrap();
        let p = partition_by_release(entries, &Version::new(0, 56, 0));
        assert!(p.announcing.is_empty());
        assert_eq!(p.planned.len(), 1);
        assert_eq!(p.planned[0].what, "Old plan");
        assert_eq!(p.future.len(), 1);
        assert_eq!(p.future[0].what, "Future plan");
    }

    #[test]
    fn rejects_symlinked_fragments() {
        // A symlink to /dev/zero (or anything outside the tree) must not be
        // ingested as a fragment. We assert behavior by symlinking inside the
        // tempdir; the loader should still refuse to read the link.
        let tmp = tempdir().unwrap();
        // Real fragment that should still be picked up.
        fs::write(
            tmp.path().join("real.md"),
            "---\nwhat: real\ndeprecated_since: \"0.56\"\n---\n",
        )
        .unwrap();
        let target = tmp.path().join("real.md");
        let link = tmp.path().join("link.md");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&target, &link).unwrap();
        #[cfg(windows)]
        std::os::windows::fs::symlink_file(&target, &link).unwrap();
        let entries = read_deprecation_fragments(tmp.path()).unwrap();
        // Only the real file is included; the symlink is silently dropped.
        let filenames: Vec<&str> = entries.iter().map(|e| e.filename.as_str()).collect();
        assert_eq!(filenames, vec!["real.md"]);
    }

    #[test]
    fn append_enacted_is_idempotent_on_exact_duplicate() {
        // Re-running `enact` after a partial failure should succeed without
        // duplicating the enacted entry.
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("deprecation.d")).unwrap();
        fs::create_dir_all(tmp.path().join("website/data")).unwrap();
        let entry = EnactedEntry {
            what: "foo".into(),
            deprecated_since: "0.55.0".into(),
            removed_in: "0.56.0".into(),
            description: String::new(),
        };
        append_enacted(tmp.path(), entry.clone()).unwrap();
        append_enacted(tmp.path(), entry).unwrap();
        let enacted = read_enacted(tmp.path()).unwrap();
        assert_eq!(enacted.len(), 1);
    }

    #[test]
    fn append_enacted_rejects_conflicting_removed_in() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("deprecation.d")).unwrap();
        fs::create_dir_all(tmp.path().join("website/data")).unwrap();
        let entry = EnactedEntry {
            what: "foo".into(),
            deprecated_since: "0.55.0".into(),
            removed_in: "0.56.0".into(),
            description: String::new(),
        };
        append_enacted(tmp.path(), entry.clone()).unwrap();
        let conflict = EnactedEntry {
            removed_in: "0.57.0".into(),
            ..entry
        };
        let err = append_enacted(tmp.path(), conflict).unwrap_err();
        assert!(format!("{err}").contains("Conflicting"));
    }

    #[test]
    fn append_enacted_rejects_mismatched_deprecated_since_or_description() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("deprecation.d")).unwrap();
        fs::create_dir_all(tmp.path().join("website/data")).unwrap();
        let entry = EnactedEntry {
            what: "foo".into(),
            deprecated_since: "0.55.0".into(),
            removed_in: "0.56.0".into(),
            description: "old".into(),
        };
        append_enacted(tmp.path(), entry.clone()).unwrap();

        // Same `what` + `removed_in` but updated description must not silently
        // keep the older record.
        let edited = EnactedEntry {
            description: "new".into(),
            ..entry.clone()
        };
        let err = append_enacted(tmp.path(), edited).unwrap_err();
        assert!(format!("{err}").contains("Mismatched"));

        // Same with a different deprecated_since.
        let edited = EnactedEntry {
            deprecated_since: "0.54.0".into(),
            ..entry
        };
        let err = append_enacted(tmp.path(), edited).unwrap_err();
        assert!(format!("{err}").contains("Mismatched"));
    }

    #[test]
    fn validate_enacted_catches_bad_versions_and_duplicates() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("website/data")).unwrap();
        // Invalid removed_in.
        fs::write(
            tmp.path().join("website/data/deprecations.json"),
            r#"{"deprecations_pending":[],"deprecations_enacted":[
                {"what":"x","deprecated_since":"0.55.0","removed_in":"not-a-version"}
            ]}"#,
        )
        .unwrap();
        assert!(validate_enacted(tmp.path()).is_err());

        // Duplicate `what` (different removed_in) — still rejected.
        fs::write(
            tmp.path().join("website/data/deprecations.json"),
            r#"{"deprecations_pending":[],"deprecations_enacted":[
                {"what":"x","deprecated_since":"0.55.0","removed_in":"0.56.0"},
                {"what":"x","deprecated_since":"0.55.0","removed_in":"0.57.0"}
            ]}"#,
        )
        .unwrap();
        let err = validate_enacted(tmp.path()).unwrap_err();
        assert!(format!("{err}").contains("Duplicate"));
    }

    #[test]
    fn validate_enacted_rejects_same_minor() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("website/data")).unwrap();
        // removed_in is later semver (patch bump) but same minor as
        // deprecated_since — policy violation that `enact` rejects, so a
        // hand-edited JSON should also fail validation.
        fs::write(
            tmp.path().join("website/data/deprecations.json"),
            r#"{"deprecations_pending":[],"deprecations_enacted":[
                {"what":"x","deprecated_since":"0.57.0","removed_in":"0.57.1"}
            ]}"#,
        )
        .unwrap();
        let err = validate_enacted(tmp.path()).unwrap_err();
        assert!(format!("{err}").contains("later minor release"));
    }

    #[test]
    fn rendered_json_drops_pending_already_enacted() {
        // Simulate an interrupted enact: the fragment file is still on disk
        // (delete failed) but the JSON already has the matching enacted entry.
        // rendered_json must keep deprecations_pending consistent with
        // deprecations_enacted so `check` doesn't accept the inconsistent
        // intermediate state.
        let tmp = tempdir().unwrap();
        let dir = tmp.path().join("deprecation.d");
        fs::create_dir_all(&dir).unwrap();
        fs::create_dir_all(tmp.path().join("website/data")).unwrap();
        fs::write(
            dir.join("foo.md"),
            "---\nwhat: foo\ndeprecated_since: \"0.55.0\"\n---\n",
        )
        .unwrap();
        fs::write(
            tmp.path().join("website/data/deprecations.json"),
            r#"{"deprecations_pending":[],"deprecations_enacted":[
                {"what":"foo","deprecated_since":"0.55.0","removed_in":"0.57.0"}
            ]}"#,
        )
        .unwrap();
        let out = rendered_json(tmp.path()).unwrap();
        assert!(out.contains("\"deprecations_pending\": []"));
        assert!(out.contains("\"what\": \"foo\""));
    }

    #[test]
    fn rejects_duplicate_what_across_fragments() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("a.md"),
            "---\nwhat: \"the foo option\"\ndeprecated_since: \"0.55.0\"\n---\n",
        )
        .unwrap();
        fs::write(
            tmp.path().join("b.md"),
            "---\nwhat: \"the foo option\"\ndeprecated_since: \"0.56.0\"\n---\n",
        )
        .unwrap();
        let err = read_deprecation_fragments(tmp.path()).unwrap_err();
        assert!(format!("{err}").contains("Duplicate"));
    }

    #[test]
    fn rejects_symlinked_dir() {
        use tempfile::tempdir;
        let outside = tempdir().unwrap();
        fs::write(
            outside.path().join("evil.md"),
            "---\nwhat: \"evil\"\ndeprecated_since: \"0.99.0\"\n---\n",
        )
        .unwrap();

        let host = tempdir().unwrap();
        let link = host.path().join("deprecation.d");
        #[cfg(unix)]
        std::os::unix::fs::symlink(outside.path(), &link).unwrap();
        #[cfg(windows)]
        std::os::windows::fs::symlink_dir(outside.path(), &link).unwrap();

        // The symlinked dir must be treated as missing, not read through.
        let entries = read_deprecation_fragments(&link).unwrap();
        assert!(entries.is_empty());
    }

    #[test]
    fn validate_enacted_rejects_prerelease_versions() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("website/data")).unwrap();
        fs::write(
            tmp.path().join("website/data/deprecations.json"),
            r#"{"deprecations_pending":[],"deprecations_enacted":[
                {"what":"x","deprecated_since":"0.55.0","removed_in":"0.56.0-alpha"}
            ]}"#,
        )
        .unwrap();
        let err = validate_enacted(tmp.path()).unwrap_err();
        assert!(format!("{err:?}").contains("prerelease or build metadata"));
    }

    #[test]
    fn rejects_prerelease_and_build_metadata() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("pre.md"),
            "---\nwhat: foo\ndeprecated_since: \"0.58.0-alpha\"\n---\n",
        )
        .unwrap();
        let err = read_deprecation_fragments(tmp.path()).unwrap_err();
        assert!(format!("{err:?}").contains("prerelease and build metadata"));

        let tmp2 = tempdir().unwrap();
        fs::write(
            tmp2.path().join("build.md"),
            "---\nwhat: foo\ndeprecated_since: \"0.58.0+ci\"\n---\n",
        )
        .unwrap();
        let err = read_deprecation_fragments(tmp2.path()).unwrap_err();
        assert!(format!("{err:?}").contains("prerelease and build metadata"));
    }

    #[test]
    fn later_minor_semantics() {
        assert!(later_minor(
            &Version::new(0, 58, 0),
            &Version::new(0, 57, 0)
        ));
        assert!(!later_minor(
            &Version::new(0, 57, 1),
            &Version::new(0, 57, 0)
        ));
        assert!(!later_minor(
            &Version::new(0, 57, 0),
            &Version::new(0, 57, 0)
        ));
        assert!(!later_minor(
            &Version::new(0, 56, 5),
            &Version::new(0, 57, 0)
        ));
    }
}