wsb 0.253.6349

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
//! Nothing is released from a tree rendered against this machine.
//!
//! # What this is about
//!
//! `wsb local on` re-renders the fleet's generated manifests with the
//! workspace's local variable set (declared in `.wsb/stamp.json`), so a
//! dependency written ordinarily as a published tag becomes a path to the
//! working copy next door. It is how a change to one library gets built
//! against before it is committed, tagged and published, and it is
//! indispensable — and it is also a shape that resolves on exactly one
//! machine.
//!
//! Every release door therefore asks this module first. A crate published with
//! a `path` dependency is refused by the registry; but a BINARY built from one
//! is not refused by anything. It links against whatever happened to be in the
//! working copy that afternoon, ships, and claims a version whose tag contains
//! something else. That artifact is unreproducible from any commit, and nothing
//! downstream can tell.
//!
//! # Why the templates decide, and not a list of shapes
//!
//! The obvious implementation is a list of ecosystem patterns — `path = ".."`
//! in Cargo, `file:..` in npm, `replace … => ..` in go. It is wrong in both
//! directions: a fleet can have legitimate committed cross-repository path
//! dependencies, deliberately and permanently, so the pattern over-reports; and a
//! local render is not always a path at all (a go.mod's local branch also
//! rewrites a version to the `v0.0.0` placeholder a replaced module takes), so
//! it under-reports too.
//!
//! What actually defines the local render is the template that produces it. So
//! that is what is read: each `{% if env.<variable> %}` block is resolved
//! both ways, every `{{ … }}` becomes a wildcard, and a line the LOCAL form
//! could produce and the other form could not is the evidence. A template that
//! grows a new local branch is covered the day it is written, and a shape this
//! module never heard of is covered too.
//!
//! # Two doors, asking different questions
//!
//! A RELEASE door asks whether anything here was built against a working
//! copy. Every local render answers yes, whatever it points at, because the
//! artifact is unreproducible from a commit either way.
//!
//! A STAGING door — anything that copies the whole workspace somewhere else —
//! asks something narrower: whether the tree still resolves once it is
//! somewhere else. Most of the local render does. `path = "../../lib/lib-rs"`
//! is read against a manifest inside the workspace, and the copy holds the
//! whole workspace, so it names the same directory there under a different
//! root. What does NOT survive the copy is a reference that leaves the
//! workspace: an absolute `file:///home/…/lib-py` names a directory on one
//! workstation, and the copy has never heard of it.
//!
//! So [`escaping`] is what a staging door asks, and it is not a lenient
//! version of the release check — it is a different predicate.

use std::path::{Path, PathBuf};

/// Directory names never walked.
///
/// Dependencies, build output and scrap. A `node_modules` holds thousands of
/// third-party manifests, and none of them is generated from a template here.
const SKIPPED: &[&str] = &[
    ".git",
    ".wsb",
    ".scrap",
    "node_modules",
    "target",
    "build",
    "dist",
    ".venv",
    "venv",
    "__pycache__",
];

/// The wildcard a `{{ … }}` expression becomes.
///
/// A character no manifest contains, so a pattern can be split on it without
/// an escape convention.
const HOLE: char = '\u{0}';

/// A generated file that carries the local render.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalRender {
    /// The rendered manifest, relative to the directory that was scanned.
    pub file: String,
    /// 1-based line in that file.
    pub line: usize,
    /// The line itself, trimmed. Shown because the whole point of the refusal
    /// is that the operator recognises what they turned on.
    pub text: String,
    /// The references this branch produced that name a place outside the
    /// workspace, with any URL scheme removed — empty when everything it
    /// points at is inside.
    ///
    /// This is the whole difference between a render that can be copied into a
    /// guest and one that cannot, so it is recorded when the finding is made
    /// rather than re-derived by each caller from the text.
    pub escapes: Vec<String>,
}

impl LocalRender {
    /// The file, the line, and the line itself.
    ///
    /// The whole point of the refusal is that whoever reads it recognises what
    /// they turned on, so it shows the manifest saying it rather than asserting
    /// that one does.
    pub fn message(&self) -> String {
        format!("{}:{}  {}", self.file, self.line, self.text)
    }

    /// Whether this render survives the workspace being copied elsewhere.
    ///
    /// True for every reference that stays inside the workspace: the copy
    /// contains it, at the same place relative to the manifest that names it.
    pub fn travels(&self) -> bool {
        self.escapes.is_empty()
    }
}

/// What to say when a release door finds any of these.
///
/// One sentence for the state, the evidence, and the one command that undoes
/// it. Built here rather than at each door so a refusal reads the same from
/// `wsb publish`, `wsb ship` and a verdict table — and so the command that
/// takes the render back is named in exactly one place.
pub fn refusal(found: &[LocalRender]) -> String {
    // Enough to recognise the state without pasting forty manifests into a
    // terminal. A fleet in local mode has every one of them.
    const SHOWN: usize = 5;
    let mut lines: Vec<String> = found
        .iter()
        .take(SHOWN)
        .map(|one| format!("      {}", one.message()))
        .collect();
    if found.len() > SHOWN {
        lines.push(format!("      … and {} more", found.len() - SHOWN));
    }
    format!(
        "this tree is rendered against this machine — `wsb local on` has not been taken back. \
         {} generated manifest(s) point at working copies here:\n{}\n  Nothing built from them \
         can be reproduced from a commit, and no registry refuses a binary. Take the render back \
         first:\n      wsb local off",
        found.len(),
        lines.join("\n")
    )
}

/// The findings a door that COPIES the workspace has to refuse.
///
/// Everything else in `found` is a local render too, and a release door
/// refuses all of it. This is the subset that names something the copy will
/// not contain.
pub fn escaping(found: &[LocalRender]) -> Vec<&LocalRender> {
    found.iter().filter(|one| !one.travels()).collect()
}

/// What to say when a door that copies the workspace finds a reference that
/// cannot come with it.
///
/// Deliberately not [`refusal`]'s wording. That one says "take the render
/// back", which is the right instruction before a release and the wrong one
/// here: local mode is not the problem, one reference that leaves the
/// workspace is, and an operator told to turn local mode off loses the working
/// copies they are in the middle of testing for no reason.
pub fn staging_refusal(escaping: &[&LocalRender]) -> String {
    let mut lines: Vec<String> = Vec::new();
    for one in escaping {
        lines.push(format!("      {}", one.message()));
        for reference in &one.escapes {
            lines.push(format!("        names {reference}"));
        }
    }
    format!(
        "{} reference(s) in this tree's generated manifests name a place \
         OUTSIDE the workspace, and copying the workspace does not bring \
         them:\n{}\n  A local render that stays inside the workspace travels \
         with it and is no obstacle here. Give these one relative to the \
         manifest that names them — or, if that is not expressible, take the \
         render back:\n      wsb local off",
        escaping.len(),
        lines.join("\n")
    )
}

/// Why a generated file still carries the local render after a take-back.
///
/// There are two of these and they call for opposite responses, so nothing may
/// report one while meaning the other. `wsb local off` restores what is
/// COMMITTED, which makes a committed local render a fixed point that no
/// take-back can escape — that is [`Persistence::Committed`], and it means a
/// repository's HISTORY needs repairing. But a file the take-back never
/// reached is untouched for a duller reason and its history is fine: that is
/// [`Persistence::NotRestored`], and a fresh render fixes it with nothing to
/// repair afterwards.
///
/// Stating the first while meaning the second sends whoever reads it to
/// rewrite manifests that were already correct.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Persistence {
    /// The committed form carries the local render too. Restoring what is
    /// committed restores it, and every `checkpoint` re-pushes it.
    Committed,
    /// The committed form is clean. The take-back simply did not run here —
    /// `wsb local off` restores the repositories in its own update scope, and
    /// a nested submodule outside that scope keeps its working-tree render.
    NotRestored,
    /// Git does not track the file, so there is no committed form to compare
    /// against. Reported rather than folded into either answer: a generated
    /// manifest nobody committed is its own thing to notice.
    Untracked,
}

impl Persistence {
    /// What this state means for the operator, in one clause.
    pub fn describe(self) -> &'static str {
        match self {
            Self::Committed => "committed local render — the history carries it",
            Self::NotRestored => "not restored — the take-back did not reach this repository",
            Self::Untracked => "untracked — git holds no committed form of it",
        }
    }
}

/// Why one finding survived the take-back, read from git rather than assumed.
///
/// The template is re-read and applied to the COMMITTED bytes: the same
/// predicate that found the render on disk, asked of what a fresh clone would
/// get. Anything that cannot be resolved — no repository, no HEAD, an
/// unreadable blob — is [`Persistence::Untracked`], because the honest answer
/// to "what does the history say" when the history cannot be read is not
/// "the history is broken".
pub fn persistence(root: &Path, one: &LocalRender, variable: &str) -> Persistence {
    let rendered = root.join(&one.file);
    let template = PathBuf::from(format!("{}.wstemplate", rendered.display()));
    let Ok(template_text) = std::fs::read_to_string(&template) else {
        return Persistence::Untracked;
    };
    let Ok(repo) = gix::discover(rendered.parent().unwrap_or(root)) else {
        return Persistence::Untracked;
    };
    let Some(workdir) = repo.workdir().map(Path::to_path_buf) else {
        return Persistence::Untracked;
    };
    let Ok(relative) = rendered.strip_prefix(&workdir) else {
        return Persistence::Untracked;
    };
    let Ok(commit) = repo.head_commit() else {
        return Persistence::Untracked;
    };
    let Ok(mut tree) = commit.tree() else {
        return Persistence::Untracked;
    };
    let Ok(Some(entry)) = tree.peel_to_entry_by_path(relative) else {
        return Persistence::Untracked;
    };
    let Ok(object) = entry.object() else {
        return Persistence::Untracked;
    };
    let Ok(committed) = std::str::from_utf8(&object.data) else {
        return Persistence::Untracked;
    };
    if carried_by(&template_text, committed, variable).is_empty() {
        Persistence::NotRestored
    } else {
        Persistence::Committed
    }
}

/// Every generated file the WORKSPACE carries the local render in, asked from
/// anywhere inside it.
///
/// "Is this fleet local" is a question about the whole nesting tree, and this
/// workspace is submodules all the way down: asked of a submodule it answers
/// for that submodule alone. A `checkpoint` run from inside a submodule
/// scanned a repository that has no local templates in it at all, found
/// nothing, and committed the whole fleet's local render with a clean bill of
/// health.
///
/// So the root is resolved as the most senior repository — the superproject —
/// and every caller that is answering for the fleet
/// uses this rather than [`scan`].
pub fn scan_workspace(start: &Path, variable: &str) -> Result<Vec<LocalRender>, String> {
    let root = crate::workspace::find_super_root(start).unwrap_or_else(|| start.to_path_buf());
    scan(&root, variable)
}

/// Every generated file under `dir` that carries the local render.
///
/// Walks for templates, not for manifests: a generated file is exactly a
/// `*.wstemplate` with the suffix removed, so the templates ARE the list, and
/// a manifest nothing generates is none of this module's business.
///
/// Errors are I/O errors on files that are there. A template whose rendered
/// form does not exist yet is not an error — an update has not run — and a
/// directory that cannot be read is skipped, because a release must not be
/// refused over a permission bit on some unrelated scrap directory.
pub fn scan(dir: &Path, variable: &str) -> Result<Vec<LocalRender>, String> {
    let mut found = Vec::new();
    for template_path in templates_under(dir) {
        let template = match std::fs::read_to_string(&template_path) {
            Ok(text) => text,
            Err(e) => {
                return Err(format!(
                    "reading {}: {e}",
                    template_path.display()
                ))
            }
        };
        if !template.contains(variable) {
            continue;
        }
        let rendered_path = rendered_form(&template_path);
        let Ok(rendered) = std::fs::read_to_string(&rendered_path) else {
            // Not rendered yet. Nothing on disk points anywhere.
            continue;
        };
        // Named from the workspace, with `/` on every platform: the same
        // file is the same finding wherever it was scanned.
        let relative =
            crate::platform::slash_path(rendered_path.strip_prefix(dir).unwrap_or(&rendered_path));
        // One finding per file. A local branch is several lines — a comment
        // saying so, then the dependency — and reporting each of them would
        // bury twenty files under sixty lines.
        if let Some(carried) = carried_by(&template, &rendered, variable).into_iter().next() {
            let escapes = escaping_references(dir, &rendered_path, &carried.block);
            found.push(LocalRender {
                file: relative,
                line: carried.line,
                text: carried.text,
                escapes,
            });
        }
    }
    found.sort_by(|a, b| a.file.cmp(&b.file));
    Ok(found)
}

/// Whether any template's local render names something under the build
/// root — something built from a sibling project, which `local on` has to
/// build and hold for as long as the tree is local.
///
/// Read from the templates, not from what is rendered, so turning local mode
/// on and off asks the same question and gets the same answer. A fleet whose
/// local branches read no `build.*` has nothing to build.
pub fn local_render_reads_build_root(dir: &Path, variable: &str) -> Result<bool, String> {
    for template_path in templates_under(dir) {
        let template = std::fs::read_to_string(&template_path)
            .map_err(|e| format!("reading {}: {e}", template_path.display()))?;
        if !template.contains(variable) {
            continue;
        }
        let references = crate::state::template_refs::TemplateReferences::parse(&template)
            .map_err(|e| format!("{}: {e:#}", template_path.display()))?;
        if !references.build_fields().is_empty() {
            return Ok(true);
        }
    }
    Ok(false)
}

/// The references in one local branch that will not resolve once the
/// workspace is somewhere else.
///
/// `root` is the directory that gets copied; `manifest` is the rendered file
/// the branch landed in. A relative reference is read against the manifest's
/// own directory — which is how Cargo, npm, go and SwiftPM all read one — so
/// it travels with the tree for exactly as long as it stays inside it.
fn escaping_references(root: &Path, manifest: &Path, block: &[String]) -> Vec<String> {
    let mut escaping: Vec<String> = Vec::new();
    for line in block {
        for reference in references(line) {
            if escapes(root, manifest, &reference) && !escaping.contains(&reference) {
                escaping.push(reference);
            }
        }
    }
    escaping
}

/// Every path-like token in one rendered line, with any URL scheme removed.
///
/// Quoted and bare both, because the ecosystems disagree: Cargo, npm and
/// SwiftPM quote their paths and a `go.mod` replace directive does not. So the
/// line is cut on whitespace AND on quotes, and each piece is judged on its
/// own.
///
/// A piece is path-like when it carries a separator or opens a relative path,
/// AND contains something nameable. That second clause is not decoration: a
/// local branch opens with a comment, `//` is a comment marker in two of these
/// languages, and `//` read as a path is the filesystem ROOT — which would
/// report every Swift and Go local render as escaping the workspace.
///
/// A piece carrying `://` after the scheme is stripped is a URL with a host,
/// which is the one thing in a manifest that looks like a path and is not.
fn references(line: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for piece in line.split(|c: char| c.is_whitespace() || c == '"' || c == '\'') {
        let token = piece.trim_matches(|c: char| matches!(c, ',' | ';' | ')' | '=' | '>' | '<'));
        if !token.chars().any(char::is_alphanumeric) {
            continue;
        }
        let path = token
            .strip_prefix("file://")
            .or_else(|| token.strip_prefix("file:"))
            .unwrap_or(token);
        if path.contains("://") {
            continue;
        }
        let path_like = is_absolute_anywhere(path)
            || path.contains('/')
            || path.contains('\\')
            || path.starts_with('.');
        if path_like && !out.iter().any(|seen| seen == path) {
            out.push(path.to_string());
        }
    }
    out
}

/// Whether one reference names something the copy will not contain.
fn escapes(root: &Path, manifest: &Path, reference: &str) -> bool {
    if is_absolute_anywhere(reference) {
        return true;
    }
    let Some(dir) = manifest.parent() else {
        // A manifest with no parent directory is not a file this scan produced.
        return true;
    };
    // Separators normalised before joining: a Windows-shaped relative path is
    // one component to a POSIX `Path`, so `..\..\elsewhere` would be read as a
    // single directory NAME and judged to be inside the workspace.
    let reference = reference.replace('\\', "/");
    !normalised(&dir.join(reference)).starts_with(normalised(root))
}

/// Whether a reference is absolute on ANY platform this workspace targets.
///
/// Spelled out rather than asked of [`Path::is_absolute`], which answers for
/// the platform the check happens to be running on. A workspace scanned on
/// Linux stages into Windows guests, and `C:\\Users\\…` is a path that leaves
/// the workspace whoever is looking at it.
fn is_absolute_anywhere(reference: &str) -> bool {
    let bytes = reference.as_bytes();
    reference.starts_with('/')
        || reference.starts_with('\\')
        || reference.starts_with('~')
        || (bytes.len() >= 3
            && bytes[0].is_ascii_alphabetic()
            && bytes[1] == b':'
            && (bytes[2] == b'/' || bytes[2] == b'\\'))
}

/// A path with `.` and `..` resolved by TEXT, without touching the disk.
///
/// Lexical on purpose. The question is where a reference points, and
/// `std::fs::canonicalize` answers a different one — it fails on a path that
/// does not exist yet, and it follows symlinks, so a workspace reached through
/// one would compare unequal to itself.
fn normalised(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for part in path.components() {
        match part {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                out.pop();
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// The file a template renders to: its own path with `.wstemplate` removed.
fn rendered_form(template: &Path) -> PathBuf {
    let name = template.to_string_lossy();
    PathBuf::from(name.trim_end_matches(".wstemplate").to_string())
}

/// Every `*.wstemplate` under `dir`, skipping what [`SKIPPED`] names.
fn templates_under(dir: &Path) -> Vec<PathBuf> {
    walkdir::WalkDir::new(dir)
        .follow_links(false)
        .into_iter()
        .filter_entry(|entry| {
            entry.depth() == 0
                || !entry
                    .file_name()
                    .to_str()
                    .is_some_and(|name| SKIPPED.contains(&name))
        })
        .filter_map(Result::ok)
        .filter(|entry| entry.file_type().is_file())
        .map(|entry| entry.into_path())
        .filter(|path| {
            path.to_str()
                .is_some_and(|name| name.ends_with(".wstemplate"))
        })
        .collect()
}

/// The lines of `rendered` that only the local branch of `template` could have
/// produced.
///
/// Separated from the walk so the decision can be tested on text alone — which
/// is the half that can be wrong in an interesting way.
///
/// The unit of evidence is a CONDITIONAL, not a line. A line on its own is not
/// enough: `path = "…"` is what a local branch emits, and it is also what a
/// deliberate, permanent, committed path dependency two tables further down
/// emits — this fleet has several, and a line-wise check refuses every release
/// over them. A whole branch, matched in order, is not something another part
/// of a manifest reproduces by coincidence.
pub fn carried_by(template: &str, rendered: &str, variable: &str) -> Vec<Carried> {
    let (local_form, blocks) = resolve(template, true, variable);
    if blocks.is_empty() {
        return Vec::new();
    }
    let (other_form, _) = resolve(template, false, variable);
    let other: Vec<String> = lines_of(&other_form).into_iter().map(|(_, p)| p).collect();

    // The rendered file as the same kind of list: numbered, blank lines gone,
    // so a blank line inside a branch does not have to be reproduced exactly.
    let actual: Vec<(usize, String)> = rendered
        .lines()
        .enumerate()
        .map(|(index, line)| (index + 1, line.trim().to_string()))
        .filter(|(_, text)| !text.is_empty())
        .collect();

    let local_lines = lines_of(&local_form);
    let mut hits = Vec::new();
    for block in &blocks {
        let wanted: Vec<&String> = local_lines
            .iter()
            .filter(|(line, _)| block.contains(line))
            .map(|(_, pattern)| pattern)
            .collect();
        if wanted.is_empty() {
            continue;
        }
        // A branch that produces only text the other branch also produces
        // decides nothing, and matching it would refuse a perfectly ordinary
        // tree.
        if wanted.iter().all(|pattern| other.contains(pattern)) {
            continue;
        }
        let Some(at) = position_of(&wanted, &actual) else {
            continue;
        };
        // Report the first line the OTHER branch could not have produced.
        // A block's range can begin on the line before the conditional —
        // `{%- if %}` eats the newline that separates them, so the branch text
        // lands on the end of `[dependencies.capdag]` — and naming that line
        // would point at a table header instead of at the dependency.
        let offset = wanted
            .iter()
            .position(|pattern| !other.contains(*pattern))
            .unwrap_or(0);
        hits.push(Carried {
            line: actual[at + offset].0,
            text: actual[at + offset].1.clone(),
            block: actual[at..at + wanted.len()]
                .iter()
                .map(|(_, text)| text.clone())
                .collect(),
        });
    }
    hits.sort_by_key(|hit| hit.line);
    hits
}

/// One local branch, as it actually landed in the rendered file.
///
/// The whole branch and not only the line worth naming, because the line worth
/// NAMING and the line that carries the dependency are routinely different:
/// the first line the other branch could not have produced is often the
/// comment the branch opens with, and a comment points at nothing. Deciding
/// whether the render can be copied means reading every line the branch
/// produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Carried {
    /// 1-based line in the rendered file, the first the other branch could not
    /// have produced.
    pub line: usize,
    /// That line, trimmed.
    pub text: String,
    /// Every line the branch produced, trimmed, in order.
    pub block: Vec<String>,
}

/// Where a branch's lines appear, in order and with nothing between them.
fn position_of(wanted: &[&String], actual: &[(usize, String)]) -> Option<usize> {
    if wanted.len() > actual.len() {
        return None;
    }
    (0..=actual.len() - wanted.len()).find(|&start| {
        wanted
            .iter()
            .enumerate()
            .all(|(offset, pattern)| matches(pattern, &actual[start + offset].1))
    })
}

/// Every non-blank line of a resolved form, as (1-based line number, pattern).
fn lines_of(resolved: &str) -> Vec<(usize, String)> {
    resolved
        .lines()
        .enumerate()
        .filter_map(|(index, line)| {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some((index + 1, blank_expressions(trimmed)))
            }
        })
        .collect()
}

/// The template with every local-variable conditional resolved one way, and
/// the lines of the result each conditional contributed.
///
/// Only that conditional is resolved. Other Tera constructs are left as they
/// stand: they render the same whichever branch is taken, so they cancel out
/// when the two forms are compared, and interpreting them here would be a
/// second template engine that could disagree with the real one.
///
/// The line ranges are why this returns more than a string. A branch can be a
/// FRAGMENT of a line — npm's whole conditional is inside one — so the text
/// that has to be recognised is the line the branch landed in, not the branch.
fn resolve(
    template: &str,
    take_local: bool,
    variable: &str,
) -> (String, Vec<std::ops::RangeInclusive<usize>>) {
    let mut out = String::with_capacity(template.len());
    let mut blocks = Vec::new();
    let mut rest = template;
    loop {
        let Some((before, opening, after)) = next_tag(rest, &format!("if env.{variable}")) else {
            out.push_str(rest);
            return (out, blocks);
        };
        out.push_str(before);
        // Whitespace control on the opening tag eats what precedes it, exactly
        // as Tera does; without this a `{%- if %}` would leave behind the blank
        // line the branch replaces.
        if opening.starts_with("{%-") {
            while out.ends_with(' ') || out.ends_with('\t') {
                out.pop();
            }
            if out.ends_with('\n') {
                out.pop();
            }
        }
        let Some((branch, tail)) = branch_and_tail(after) else {
            // An unterminated conditional. Nothing is guessed: the rest is
            // copied through, and the template will fail to render for real
            // long before anything is released.
            out.push_str(after);
            return (out, blocks);
        };
        let taken = if take_local { branch.local } else { branch.other };
        let first = line_at(&out, out.len());
        out.push_str(taken);
        let last = line_at(&out, out.len());
        if !taken.trim().is_empty() {
            blocks.push(first..=last);
        }
        rest = tail;
    }
}

/// The 1-based line `offset` falls on.
fn line_at(text: &str, offset: usize) -> usize {
    text[..offset].matches('\n').count() + 1
}

/// The two branches of one conditional.
struct Branches<'a> {
    local: &'a str,
    other: &'a str,
}

/// Split the text after an opening tag into its branches and the remainder.
fn branch_and_tail(after: &str) -> Option<(Branches<'_>, &str)> {
    let (before_end, end_tag, tail) = next_tag(after, "endif")?;
    // Whitespace control on `endif` eats what precedes it — the end of
    // whichever branch is last.
    let mut body = before_end;
    if end_tag.starts_with("{%-") {
        body = body.trim_end_matches([' ', '\t']);
        body = body.strip_suffix('\n').unwrap_or(body);
    }
    match next_tag(body, "else") {
        Some((local, else_tag, other)) => {
            let mut local = local;
            if else_tag.starts_with("{%-") {
                local = local.trim_end_matches([' ', '\t']);
                local = local.strip_suffix('\n').unwrap_or(local);
            }
            Some((Branches { local, other }, tail))
        }
        // No else. The conditional adds text or adds nothing, which is the
        // shape a go.mod's `replace` line takes.
        None => Some((Branches { local: body, other: "" }, tail)),
    }
}

/// The next `{% … %}` tag whose body starts with `keyword`, as (before, tag,
/// after).
///
/// Written by hand rather than with a regex because the whitespace-control
/// marker has to survive into the caller: `{%-` and `{%` produce different
/// text, and a matcher that normalised them would build patterns no rendered
/// file contains.
fn next_tag<'a>(text: &'a str, keyword: &str) -> Option<(&'a str, &'a str, &'a str)> {
    let mut search = 0usize;
    while let Some(offset) = text[search..].find("{%") {
        let start = search + offset;
        let length = text[start..].find("%}")?;
        let end = start + length + 2;
        let tag = &text[start..end];
        let body = tag
            .trim_start_matches("{%-")
            .trim_start_matches("{%")
            .trim_end_matches("-%}")
            .trim_end_matches("%}")
            .trim();
        if body.starts_with(keyword) {
            return Some((&text[..start], tag, &text[end..]));
        }
        search = end;
    }
    None
}

/// Every `{{ … }}` replaced by the wildcard.
fn blank_expressions(line: &str) -> String {
    let mut out = String::with_capacity(line.len());
    let mut rest = line;
    while let Some(start) = rest.find("{{") {
        out.push_str(&rest[..start]);
        let Some(length) = rest[start..].find("}}") else {
            out.push_str(&rest[start..]);
            return out;
        };
        out.push(HOLE);
        rest = &rest[start + length + 2..];
    }
    out.push_str(rest);
    out
}

/// Whether a rendered line is one this pattern could have produced.
///
/// Anchored at both ends: the literal parts must appear in order, the first at
/// the start and the last at the end. A wildcard stands for one `{{ … }}`, and
/// an expression that rendered to nothing at all is not a case worth admitting
/// — a version or a path is never empty, and allowing it would let a bare
/// wildcard match every line in the file.
fn matches(pattern: &str, line: &str) -> bool {
    let mut parts = pattern.split(HOLE);
    let Some(first) = parts.next() else {
        return false;
    };
    let Some(mut rest) = line.strip_prefix(first) else {
        return false;
    };
    let tail: Vec<&str> = parts.collect();
    if tail.is_empty() {
        return rest.is_empty();
    }
    for (index, part) in tail.iter().enumerate() {
        let last = index + 1 == tail.len();
        if last {
            if part.is_empty() {
                // A trailing wildcard: whatever it stood for must have been
                // something.
                return !rest.is_empty();
            }
            let Some(at) = rest.rfind(part) else {
                return false;
            };
            // The wildcard before it stood for at least one character, and
            // nothing may follow the final literal.
            return at > 0 && at + part.len() == rest.len();
        }
        let Some(at) = rest.find(part) else {
            return false;
        };
        if at == 0 {
            // Two literals with nothing between them: the expression they
            // surround rendered to nothing.
            return false;
        }
        rest = &rest[at + part.len()..];
    }
    false
}

#[cfg(test)]
#[path = "local_render_tests.rs"]
mod tests;