wsb 0.258.6441

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
//! Everything a `.wstemplate` file can know about one project.
//!
//! Templates historically saw only a project's calculated version. That is the
//! *next* version — `version.txt` is bumped on commit — so stamping it into a
//! dependency pin produces a reference that no consumer can resolve until the
//! next publish. Facts such as [`latest_tag`](FIELDS) close that gap by
//! reporting what has actually been published, alongside the identity and head
//! state a template usually needs.
//!
//! # Availability
//!
//! A field is either present with a real value or *unavailable with a reason* —
//! never present but empty. A project with no tags does not report an empty
//! `latest_tag`; it reports that it has no tags, and a template referencing that
//! field fails with that sentence instead of silently stamping `""`.

use crate::git_backend;
use crate::prelude::*;
use crate::state::run_cache::{HeadSnapshot, RunCache};
use crate::state::VersionInfo;
use serde_json::{json, Value};
use std::collections::BTreeMap;

/// One template variable exposed under `project.*` and `projects.ALIAS.*`.
pub struct FieldSpec {
    pub name: &'static str,
    pub description: &'static str,
    /// Whether resolving this field contacts the network.
    pub network: bool,
}

/// The complete catalogue of project fields.
///
/// Grouped by kind, and — apart from the two network fields — every entry is
/// resolved on every render, so `{% for k, v in projects.x %}` sees the whole
/// local set.
pub const FIELDS: &[FieldSpec] = &[
    // ── identity ──
    FieldSpec {
        name: "alias",
        description: "Tera alias this project is registered under",
        network: false,
    },
    FieldSpec {
        name: "name",
        description: "Project name from its .wsb/state.json",
        network: false,
    },
    FieldSpec {
        name: "path",
        description: "Absolute path to the project root",
        network: false,
    },
    FieldSpec {
        name: "relative_path",
        description: "Path from the workspace root, e.g. 'ext/gtest' for a submodule",
        network: false,
    },
    FieldSpec {
        name: "path_from_here",
        description: "Path from the file being rendered to this project, e.g. '../../capdag/capdag-rs' — what a local dependency is written as",
        network: false,
    },
    // ── calculated version ──
    FieldSpec {
        name: "version",
        description: "Full calculated version from version.txt, e.g. '1.649.0'",
        network: false,
    },
    FieldSpec {
        name: "major_version",
        description: "Major component, prefixed, e.g. 'v1'",
        network: false,
    },
    FieldSpec {
        name: "minor_version",
        description: "Minor component as a number, e.g. 649",
        network: false,
    },
    FieldSpec {
        name: "patch_version",
        description: "Patch component as a number",
        network: false,
    },
    // ── published tags ──
    FieldSpec {
        name: "latest_tag",
        description: "Highest tag in this clone, verbatim, e.g. 'v1.648.6494'",
        network: false,
    },
    FieldSpec {
        name: "latest_version",
        description: "latest_tag without its leading 'v' — the pin-ready form",
        network: false,
    },
    FieldSpec {
        name: "nearest_tag",
        description: "Newest tag reachable from HEAD (git describe)",
        network: false,
    },
    FieldSpec {
        name: "tag_count",
        description: "Number of tags in this clone, as a number",
        network: false,
    },
    FieldSpec {
        name: "latest_remote_tag",
        description: "Highest tag that exists on the remote (contacts the network)",
        network: true,
    },
    FieldSpec {
        name: "latest_remote_version",
        description: "latest_remote_tag without its leading 'v' (contacts the network)",
        network: true,
    },
    // ── head state ──
    FieldSpec {
        name: "commit",
        description: "Full HEAD commit hash",
        network: false,
    },
    FieldSpec {
        name: "short_commit",
        description: "Abbreviated HEAD commit hash (7 characters)",
        network: false,
    },
    FieldSpec {
        name: "commit_date",
        description: "HEAD commit date as YYYY-MM-DD",
        network: false,
    },
    FieldSpec {
        name: "commit_datetime",
        description: "HEAD commit timestamp as RFC 3339",
        network: false,
    },
    FieldSpec {
        name: "branch",
        description: "Checked-out branch name",
        network: false,
    },
    FieldSpec {
        name: "is_detached",
        description: "Whether HEAD is detached, as a boolean",
        network: false,
    },
    FieldSpec {
        name: "is_dirty",
        description: "Whether the worktree has uncommitted changes, as a boolean",
        network: false,
    },
    FieldSpec {
        name: "remote",
        description: "Name of the remote the project publishes to",
        network: false,
    },
    FieldSpec {
        name: "remote_url",
        description: "Fetch URL of that remote",
        network: false,
    },
];

/// Whether `name` is a field a template may reference.
pub fn is_known_field(name: &str) -> bool {
    FIELDS.iter().any(|field| field.name == name)
}

/// Whether resolving `fields` requires contacting a remote.
pub fn requires_network<'a, I: IntoIterator<Item = &'a str>>(fields: I) -> bool {
    fields.into_iter().any(|name| {
        FIELDS
            .iter()
            .any(|field| field.name == name && field.network)
    })
}

/// Comma-separated catalogue, for error messages.
fn field_catalogue() -> String {
    FIELDS
        .iter()
        .map(|field| field.name)
        .collect::<Vec<_>>()
        .join(", ")
}

/// Which project to gather facts for, and the version to report for it.
///
/// The version is supplied rather than read here because the project currently
/// being updated must report its freshly-calculated version, not the stale
/// contents of its `version.txt`.
pub struct ProjectIdentity<'a> {
    pub alias: &'a str,
    pub root: &'a Path,
    pub scan_root: &'a Path,
    pub version: &'a VersionInfo,
    /// Overrides the name recorded in `.wsb/state.json` when known already.
    pub name: Option<&'a str>,
}

/// Resolved facts for one project.
pub struct ProjectFacts {
    label: String,
    values: BTreeMap<String, Value>,
    unavailable: BTreeMap<String, String>,
    /// Whether network fields were resolved for this snapshot.
    pub resolved_remote: bool,
}

impl ProjectFacts {
    /// The values to expose to Tera.
    pub fn values(&self) -> &BTreeMap<String, Value> {
        &self.values
    }

    /// Fields that do not apply to this project, mapped to the reason why.
    pub fn unavailable(&self) -> &BTreeMap<String, String> {
        &self.unavailable
    }

    /// Fail unless `field` is a real field carrying a real value.
    ///
    /// Called for every field a template references, before rendering, so that
    /// an unusable reference reports *why* it is unusable rather than surfacing
    /// as Tera's generic "variable not found".
    pub fn require(&self, field: &str) -> Result<()> {
        if self.values.contains_key(field) {
            return Ok(());
        }
        if let Some(reason) = self.unavailable.get(field) {
            bail!("{} has no '{}': {}", self.label, field, reason);
        }
        bail!(
            "'{}' is not a wstemplate project field.\nAvailable fields: {}",
            field,
            field_catalogue()
        );
    }
}

/// Collects values and the reasons missing ones are missing.
struct FactBuilder {
    label: String,
    values: BTreeMap<String, Value>,
    unavailable: BTreeMap<String, String>,
}

impl FactBuilder {
    fn set(&mut self, field: &str, value: Value) {
        debug_assert!(is_known_field(field), "undeclared field '{field}'");
        self.values.insert(field.to_string(), value);
    }

    /// Record that `field` cannot be resolved, and why.
    fn missing(&mut self, field: &str, reason: impl Into<String>) {
        debug_assert!(is_known_field(field), "undeclared field '{field}'");
        self.unavailable.insert(field.to_string(), reason.into());
    }

    fn missing_all(&mut self, fields: &[&str], reason: &str) {
        for field in fields {
            self.missing(field, reason.to_string());
        }
    }
}

/// Fields that only exist once the project is a git repository of its own.
const GIT_FIELDS: &[&str] = &[
    "latest_tag",
    "latest_version",
    "nearest_tag",
    "tag_count",
    "latest_remote_tag",
    "latest_remote_version",
    "commit",
    "short_commit",
    "commit_date",
    "commit_datetime",
    "branch",
    "is_detached",
    "is_dirty",
    "remote",
    "remote_url",
];

/// Fields that need a commit to exist.
const HEAD_FIELDS: &[&str] = &[
    "commit",
    "short_commit",
    "commit_date",
    "commit_datetime",
    "is_dirty",
    "nearest_tag",
];

/// Fields that need a resolvable remote.
const REMOTE_FIELDS: &[&str] = &[
    "remote",
    "remote_url",
    "latest_remote_tag",
    "latest_remote_version",
];

/// Resolve every fact about `identity`.
///
/// `with_remote` opts into the two network fields; when false they are marked
/// unavailable rather than silently absent, so referencing one without opting in
/// is impossible (the caller derives the flag from the template's own text).
pub fn gather(identity: &ProjectIdentity<'_>, with_remote: bool) -> Result<ProjectFacts> {
    gather_with_cache(identity, with_remote, &RunCache::new())
}

/// The same, reusing what a run has already read.
///
/// Everything the cache serves here is a fact about refs and remotes, which an
/// update does not move — see [`RunCache`] for the rule and for the one fact
/// (`is_dirty`) that is deliberately left out of it, because writing files is
/// exactly what an update does.
pub fn gather_with_cache(
    identity: &ProjectIdentity<'_>,
    with_remote: bool,
    cache: &RunCache,
) -> Result<ProjectFacts> {
    let mut builder = FactBuilder {
        label: format!(
            "Project '{}' at {}",
            identity.alias,
            identity.root.display()
        ),
        values: BTreeMap::new(),
        unavailable: BTreeMap::new(),
    };

    gather_identity(&mut builder, identity)?;
    gather_version(&mut builder, identity.version);
    gather_git(&mut builder, identity.root, with_remote, cache)?;

    Ok(ProjectFacts {
        label: builder.label,
        values: builder.values,
        unavailable: builder.unavailable,
        resolved_remote: with_remote,
    })
}

fn gather_identity(builder: &mut FactBuilder, identity: &ProjectIdentity<'_>) -> Result<()> {
    builder.set("alias", json!(identity.alias));
    builder.set("path", json!(identity.root.display().to_string()));
    // Resolved by the render engine rather than here: it is the path from the
    // FILE BEING WRITTEN to this project, so it is a different answer for two
    // templates of the same project and cannot be a cached fact. Declared as
    // unavailable so that asking about it outside a render says why.
    builder.missing(
        "path_from_here",
        "it is resolved while rendering, from the file being written".to_string(),
    );

    match identity.root.strip_prefix(identity.scan_root) {
        Ok(relative) if relative.as_os_str().is_empty() => builder.set("relative_path", json!(".")),
        Ok(relative) => {
            let text = relative
                .to_str()
                .with_context(|| {
                    format!(
                        "Path of project '{}' is not valid UTF-8: {}",
                        identity.alias,
                        identity.root.display()
                    )
                })?
                .replace(std::path::MAIN_SEPARATOR, "/");
            builder.set("relative_path", json!(text));
        }
        Err(_) => builder.missing(
            "relative_path",
            format!(
                "it lives outside the workspace root {}",
                identity.scan_root.display()
            ),
        ),
    }

    let name = match identity.name {
        Some(name) => Some(name.to_string()),
        None => read_project_name(identity.root)?,
    };
    match name {
        Some(name) => builder.set("name", json!(name)),
        None => builder.missing(
            "name",
            "its .wsb/state.json records no project_name — run 'wsb init' there",
        ),
    }
    Ok(())
}

/// Read `project_name` out of a project's own `.wsb/state.json`.
fn read_project_name(root: &Path) -> Result<Option<String>> {
    #[derive(Deserialize)]
    struct NameOnly {
        #[serde(default)]
        project_name: Option<String>,
    }

    let state_path = root.join(".wsb").join("state.json");
    if !state_path.is_file() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(&state_path)
        .with_context(|| format!("Cannot read {}", state_path.display()))?;
    let state: NameOnly = serde_json::from_str(&content)
        .with_context(|| format!("Cannot parse {}", state_path.display()))?;
    Ok(state.project_name.filter(|name| !name.trim().is_empty()))
}

fn gather_version(builder: &mut FactBuilder, version: &VersionInfo) {
    builder.set("version", json!(version.full_version));
    builder.set("major_version", json!(version.major_version));
    builder.set("minor_version", json!(version.minor_version));
    builder.set("patch_version", json!(version.patch_version));
}

fn gather_git(
    builder: &mut FactBuilder,
    root: &Path,
    with_remote: bool,
    cache: &RunCache,
) -> Result<()> {
    // `open` rather than `discover`: facts must describe this project, never an
    // ancestor repository that merely happens to contain it.
    let repo = match git_backend::open_repo(root) {
        Ok(repo) => repo,
        Err(_) => {
            builder.missing_all(GIT_FIELDS, "it is not a git repository");
            return Ok(());
        }
    };

    gather_head(builder, &repo, root, cache)?;
    gather_tags(builder, &repo, root, with_remote, cache)?;
    Ok(())
}

fn gather_head(
    builder: &mut FactBuilder,
    repo: &gix::Repository,
    root: &Path,
    cache: &RunCache,
) -> Result<()> {
    // HEAD is read once per repository per run. An update writes files; it does
    // not commit, and it does not check anything out, so nothing below can be a
    // different answer later in the same run.
    let head = cache.head(root, || {
        let detached = git_backend::is_detached_head(repo)
            .context("Failed to determine whether HEAD is detached")?;
        let branch = if detached {
            None
        } else {
            Some(
                git_backend::current_branch(repo)
                    .context("Failed to read the current branch")?,
            )
        };
        let commit = match repo.head_commit() {
            Ok(commit) => {
                let time = commit
                    .time()
                    .context("Failed to read the HEAD commit time")?;
                Some((
                    commit.id().to_hex().to_string(),
                    time.seconds,
                    time.offset,
                ))
            }
            Err(_) => None,
        };
        Ok(HeadSnapshot {
            detached,
            branch,
            commit,
        })
    })?;

    builder.set("is_detached", json!(head.detached));

    match &head.branch {
        Some(branch) => builder.set("branch", json!(branch)),
        None => builder.missing("branch", "HEAD is detached"),
    }

    let Some((id, seconds, offset)) = &head.commit else {
        builder.missing_all(HEAD_FIELDS, "it has no commits yet");
        return Ok(());
    };

    builder.set(
        "short_commit",
        json!(id.chars().take(7).collect::<String>()),
    );
    builder.set("commit", json!(id));

    let offset = chrono::FixedOffset::east_opt(*offset)
        .with_context(|| format!("HEAD commit carries an invalid timezone offset {offset}"))?;
    let stamp = chrono::DateTime::from_timestamp(*seconds, 0)
        .with_context(|| format!("HEAD commit carries an invalid timestamp {seconds}"))?
        .with_timezone(&offset);
    builder.set("commit_date", json!(stamp.format("%Y-%m-%d").to_string()));
    builder.set("commit_datetime", json!(stamp.to_rfc3339()));

    // The one fact an update changes, and so the one that is never remembered:
    // rendering a manifest into a clean worktree makes it dirty, and a project
    // updated later in the run has to see that.
    builder.set(
        "is_dirty",
        json!(!git_backend::is_clean(repo).context("Failed to read the worktree status")?),
    );
    Ok(())
}

fn gather_tags(
    builder: &mut FactBuilder,
    repo: &gix::Repository,
    root: &Path,
    with_remote: bool,
    cache: &RunCache,
) -> Result<()> {
    let tags = cache.tags(root, || {
        git_backend::list_tags(repo).context("Failed to list tags")
    })?;
    builder.set("tag_count", json!(tags.len()));

    match tags.first() {
        Some(tag) => {
            builder.set("latest_tag", json!(tag));
            set_tag_version(builder, "latest_version", "latest_tag", tag);
        }
        None => {
            builder.missing("latest_tag", "it has no tags");
            builder.missing("latest_version", "it has no tags");
        }
    }

    // `nearest_tag` is only meaningful with a commit to describe; a repo with no
    // commits already marked it unavailable.
    if builder.values.contains_key("commit") {
        let nearest = cache.nearest_tag(root, || {
            git_backend::nearest_tag(repo, None).context("Failed to describe HEAD")
        })?;
        match nearest.as_ref() {
            Some(tag) => builder.set("nearest_tag", json!(tag)),
            None => builder.missing("nearest_tag", "no tag is reachable from HEAD"),
        }
    }

    let remote = match publishing_remote(repo, root, cache).as_ref() {
        Ok(remote) => remote.clone(),
        Err(reason) => {
            builder.missing_all(REMOTE_FIELDS, reason);
            return Ok(());
        }
    };
    builder.set("remote", json!(remote));
    builder.set(
        "remote_url",
        json!(cache
            .remote_url(root, &remote, || {
                git_backend::remote_url(repo, &remote)
                    .with_context(|| format!("Failed to read the URL of remote '{remote}'"))
            })?
            .as_str()),
    );

    if !with_remote {
        // Rendering stays offline unless something asks for a published tag, so
        // the reason has to point at how to opt in rather than at a defect.
        let reason = "the remote was not contacted — reference the field in a \
                      template, or pass --remote, to resolve it";
        builder.missing("latest_remote_tag", reason);
        builder.missing("latest_remote_version", reason);
        return Ok(());
    }

    // The only fact here that costs a network round trip. Before it was cached,
    // a recursive update asked GitHub 48 times about 7 projects.
    let remote_tags = cache.remote_tags(root, &remote, || {
        git_backend::remote_tags(repo, &remote)
            .with_context(|| format!("Failed to list tags on remote '{remote}'"))
    })?;
    match remote_tags.first() {
        Some(tag) => {
            builder.set("latest_remote_tag", json!(tag));
            set_tag_version(builder, "latest_remote_version", "latest_remote_tag", tag);
        }
        None => {
            let reason = format!("remote '{remote}' has no tags");
            builder.missing("latest_remote_tag", reason.clone());
            builder.missing("latest_remote_version", reason);
        }
    }
    Ok(())
}

/// Derive the pin-ready form of a tag: `v1.2.3` → `1.2.3`.
///
/// A tag that is not a version number has no version form, and says so — a
/// release named `nightly` must not be stamped into a version constraint.
fn set_tag_version(builder: &mut FactBuilder, field: &str, source_field: &str, tag: &str) {
    let candidate = tag.strip_prefix('v').unwrap_or(tag);
    if candidate.starts_with(|c: char| c.is_ascii_digit()) {
        builder.set(field, json!(candidate));
    } else {
        builder.missing(
            field,
            format!("{source_field} is '{tag}', which is not a version number"),
        );
    }
}

/// Pick the remote a project publishes to.
///
/// The choice must be unambiguous: a lone remote, or `origin` when several
/// exist. Anything else is reported as a reason rather than guessed at.
#[allow(clippy::type_complexity)]
fn publishing_remote(
    repo: &gix::Repository,
    root: &Path,
    cache: &RunCache,
) -> Arc<std::result::Result<String, String>> {
    // `git remote` is a subprocess, and a recursive update ran 144 of them for
    // 43 repositories. An update does not add or remove a remote.
    let remotes = cache.remotes(root, || {
        // `remotes` fails hard when none are configured, which is an ordinary
        // state for a local-only project rather than a broken repository.
        git_backend::remotes(repo).map_err(|_| "it has no remotes configured".to_string())
    });

    Arc::new(match remotes.as_ref() {
        Err(reason) => Err(reason.clone()),
        Ok(remotes) if remotes.len() == 1 => Ok(remotes[0].clone()),
        Ok(remotes) if remotes.iter().any(|remote| remote == "origin") => {
            Ok("origin".to_string())
        }
        Ok(remotes) => Err(format!(
            "it has several remotes ({}) and none named 'origin', so the one it publishes to is ambiguous",
            remotes.join(", ")
        )),
    })
}

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

    fn version() -> VersionInfo {
        VersionInfo {
            major_version: "v1".to_string(),
            minor_version: 2,
            patch_version: 3,
            full_version: "1.2.3".to_string(),
        }
    }

    fn facts_for(root: &Path, scan_root: &Path) -> ProjectFacts {
        let version = version();
        gather(
            &ProjectIdentity {
                alias: "demo",
                root,
                scan_root,
                version: &version,
                name: None,
            },
            false,
        )
        .unwrap()
    }

    /// A repository with one commit, so head facts are resolvable.
    fn seed_repo(root: &Path) -> gix::Repository {
        let repo = git_backend::init_repository(root).unwrap();
        git_backend::configure_local_user(&repo, "Test User", "test@example.com").unwrap();
        fs::write(root.join("README.md"), "hello\n").unwrap();
        git_backend::stage_paths(&repo, &["README.md".to_string()]).unwrap();
        git_backend::commit_all(&repo, "initial").unwrap();
        git_backend::open_repo(root).unwrap()
    }

    #[test]
    fn every_declared_field_is_either_valued_or_explained() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("proj");
        fs::create_dir_all(&root).unwrap();
        seed_repo(&root);

        let facts = facts_for(&root, workspace.path());
        for field in FIELDS {
            assert!(
                facts.values.contains_key(field.name) || facts.unavailable.contains_key(field.name),
                "field '{}' is neither resolved nor explained",
                field.name
            );
        }
    }

    #[test]
    fn a_project_without_tags_explains_the_absence_instead_of_stamping_empty() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("proj");
        fs::create_dir_all(&root).unwrap();
        seed_repo(&root);

        let facts = facts_for(&root, workspace.path());
        assert!(!facts.values.contains_key("latest_tag"));
        let err = facts.require("latest_tag").unwrap_err().to_string();
        assert!(err.contains("has no tags"), "got: {err}");
        assert!(
            err.contains("demo"),
            "error must name the project, got: {err}"
        );
    }

    #[test]
    fn the_newest_tag_wins_over_older_and_non_version_tags() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("proj");
        fs::create_dir_all(&root).unwrap();
        let repo = seed_repo(&root);
        git_backend::create_tag(&repo, "v1.9.0", "old").unwrap();
        git_backend::create_tag(&repo, "v1.10.0", "new").unwrap();
        git_backend::create_tag(&repo, "nightly", "not a version").unwrap();

        let facts = facts_for(&root, workspace.path());
        // Numeric precedence, not lexicographic: 1.10.0 is newer than 1.9.0.
        assert_eq!(facts.values["latest_tag"], json!("v1.10.0"));
        assert_eq!(facts.values["latest_version"], json!("1.10.0"));
        assert_eq!(facts.values["tag_count"], json!(3));
    }

    #[test]
    fn a_non_version_tag_has_no_pin_ready_form() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("proj");
        fs::create_dir_all(&root).unwrap();
        let repo = seed_repo(&root);
        git_backend::create_tag(&repo, "nightly", "not a version").unwrap();

        let facts = facts_for(&root, workspace.path());
        assert_eq!(facts.values["latest_tag"], json!("nightly"));
        let err = facts.require("latest_version").unwrap_err().to_string();
        assert!(
            err.contains("not a version number"),
            "a non-version tag must not become a pin, got: {err}"
        );
    }

    #[test]
    fn network_fields_are_withheld_until_a_template_asks_for_them() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("proj");
        fs::create_dir_all(&root).unwrap();
        seed_repo(&root);

        let facts = facts_for(&root, workspace.path());
        let err = facts.require("latest_remote_tag").unwrap_err().to_string();
        assert!(
            err.contains("remote was not contacted") || err.contains("no remotes"),
            "got: {err}"
        );
    }

    #[test]
    fn a_plain_directory_reports_why_git_facts_are_missing() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("proj");
        fs::create_dir_all(&root).unwrap();

        let facts = facts_for(&root, workspace.path());
        let err = facts.require("commit").unwrap_err().to_string();
        assert!(err.contains("not a git repository"), "got: {err}");
        // Version and identity still resolve without git.
        assert_eq!(facts.values["version"], json!("1.2.3"));
        assert_eq!(facts.values["relative_path"], json!("proj"));
    }

    #[test]
    fn nested_projects_report_their_path_from_the_workspace_root() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("ext").join("gtest");
        fs::create_dir_all(&root).unwrap();

        let facts = facts_for(&root, workspace.path());
        assert_eq!(facts.values["relative_path"], json!("ext/gtest"));
    }

    #[test]
    fn an_unknown_field_lists_the_ones_that_exist() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("proj");
        fs::create_dir_all(&root).unwrap();

        let facts = facts_for(&root, workspace.path());
        let err = facts
            .require("published_yesterday")
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("is not a wstemplate project field"),
            "got: {err}"
        );
        assert!(err.contains("latest_tag"), "got: {err}");
    }

    #[test]
    fn head_facts_describe_the_checked_out_commit() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("proj");
        fs::create_dir_all(&root).unwrap();
        let repo = seed_repo(&root);
        let head = repo.head_commit().unwrap().id().to_hex().to_string();

        let facts = facts_for(&root, workspace.path());
        assert_eq!(facts.values["commit"], json!(head));
        assert_eq!(facts.values["short_commit"], json!(head[..7].to_string()));
        assert_eq!(facts.values["is_detached"], json!(false));
        assert_eq!(facts.values["is_dirty"], json!(false));
        assert_eq!(
            facts.values["commit_date"].as_str().unwrap().len(),
            "YYYY-MM-DD".len()
        );
    }

    #[test]
    fn a_dirty_worktree_is_reported_as_dirty() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path().join("proj");
        fs::create_dir_all(&root).unwrap();
        seed_repo(&root);
        fs::write(root.join("README.md"), "changed\n").unwrap();

        let facts = facts_for(&root, workspace.path());
        assert_eq!(facts.values["is_dirty"], json!(true));
    }

    #[test]
    fn network_is_required_only_for_remote_fields() {
        assert!(requires_network(["latest_remote_tag"]));
        assert!(!requires_network(["latest_tag", "version", "commit"]));
    }
}