vissue-core 0.6.0

Plain-text issue tracking over per-project orgmode files: model, store, queries, and org projection
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
//! A read-only projection of selected projects into a single shareable file.
//!
//! The mirror exists so a collaborator who cannot reach the tracker still sees
//! the backlog. It carries a banner naming it as generated output, because the
//! next run overwrites it and hand edits are lost.

use anyhow::{Context, anyhow};

use crate::error::Result;
use chrono::Local;
use std::fmt::Write as _;
use std::path::Path;

use crate::config::Layout;
use crate::digest::{CorpusDigest, corpus_digest};
use crate::model::{IssueHeading, TODO_HEADER, today_inactive_bracket};
use crate::store::{IssueDoc, list_projects};

/// Body lines carried into the projection before it is cut short.
pub const BODY_LINES: usize = 12;

const BANNER: &str =
    "MIRROR: generated by `vissue mirror`. Read-only projection; edits here are overwritten.";

/// Output shape for [`render`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    /// Org file with a banner, planning lines, and drawers.
    Org,
    /// Markdown file with metadata as bullets.
    Markdown,
}

impl Format {
    /// Parse `org`, `markdown`, or `md`.
    ///
    /// # Errors
    ///
    /// Returns an error if `s` is not one of those names.
    pub fn parse(s: &str) -> Result<Self> {
        match s {
            "org" => Ok(Format::Org),
            "markdown" | "md" => Ok(Format::Markdown),
            other => Err(anyhow!("unknown format {other:?}; allowed: org, markdown").into()),
        }
    }
}

/// What a mirror was generated against, written into its header so a reader
/// can tell whether the file still matches the tracker.
///
/// Every field but `at` is a function of the corpus, so two runs over an
/// unchanged tracker differ only in the timestamp.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SyncStamp {
    /// Combined corpus digest the mirror was generated against.
    pub digest: String,
    /// Event-log generation at stamp time.
    pub generation: u64,
    /// Issue count at stamp time.
    pub issues: usize,
    /// Project name paired with its sub-digest, so a staleness check can name
    /// which project moved rather than only that something did.
    pub projects: Vec<(String, String)>,
    /// Local timestamp the stamp was written, `YYYY-MM-DDTHH:MM`.
    pub at: String,
}

impl SyncStamp {
    /// Build a stamp from a digest and a caller-supplied timestamp.
    pub fn from_digest(digest: &CorpusDigest, at: String) -> Self {
        Self {
            digest: digest.combined.clone(),
            generation: digest.generation,
            issues: digest.issues,
            projects: digest
                .projects
                .iter()
                .map(|p| (p.project.clone(), p.digest.clone()))
                .collect(),
            at,
        }
    }

    /// The stamp body, without the comment markers a format wraps it in.
    ///
    /// Written without spaces inside any field so the line splits on
    /// whitespace.
    pub fn render(&self) -> String {
        let projects = self
            .projects
            .iter()
            .map(|(name, digest)| format!("{name}:{digest}"))
            .collect::<Vec<_>>()
            .join(",");
        format!(
            "SYNC: digest={} generation={} issues={} at={} projects={}",
            self.digest, self.generation, self.issues, self.at, projects
        )
    }

    /// Read a stamp from a line of a mirror, whatever comment syntax wraps it.
    pub fn parse(line: &str) -> Option<Self> {
        let body = line
            .trim()
            .trim_start_matches("<!--")
            .trim_end_matches("-->")
            .trim()
            .trim_start_matches('#')
            .trim();
        let rest = body.strip_prefix("SYNC:")?;

        let mut digest = None;
        let mut generation = None;
        let mut issues = None;
        let mut at = None;
        let mut projects = Vec::new();
        for field in rest.split_whitespace() {
            let (key, value) = field.split_once('=')?;
            match key {
                "digest" => digest = Some(value.to_string()),
                "generation" => generation = value.parse().ok(),
                "issues" => issues = value.parse().ok(),
                "at" => at = Some(value.to_string()),
                "projects" => {
                    for entry in value.split(',').filter(|e| !e.is_empty()) {
                        let (name, sub) = entry.split_once(':')?;
                        projects.push((name.to_string(), sub.to_string()));
                    }
                }
                _ => {}
            }
        }
        Some(Self {
            digest: digest?,
            generation: generation?,
            issues: issues?,
            projects,
            at: at?,
        })
    }

    /// Find the stamp in a whole mirror file.
    pub fn find(text: &str) -> Option<Self> {
        text.lines().find_map(Self::parse)
    }
}

/// The stamp for the current state of the named projects.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read or digested.
pub fn stamp_for(layout: &Layout, projects: &[String]) -> Result<SyncStamp> {
    let digest = corpus_digest(layout, projects)?;
    Ok(SyncStamp::from_digest(
        &digest,
        Local::now().format("%Y-%m-%dT%H:%M").to_string(),
    ))
}

/// The verdict of comparing a mirror's stamp against the tracker.
#[derive(Debug, Clone)]
pub struct Freshness {
    /// Whether the stamp's digest still matches the tracker.
    pub fresh: bool,
    /// Human-readable verdict, including which projects moved when stale.
    pub report: String,
}

/// Compare the stamp inside `path` against the corpus it claims to mirror.
///
/// With no explicit `projects`, the stamp's own project list is used: the file
/// records what it covered, so a caller need not repeat it.
///
/// # Errors
///
/// Returns an error if `path` cannot be read, or the corpus cannot be
/// digested.
pub fn check(layout: &Layout, path: &Path, projects: &[String]) -> Result<Freshness> {
    let text = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    let Some(stamped) = SyncStamp::find(&text) else {
        return Ok(Freshness {
            fresh: false,
            report: format!(
                "stale: {} carries no SYNC stamp; regenerate it with `vissue mirror`\n",
                path.display()
            ),
        });
    };

    let selected: Vec<String> = if projects.is_empty() {
        stamped.projects.iter().map(|(n, _)| n.clone()).collect()
    } else {
        projects.to_vec()
    };
    let current = corpus_digest(layout, &selected)?;

    if current.combined == stamped.digest {
        return Ok(Freshness {
            fresh: true,
            report: format!(
                "fresh: digest={} issues={} generation={} (stamped {})\n",
                current.combined, current.issues, current.generation, stamped.at
            ),
        });
    }

    let mut report = format!(
        "stale: {}\n  stamped digest={} at={} issues={}\n  current digest={} issues={} generation={}\n",
        path.display(),
        stamped.digest,
        stamped.at,
        stamped.issues,
        current.combined,
        current.issues,
        current.generation
    );
    for (name, was) in &stamped.projects {
        match current.digest_of(name) {
            Some(now) if now == was => {}
            Some(now) => {
                let _ = writeln!(report, "  moved: {name} {was} -> {now}");
            }
            None => {
                let _ = writeln!(report, "  gone:  {name} was {was}");
            }
        }
    }
    for name in current.project_names() {
        if !stamped.projects.iter().any(|(n, _)| n == &name) {
            let _ = writeln!(
                report,
                "  added: {name} {}",
                current.digest_of(&name).unwrap_or("?")
            );
        }
    }
    Ok(Freshness {
        fresh: false,
        report,
    })
}

/// Project the named projects into one document. An empty `projects` list
/// covers every project in the layout.
///
/// # Errors
///
/// Returns an error if the corpus cannot be listed, read, or digested.
pub fn render(
    layout: &Layout,
    projects: &[String],
    format: Format,
    state_filter: Option<&str>,
) -> Result<String> {
    let selected: Vec<String> = if projects.is_empty() {
        list_projects(layout)?
    } else {
        let mut v = projects.to_vec();
        v.sort();
        v.dedup();
        v
    };

    let stamp = stamp_for(layout, &selected)?.render();

    let mut out = String::new();
    match format {
        Format::Org => {
            writeln!(out, "#+TITLE: vissue mirror")?;
            writeln!(out, "#+DATE: {}", today_inactive_bracket())?;
            writeln!(out, "#+FILETAGS: :vissue:mirror:")?;
            writeln!(out, "{TODO_HEADER}")?;
            writeln!(out, "# {BANNER}")?;
            writeln!(out, "# Projects: {}", selected.join(", "))?;
            writeln!(out, "# {stamp}")?;
            writeln!(out)?;
        }
        Format::Markdown => {
            writeln!(out, "# vissue mirror")?;
            writeln!(out)?;
            writeln!(out, "_{BANNER}_")?;
            writeln!(out)?;
            writeln!(
                out,
                "Generated {} for: {}",
                today_inactive_bracket(),
                selected.join(", ")
            )?;
            writeln!(out)?;
            writeln!(out, "<!-- {stamp} -->")?;
            writeln!(out)?;
        }
    }

    for project in &selected {
        let path = layout.project_issues_path(project);
        let doc = IssueDoc::parse_file(project, &path)?;
        let mut headings: Vec<&IssueHeading> = doc
            .headings
            .iter()
            .filter(|h| state_filter.map(|s| h.state == s).unwrap_or(true))
            .filter(|h| doc.tag_settings.heading_exportable(&h.org_tags))
            .collect();
        headings.sort_by(|a, b| {
            a.priority
                .cmp(&b.priority)
                .then_with(|| a.state.cmp(&b.state))
                .then_with(|| a.id.cmp(&b.id))
        });
        if headings.is_empty() {
            continue;
        }
        match format {
            Format::Org => {
                writeln!(out, "* {project}")?;
                for h in headings {
                    render_org_issue(&mut out, h)?;
                }
            }
            Format::Markdown => {
                writeln!(out, "## {project}")?;
                writeln!(out)?;
                for h in headings {
                    render_markdown_issue(&mut out, h)?;
                }
            }
        }
    }
    Ok(out)
}

/// Issues render at level two, so a body heading has to sit at level three or
/// deeper. Without the shift, a body that opens with `** Scope` becomes a
/// sibling of the issues and the projection's outline is wrong.
const ISSUE_LEVEL: usize = 2;

fn render_org_issue(out: &mut String, h: &IssueHeading) -> Result<()> {
    // The projection is an Org file someone opens in Emacs, so it carries the
    // dates and tags the same way the tracker does: on the planning line and
    // the heading, where Org's agenda and tag search read them.
    let stem = format!("** {} [#{}] {}", h.state, h.priority, h.title);
    writeln!(out, "{}", crate::model::align_tags(&stem, &h.org_tags))?;
    let planning: Vec<String> = crate::model::PLANNING_KEYS
        .iter()
        .filter_map(|key| {
            let value = h.properties.get(*key)?.trim();
            (!value.is_empty()).then(|| format!("{key}: {value}"))
        })
        .collect();
    if !planning.is_empty() {
        writeln!(out, "{}", planning.join(" "))?;
    }
    writeln!(out, ":PROPERTIES:")?;
    writeln!(out, "{}", property_line("ID", &h.id))?;
    for key in [
        "PARENT",
        "BLOCKED_BY",
        crate::model::TAGS_PROPERTY,
        "TYPE",
        "CLAIMED_BY",
        "CLAIMED_AT",
    ] {
        if let Some(val) = h.properties.get(key) {
            writeln!(out, "{}", property_line(key, val))?;
        }
    }
    writeln!(out, ":END:")?;
    let body = demote_headings(&compact_body(&h.body));
    if !body.is_empty() {
        writeln!(out)?;
        writeln!(out, "{body}")?;
    }
    Ok(())
}

/// `:KEY:` padded to the column the tracker's own writer uses.
fn property_line(key: &str, value: &str) -> String {
    let name = format!(":{key}:");
    let pad = 13usize.saturating_sub(name.len()).max(1);
    format!("{name}{}{value}", " ".repeat(pad))
}

/// Push every heading in a body below the issue that owns it, preserving the
/// relative nesting the author wrote.
fn demote_headings(body: &str) -> String {
    let shallowest = body
        .lines()
        .filter_map(heading_level)
        .min()
        .unwrap_or(usize::MAX);
    if shallowest > ISSUE_LEVEL {
        return body.to_string();
    }
    let shift = ISSUE_LEVEL + 1 - shallowest;
    body.lines()
        .map(|line| {
            if heading_level(line).is_some() {
                format!("{}{}", "*".repeat(shift), line)
            } else {
                line.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// The number of leading stars, when the line is an org heading.
fn heading_level(line: &str) -> Option<usize> {
    let stars = line.chars().take_while(|c| *c == '*').count();
    if stars > 0 && line.chars().nth(stars) == Some(' ') {
        Some(stars)
    } else {
        None
    }
}

fn render_markdown_issue(out: &mut String, h: &IssueHeading) -> Result<()> {
    writeln!(out, "### {} [#{}] {}", h.state, h.priority, h.title)?;
    writeln!(out)?;
    writeln!(out, "- id: `{}`", h.id)?;
    let tags = h.tags();
    if !tags.is_empty() {
        writeln!(out, "- tags: {}", tags.join(","))?;
    }
    for key in [
        "PARENT",
        "BLOCKED_BY",
        "DEADLINE",
        "SCHEDULED",
        "TYPE",
        "CLAIMED_BY",
        "CLAIMED_AT",
    ] {
        if let Some(val) = h.properties.get(key) {
            writeln!(out, "- {}: {}", key.to_lowercase(), val)?;
        }
    }
    let body = compact_body(&h.body);
    if !body.is_empty() {
        writeln!(out)?;
        writeln!(out, "{body}")?;
    }
    writeln!(out)?;
    Ok(())
}

/// Collapse blank runs and stop after [`BODY_LINES`], marking the cut.
fn compact_body(body: &str) -> String {
    let mut kept: Vec<&str> = Vec::new();
    let mut previous_blank = false;
    let mut truncated = false;
    for line in body.lines() {
        let blank = line.trim().is_empty();
        if blank && (previous_blank || kept.is_empty()) {
            continue;
        }
        if kept.len() >= BODY_LINES {
            truncated = true;
            break;
        }
        kept.push(line);
        previous_blank = blank;
    }
    while kept.last().map(|l| l.trim().is_empty()).unwrap_or(false) {
        kept.pop();
    }
    let mut text = kept.join("\n");
    if truncated {
        text.push_str("\n(...)");
    }
    text
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::DEFAULT_PREFIX;
    use crate::ops::{CreateOpts, create};
    use std::fs;

    fn seeded_layout() -> (tempfile::TempDir, Layout) {
        let dir = tempfile::tempdir().unwrap();
        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
        fs::create_dir_all(layout.projects_dir()).unwrap();
        create(
            &layout,
            "alpha",
            "wire the parser",
            CreateOpts {
                priority: Some('A'),
                tags: Some("parser,core"),
                body: Some("Scope: the front end.\n\n\nDone-when: it round-trips."),
                ..Default::default()
            },
        )
        .unwrap();
        create(&layout, "beta", "other project work", CreateOpts::default()).unwrap();
        (dir, layout)
    }

    #[test]
    fn org_mirror_carries_the_banner_and_selected_projects_only() {
        let (_dir, layout) = seeded_layout();
        let text = render(&layout, &["alpha".to_string()], Format::Org, None).unwrap();
        assert!(
            text.contains("# MIRROR: generated by `vissue mirror`"),
            "{text}"
        );
        assert!(text.contains("# Projects: alpha"), "{text}");
        assert!(text.contains("* alpha"), "{text}");
        assert!(!text.contains("* beta"), "{text}");
        assert!(text.contains("** TODO [#A] wire the parser"), "{text}");
        // Tags ride the heading, which is where Org's tag search reads them.
        let heading = text
            .lines()
            .find(|l| l.starts_with("** TODO [#A] wire the parser"))
            .expect("issue heading");
        assert!(heading.ends_with(":parser:core:"), "{heading:?}");
        assert!(text.contains("Scope: the front end."), "{text}");
    }

    #[test]
    fn an_empty_project_list_covers_every_project() {
        let (_dir, layout) = seeded_layout();
        let text = render(&layout, &[], Format::Org, None).unwrap();
        assert!(text.contains("* alpha"), "{text}");
        assert!(text.contains("* beta"), "{text}");
        assert!(text.contains("# Projects: alpha, beta"), "{text}");
    }

    #[test]
    fn the_mirror_reparses_as_issue_headings() {
        let (_dir, layout) = seeded_layout();
        let text = render(&layout, &[], Format::Org, None).unwrap();
        // Level-one project names are Org sections, not issues. Level-two
        // issue headings stay in that section's body. A reparse must not
        // fail the file for a missing :ID: on the project heading.
        let doc = IssueDoc::parse("mirror", std::path::PathBuf::from("/tmp/m.org"), &text)
            .expect("a mirror is legal Org");
        assert!(
            doc.headings.is_empty(),
            "project headings are sections, not issues: {:?}",
            doc.headings.iter().map(|h| &h.id).collect::<Vec<_>>()
        );
    }

    #[test]
    fn markdown_mirror_lists_metadata_as_bullets() {
        let (_dir, layout) = seeded_layout();
        let text = render(&layout, &["alpha".to_string()], Format::Markdown, None).unwrap();
        assert!(text.contains("### TODO [#A] wire the parser"), "{text}");
        assert!(text.contains("- tags: parser,core"), "{text}");
    }

    #[test]
    fn state_filter_selects_a_single_bucket() {
        let (_dir, layout) = seeded_layout();
        let text = render(&layout, &[], Format::Org, Some("DONE")).unwrap();
        assert!(!text.contains("** TODO"), "{text}");
        assert!(text.contains("# Projects: alpha, beta"), "{text}");
    }

    #[test]
    fn body_compaction_collapses_blanks_and_marks_the_cut() {
        let long: String = (1..=20).map(|i| format!("line {i}\n")).collect();
        let compacted = compact_body(&long);
        assert_eq!(compacted.lines().count(), BODY_LINES + 1);
        assert!(compacted.ends_with("(...)"), "{compacted}");
        assert_eq!(compact_body("a\n\n\n\nb"), "a\n\nb");
        assert_eq!(compact_body("\n\n"), "");
    }

    #[test]
    fn body_headings_sit_below_the_issue_that_owns_them() {
        // A body written with level-two headings would otherwise render as a
        // sibling of the issues, so the outline would claim Scope is an issue.
        assert_eq!(
            demote_headings("** Scope\ntext\n*** Detail"),
            "*** Scope\ntext\n**** Detail"
        );
        assert_eq!(demote_headings("* Top\n** Under"), "*** Top\n**** Under");
        assert_eq!(
            demote_headings("**** Already deep"),
            "**** Already deep",
            "a body that is already nested is left alone"
        );
        assert_eq!(demote_headings("no headings here"), "no headings here");
        assert_eq!(
            demote_headings("*bold* not a heading"),
            "*bold* not a heading",
            "a star without a following space is not a heading"
        );
    }

    #[test]
    fn a_mirrored_body_heading_never_reparses_as_an_issue() {
        let dir = tempfile::tempdir().unwrap();
        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
        fs::create_dir_all(layout.projects_dir()).unwrap();
        create(
            &layout,
            "alpha",
            "structured body",
            CreateOpts {
                body: Some("** Scope\nthe front end.\n** Done when\nit round-trips."),
                ..Default::default()
            },
        )
        .unwrap();
        let text = render(&layout, &[], Format::Org, None).unwrap();
        assert!(text.contains("*** Scope"), "{text}");
        assert!(text.contains("*** Done when"), "{text}");
        assert!(
            !text.contains("\n** Scope"),
            "a body heading kept issue level: {text}"
        );
    }

    #[test]
    fn property_lines_line_up_with_the_tracker_format() {
        assert_eq!(property_line("ID", "alpha-1a2b"), ":ID:         alpha-1a2b");
        assert_eq!(
            property_line("PARENT", "alpha-9z8y"),
            ":PARENT:     alpha-9z8y"
        );
        assert_eq!(
            property_line("BLOCKED_BY", "alpha-1"),
            ":BLOCKED_BY: alpha-1"
        );
    }

    #[test]
    fn a_stamp_round_trips_through_its_rendered_form() {
        let stamp = SyncStamp {
            digest: "0123456789abcdef".into(),
            generation: 3167,
            issues: 13,
            projects: vec![
                ("alpha".into(), "aaaaaaaaaaaaaaaa".into()),
                ("beta".into(), "bbbbbbbbbbbbbbbb".into()),
            ],
            at: "2026-08-03T09:30".into(),
        };
        let line = stamp.render();
        assert!(line.starts_with("SYNC: digest=0123456789abcdef"), "{line}");
        assert!(
            line.contains("projects=alpha:aaaaaaaaaaaaaaaa,beta:bbbbbbbbbbbbbbbb"),
            "{line}"
        );

        // The comment wrappers each format uses must both parse back.
        assert_eq!(SyncStamp::parse(&format!("# {line}")).unwrap(), stamp);
        assert_eq!(
            SyncStamp::parse(&format!("<!-- {line} -->")).unwrap(),
            stamp
        );
        assert_eq!(SyncStamp::parse(&line).unwrap(), stamp);
    }

    #[test]
    fn a_line_that_is_not_a_stamp_parses_as_nothing() {
        for line in [
            "# MIRROR: generated by `vissue mirror`.",
            "# Projects: alpha, beta",
            "* alpha",
            "",
        ] {
            assert!(SyncStamp::parse(line).is_none(), "{line}");
        }
    }

    #[test]
    fn the_stamp_is_found_in_a_rendered_mirror() {
        let (_dir, layout) = seeded_layout();
        let text = render(&layout, &[], Format::Org, None).unwrap();
        let stamp = SyncStamp::find(&text).expect("no stamp in the mirror header");
        let current = crate::digest::corpus_digest(&layout, &[]).unwrap();
        assert_eq!(stamp.digest, current.combined);
        assert_eq!(stamp.issues, current.issues);
        assert_eq!(stamp.projects.len(), 2);

        let markdown = render(&layout, &[], Format::Markdown, None).unwrap();
        assert_eq!(SyncStamp::find(&markdown).unwrap().digest, current.combined);
    }

    #[test]
    fn format_parsing_rejects_unknown_names() {
        assert_eq!(Format::parse("org").unwrap(), Format::Org);
        assert_eq!(Format::parse("md").unwrap(), Format::Markdown);
        assert!(Format::parse("pdf").is_err());
    }

    #[test]
    fn org_mirror_drops_a_heading_tagged_noexport() {
        let dir = tempfile::tempdir().unwrap();
        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
        fs::create_dir_all(layout.projects_dir()).unwrap();
        crate::ops::create(
            &layout,
            "alpha",
            "keep this",
            crate::ops::CreateOpts::default(),
        )
        .unwrap();
        crate::ops::create(
            &layout,
            "alpha",
            "secret tree",
            crate::ops::CreateOpts {
                tags: Some("noexport"),
                ..Default::default()
            },
        )
        .unwrap();
        let text = render(&layout, &["alpha".into()], Format::Org, None).unwrap();
        assert!(text.contains("keep this"), "{text}");
        assert!(
            !text.contains("secret tree"),
            "a heading tagged noexport stayed in the Org mirror: {text}"
        );
    }
}