tw-cli 0.1.0

One command for a Markdoc corpus
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! The corpus root's `.env`: a writer's personal credentials.
//!
//! One convention, read the same way by `tw`, `writer-setup.sh`,
//! `writer-setup.ps1`, the corpus's npm scripts (`.tooling/scripts/lib`),
//! `tw-xlate` and `tw-assets`:
//!
//! * `<corpus root>/.env`, the corpus root being the nearest directory at or
//!   above where tw runs that has `.tooling/` -- the root
//!   `tools::corpus_root` finds, which is also the `TW_ROOT` an extension is
//!   given. Outside a corpus -- no `.tooling/` above -- no `.env` is read at
//!   all, whatever the working directory holds.
//! * UTF-8. A leading byte-order mark (U+FEFF) is dropped. A file with a
//!   UTF-16 byte-order mark, any NUL byte or any byte that is not UTF-8 is
//!   refused whole ("save it as UTF-8"), never patched, and so is a
//!   directory named `.env`.
//! * `KEY=VALUE` lines, `#` comments, an optional `export ` and optional
//!   single or double quotes. A double-quoted value takes `\n`, `\r`, `\t`
//!   and `\<char>` escapes; a single-quoted one is literal; an unquoted one
//!   ends at a `#` that follows a space or tab, and is trimmed of white
//!   space, U+00A0 included. A key is `[A-Za-z_][A-Za-z0-9_.]*`; a line that
//!   is not an assignment is skipped. The last assignment of a key wins, as
//!   when the file is sourced.
//! * A real environment variable that is set and not empty wins over the
//!   file, so CI sets the same names and never has a `.env`.
//! * The file is used only when git ignores it (`git check-ignore`). One git
//!   does not ignore -- tracked, or not listed in `.gitignore`, or outside a
//!   work tree git can answer for -- is refused, with what to do about it,
//!   because a token in a commit is a token on the forge. A `.env` that is
//!   a symbolic link is judged by its target too: a target inside the same
//!   git work tree (`git rev-parse --show-toplevel`, which may reach above
//!   the corpus root) must be ignored and untracked as well; a target
//!   outside it is accepted; a link to nothing is refused.
//! * A `.env` with more than one name on disk -- a hard link, or a link to a
//!   file that has one -- is refused before it is read: git ignores this
//!   name, but could commit another of them with the tokens in it.
//! * A value is never printed: messages name the variable and the file.
//!
//! tw reads it for its own downloads and hands its values to every program
//! it runs -- an extension, the site generator, the language server -- for
//! the names the real environment does not already set.
//!
//! ## Telling the file from the environment (the extension protocol)
//!
//! A child sees the `.env`'s values as ordinary environment variables, so
//! tw says which ones they are:
//!
//! * `TW_DOTENV` -- the absolute path of the `.env` tw read, `$TW_ROOT/.env`
//!   (a link named as the link). Set only when it read one; an extension
//!   that reads or writes the file uses this one.
//! * `TW_DOTENV_KEYS` -- the names tw set from that file, comma-separated
//!   (empty when the real environment set every one of them).
//!
//! Both describe what this tw read and nothing else: when it read no `.env`
//! they are removed from the child's environment, so a pair tw inherited --
//! exported in a shell, or left by an outer tool -- never reaches it.
//!
//! A name in `TW_DOTENV_KEYS` came from the writer's file; any other set
//! name came from the real environment. An extension that keeps state in
//! the file (a sign-in it renews and writes back) treats the first kind as
//! the file's and may rewrite it there, and never rewrites the second kind,
//! which CI or a script set. Run directly, without tw, neither variable is
//! set and the extension reads `.env` itself by this same convention.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;

/// The file, at the corpus root.
pub const FILENAME: &str = ".env";

/// The path of the `.env` tw read, for the programs it runs.
pub const DOTENV_VAR: &str = "TW_DOTENV";

/// The names tw set from that file, comma-separated.
pub const KEYS_VAR: &str = "TW_DOTENV_KEYS";

#[derive(Debug, Default)]
pub struct DotEnv {
    /// Where it was read from.
    path: PathBuf,
    /// In file order; a later assignment of a key overrides an earlier one.
    entries: Vec<(String, String)>,
}

impl DotEnv {
    /// `root/.env` if there is one and git ignores it; `None` if there is
    /// none; an error, saying what to do, if git does not ignore it, it has
    /// more than one name on disk, or it is not UTF-8 text.
    pub fn load(root: &Path) -> Result<Option<DotEnv>, String> {
        let path = root.join(FILENAME);
        match std::fs::metadata(&path) {
            Ok(m) if m.is_dir() => {
                return Err(format!(
                    "{} is a directory. tw reads a writer's tokens from a file of that \
                     name at the corpus root; rename the directory (a Python virtual \
                     environment, say, to .venv).",
                    path.display()
                ));
            }
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                if std::fs::symlink_metadata(&path).is_ok() {
                    return Err(format!(
                        "{} is a link to a file that is not there. Create that file or \
                         remove the link.",
                        path.display()
                    ));
                }
                return Ok(None);
            }
            Err(e) => return Err(format!("{}: {e}", path.display())),
        }
        ensure_ignored(&path)?;
        ensure_one_name(&path)?;
        let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
        let text = decode(&bytes, &path)?;
        let mut env = DotEnv::parse(&text);
        env.path = path;
        Ok(Some(env))
    }

    pub fn parse(text: &str) -> DotEnv {
        DotEnv {
            path: PathBuf::from(FILENAME),
            entries: text.lines().filter_map(parse_line).collect(),
        }
    }

    /// The file's own value for `key`; the last assignment wins.
    pub fn file_value(&self, key: &str) -> Option<&str> {
        self.entries
            .iter()
            .rev()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v.as_str())
    }

    /// What a child is given: each key once, with its last value, unless the
    /// real environment sets it to something not empty.
    pub fn for_children(&self) -> Vec<(String, String)> {
        let mut out: Vec<(String, String)> = Vec::new();
        for (key, _) in &self.entries {
            if out.iter().any(|(k, _)| k == key) || self.in_environment(key) {
                continue;
            }
            if let Some(value) = self.file_value(key) {
                out.push((key.clone(), value.to_string()));
            }
        }
        out
    }

    /// Set and not empty in the real environment -- not handed down from
    /// this same file by a tw that runs this one (`TW_DOTENV_KEYS`).
    pub fn in_environment(&self, key: &str) -> bool {
        in_environment(key) && !from_this_file(&self.path, key)
    }
}

/// The file's text: UTF-8 with any leading byte-order mark dropped. UTF-16
/// -- what Windows PowerShell 5.1's `>` and `Out-File` write -- NUL bytes,
/// and bytes that are not UTF-8 -- what its `Set-Content` writes, in the
/// ANSI code page -- are refused rather than half read: a token with a byte
/// replaced is a token that fails somewhere else, for no reason given.
pub fn decode(bytes: &[u8], path: &Path) -> Result<String, String> {
    let utf16 = bytes.starts_with(b"\xFF\xFE") || bytes.starts_with(b"\xFE\xFF");
    let text = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
    let what = if utf16 {
        "saved as UTF-16".to_string()
    } else if bytes.contains(&0) {
        "not plain text (it holds NUL bytes)".to_string()
    } else {
        match std::str::from_utf8(text) {
            Ok(text) => return Ok(text.to_string()),
            Err(e) => format!(
                "not UTF-8 text (byte {} is not UTF-8; Windows PowerShell 5.1's \
                 Set-Content writes the ANSI code page)",
                bytes.len() - text.len() + e.valid_up_to() + 1
            ),
        }
    };
    Err(format!(
        "{} is {what}, and tw reads UTF-8 only. Open it in an editor and save it as \
         UTF-8 (in VS Code: \"Save with Encoding\", UTF-8; in PowerShell 7: \
         Set-Content -Encoding utf8).",
        path.display(),
    ))
}

/// Set and not empty in the environment this process was given.
pub fn in_environment(key: &str) -> bool {
    std::env::var_os(key).is_some_and(|v| !v.is_empty())
}

/// Whether a tw that runs this one set `key` from the file at `path`.
fn from_this_file(path: &Path, key: &str) -> bool {
    let (Some(file), Ok(keys)) = (std::env::var_os(DOTENV_VAR), std::env::var(KEYS_VAR)) else {
        return false;
    };
    let same = Path::new(&file) == path
        || matches!(
            (Path::new(&file).canonicalize(), path.canonicalize()),
            (Ok(a), Ok(b)) if a == b
        );
    same && keys.split(',').any(|k| k == key)
}

static LOADED: OnceLock<Option<DotEnv>> = OnceLock::new();

/// Load the `.env` for this run (`for_run`). Called once, before anything
/// reads a variable or starts a program, with the directory the command
/// works on; a second call is a no-op.
pub fn init(start: &Path) -> Result<(), String> {
    if LOADED.get().is_some() {
        return Ok(());
    }
    let loaded = for_run(start)?;
    let _ = LOADED.set(loaded);
    Ok(())
}

/// The `.env` a run that works on `start` reads: the corpus root's, at the
/// root `tools::corpus` finds (the one `TW_ROOT` names), and only when that
/// root has `.tooling/`. Outside a corpus there is none -- the working
/// directory's belongs to some other project. A `TW_DOTENV` in tw's own
/// environment never names it either: tw reads the file at its corpus root
/// or nothing (an inherited `TW_DOTENV_KEYS` only tells it which set names a
/// tw that runs this one took from that same file, `from_this_file`).
pub fn for_run(start: &Path) -> Result<Option<DotEnv>, String> {
    let root = crate::tools::corpus(start);
    if !root.join(crate::tools::TOOLING_DIR).is_dir() {
        return Ok(None);
    }
    DotEnv::load(&root)
}

/// The real environment's value if it is set and not empty, else the
/// `.env`'s, if one was loaded.
pub fn var(key: &str) -> Option<String> {
    let loaded = LOADED.get().and_then(Option::as_ref);
    let real = match loaded {
        Some(env) => env.in_environment(key),
        None => in_environment(key),
    };
    if real {
        return std::env::var(key).ok();
    }
    loaded
        .and_then(|env| env.file_value(key))
        .map(str::to_string)
        .or_else(|| std::env::var(key).ok().filter(|v| !v.is_empty()))
}

/// Give `command` the `.env`'s values the real environment does not set,
/// and say which they are (`TW_DOTENV`, `TW_DOTENV_KEYS`).
pub fn apply(command: &mut Command) {
    hand_down(command, LOADED.get().and_then(Option::as_ref));
}

/// `apply` with the `.env` tw loaded for this run, or `None` when it loaded
/// none (outside a corpus, or a corpus with no `.env`).
///
/// `TW_DOTENV` and `TW_DOTENV_KEYS` describe what this tw read and nothing
/// else. An extension takes `TW_DOTENV` as the `.env` to read and write, so
/// one this process inherited -- exported in a shell, or left by an outer
/// tool -- would hand it another corpus's file, or a file tw never judged,
/// when this run read none. So they are removed then, not passed on.
fn hand_down(command: &mut Command, loaded: Option<&DotEnv>) {
    match loaded {
        Some(env) => {
            let children = env.for_children();
            let keys: Vec<&str> = children.iter().map(|(k, _)| k.as_str()).collect();
            let keys = keys.join(",");
            command.envs(children);
            command.env(DOTENV_VAR, env.handed_path());
            command.env(KEYS_VAR, keys);
        }
        None => {
            command.env_remove(DOTENV_VAR);
            command.env_remove(KEYS_VAR);
        }
    }
}

impl DotEnv {
    /// What `TW_DOTENV` says: the absolute path of the `.env` at the corpus
    /// root -- the link itself when it is one, not the file it points to.
    /// An extension that writes the file back judges it by the same rules
    /// (git ignores the link; a target in the work tree is ignored and
    /// untracked), and a target outside any work tree is only acceptable
    /// as the target of an ignored link.
    pub fn handed_path(&self) -> PathBuf {
        std::path::absolute(&self.path).unwrap_or_else(|_| self.path.clone())
    }
}

/// `KEY=VALUE` (with an optional `export `), or `None` for a comment, a blank
/// line or anything that is not an assignment. The same reading as
/// tw-assets' `dotenv::parse_line`, which keeps its sign-in in this file.
pub fn parse_line(line: &str) -> Option<(String, String)> {
    let t = line.trim_start();
    if t.is_empty() || t.starts_with('#') {
        return None;
    }
    let t = t.strip_prefix("export ").map(str::trim_start).unwrap_or(t);
    let (key, value) = t.split_once('=')?;
    let key = key.trim();
    let mut chars = key.chars();
    let first_ok = chars
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
    if !first_ok || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') {
        return None;
    }
    let v = value.trim_start();
    let value = if let Some(rest) = v.strip_prefix('"') {
        let mut s = String::new();
        let mut it = rest.chars();
        while let Some(c) = it.next() {
            match c {
                '"' => break,
                '\\' => match it.next() {
                    Some('n') => s.push('\n'),
                    Some('r') => s.push('\r'),
                    Some('t') => s.push('\t'),
                    Some(other) => s.push(other),
                    None => break,
                },
                c => s.push(c),
            }
        }
        s
    } else if let Some(rest) = v.strip_prefix('\'') {
        rest.split('\'').next().unwrap_or_default().to_string()
    } else {
        // An unquoted value ends at a ` #` comment.
        let cut = v
            .char_indices()
            .find(|&(i, c)| c == '#' && i > 0 && v[..i].ends_with([' ', '\t']))
            .map_or(v.len(), |(i, _)| i);
        v[..cut].trim_end().to_string()
    };
    Some((key.to_string(), value))
}

/// Refuse unless git ignores `file` -- asked in the directory that holds it
/// -- and, when `file` is a symbolic link, the file it points to as well, if
/// that lies in the same git work tree (`git rev-parse --show-toplevel`,
/// asked in that directory): the tokens are in the target, and a target git
/// would commit is a token on the forge however well the link is ignored.
///
/// The boundary is the work tree, not the corpus root: a corpus may be a
/// subdirectory of its repository, and a target elsewhere in that
/// repository is as committable as one inside the corpus. A target outside
/// the work tree is accepted -- this repository cannot commit it -- and a
/// link to nothing is refused.
pub fn ensure_ignored(file: &Path) -> Result<(), String> {
    let dir = holder(file);
    let name = file.file_name().map_or_else(
        || FILENAME.to_string(),
        |n| n.to_string_lossy().into_owned(),
    );
    ensure_name_ignored(&dir, &name, file)?;
    let linked = std::fs::symlink_metadata(file).is_ok_and(|m| m.file_type().is_symlink());
    if !linked {
        return Ok(());
    }
    let target = std::fs::canonicalize(file).map_err(|e| {
        format!(
            "{} is a link to a file that cannot be opened ({e}). Create that file or \
             remove the link.",
            file.display()
        )
    })?;
    let top = work_tree(&dir, file)?;
    match target.strip_prefix(&top) {
        Ok(inside) => {
            let name = inside.to_string_lossy().replace('\\', "/");
            ensure_name_ignored(&top, &name, &target)
                .map_err(|e| format!("{} is a link to {}: {e}", file.display(), target.display()))
        }
        // Outside the work tree this repository cannot commit it.
        Err(_) => Ok(()),
    }
}

/// Refuse a `.env` with more than one name on disk: a hard link, or a
/// symbolic link to a file that is one. `ensure_ignored` judges one name;
/// git could commit another, untracked and not ignored, with the tokens in
/// it, and nothing here can find where that name is.
pub fn ensure_one_name(file: &Path) -> Result<(), String> {
    let names = names_on_disk(file).map_err(|e| format!("{}: {e}", file.display()))?;
    if names <= 1 {
        return Ok(());
    }
    let linked = std::fs::symlink_metadata(file).is_ok_and(|m| m.file_type().is_symlink());
    if !linked {
        return Err(hard_linked(file, names));
    }
    let target = std::fs::canonicalize(file).map_err(|e| format!("{}: {e}", file.display()))?;
    Err(format!(
        "{} is a link to {}: {}",
        file.display(),
        target.display(),
        hard_linked(&target, names)
    ))
}

/// What a file with `names` names on disk is told, in the words every
/// reader of `.env` uses. Never a value.
fn hard_linked(file: &Path, names: u64) -> String {
    format!(
        "{} has {names} names on disk (it is hard-linked), and git could commit another \
         of them with the tokens in it, so it is not read. Copy it to a new file and \
         replace it with the copy, which has one name.",
        file.display()
    )
}

/// How many names the file at `path` has on disk, a symbolic link followed.
#[cfg(unix)]
fn names_on_disk(path: &Path) -> std::io::Result<u64> {
    use std::os::unix::fs::MetadataExt;
    Ok(std::fs::metadata(path)?.nlink())
}

/// On Windows std has the count only behind an unstable feature
/// (`MetadataExt::number_of_links`, `windows_by_handle`), so this asks
/// GetFileInformationByHandle through winapi-util, which the tree already
/// has (walkdir). Opening the file follows a symbolic link.
#[cfg(windows)]
fn names_on_disk(path: &Path) -> std::io::Result<u64> {
    let file = std::fs::File::open(path)?;
    Ok(winapi_util::file::information(&file)?.number_of_links())
}

/// Elsewhere there is no count to ask for, and no `.env` reader ships.
#[cfg(not(any(unix, windows)))]
fn names_on_disk(_: &Path) -> std::io::Result<u64> {
    Ok(1)
}

/// The directory that holds `file`.
fn holder(file: &Path) -> PathBuf {
    match file.parent() {
        Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
        _ => PathBuf::from("."),
    }
}

/// The top of the git work tree `dir` lies in, canonical, so a canonical
/// link target can be compared with it.
fn work_tree(dir: &Path, file: &Path) -> Result<PathBuf, String> {
    let out = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .map_err(|e| {
            format!(
                "could not run git to find the work tree of {} ({e})",
                file.display()
            )
        })?;
    if !out.status.success() {
        return Err(format!(
            "could not ask git which work tree holds {}: {}. tw reads tokens from \
             that file only inside a git work tree that ignores it.",
            file.display(),
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    let top = path_of(&out.stdout);
    top.canonicalize()
        .map_err(|e| format!("{}: {e}", top.display()))
}

/// A path git printed on a line of its own.
fn path_of(stdout: &[u8]) -> PathBuf {
    let line = stdout.strip_suffix(b"\n").unwrap_or(stdout);
    let line = line.strip_suffix(b"\r").unwrap_or(line);
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        PathBuf::from(std::ffi::OsStr::from_bytes(line))
    }
    #[cfg(not(unix))]
    {
        PathBuf::from(String::from_utf8_lossy(line).into_owned())
    }
}

/// Refuse unless git ignores `name` (relative to `root`), shown as `file`.
fn ensure_name_ignored(root: &Path, name: &str, file: &Path) -> Result<(), String> {
    let shown = file.display();
    let check = Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["check-ignore", "-q", "--", name])
        .output()
        .map_err(|e| {
            format!(
                "could not run git to check that {shown} is ignored ({e}). tw reads \
                 tokens from that file only when git ignores it; until then, set \
                 them in the environment instead."
            )
        })?;
    match check.status.code() {
        Some(0) => Ok(()),
        Some(1) => {
            let tracked = Command::new("git")
                .arg("-C")
                .arg(root)
                .args(["ls-files", "--error-unmatch", "--", name])
                .output()
                .is_ok_and(|o| o.status.success());
            if tracked {
                Err(format!(
                    "git tracks {shown}, so the tokens in it are committed or about to \
                     be. tw will not read it. Run `git rm --cached {name}`, make sure \
                     .gitignore has a line `{name}`, and if that file ever held a \
                     secret in a commit, treat the secret as leaked."
                ))
            } else {
                Err(format!(
                    "git does not ignore {shown}, so the tokens in it could be \
                     committed. tw will not read it. Add a line `{name}` to {}, \
                     then run this again.",
                    root.join(".gitignore").display()
                ))
            }
        }
        _ => Err(format!(
            "could not ask git whether {shown} is ignored: {}. tw reads tokens from \
             that file only inside a git work tree that ignores it; outside one, set \
             them in the environment instead.",
            String::from_utf8_lossy(&check.stderr).trim()
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn the_shared_syntax_is_read() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let p = |l: &str| parse_line(l).map(|(k, v)| format!("{k}={v}"));
        assert_eq!(p("A=1"), Some("A=1".into()));
        assert_eq!(p("  export B = two  "), Some("B=two".into()));
        assert_eq!(
            p("C=\"quoted # not a comment\" # a comment"),
            Some("C=quoted # not a comment".into())
        );
        assert_eq!(p("D='single $HOME'"), Some("D=single $HOME".into()));
        assert_eq!(p("E=bare # comment"), Some("E=bare".into()));
        assert_eq!(p("F=a#b"), Some("F=a#b".into()));
        assert_eq!(
            p("G=\"line\\nbreak \\\"q\\\"\""),
            Some("G=line\nbreak \"q\"".into())
        );
        assert_eq!(p("H="), Some("H=".into()));
        assert_eq!(p("# X=1"), None);
        assert_eq!(p(""), None);
        assert_eq!(p("not an assignment"), None);
        assert_eq!(p("1BAD=x"), None);
        // A file saved on Windows: `lines()` leaves no \r on a line.
        let env = DotEnv::parse("K=v\r\nQ=\"x\"\r\n");
        assert_eq!(env.file_value("K"), Some("v"));
        assert_eq!(env.file_value("Q"), Some("x"));
    }

    #[test]
    fn the_last_assignment_wins_and_children_get_each_key_once() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let env =
            DotEnv::parse("TW_DOTENV_TEST_K=first\nTW_DOTENV_TEST_K=second\nTW_DOTENV_TEST_J=j\n");
        assert_eq!(env.file_value("TW_DOTENV_TEST_K"), Some("second"));
        assert_eq!(
            env.for_children(),
            [
                ("TW_DOTENV_TEST_K".to_string(), "second".to_string()),
                ("TW_DOTENV_TEST_J".to_string(), "j".to_string())
            ]
        );
    }

    #[test]
    fn the_real_environment_wins() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        // PATH is set in any environment a test runs in.
        let env = DotEnv::parse("PATH=/from/dotenv\nTW_DOTENV_UNSET_X=1\n");
        let children = env.for_children();
        assert!(!children.iter().any(|(k, _)| k == "PATH"), "{children:?}");
        assert!(children.iter().any(|(k, _)| k == "TW_DOTENV_UNSET_X"));
    }

    /// git as a test runs it: no system or global configuration.
    fn git(dir: &Path, args: &[&str]) {
        let ok = Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_CONFIG_GLOBAL", dir.join(".git").join("no-config"))
            .output()
            .expect("git runs")
            .status
            .success();
        assert!(ok, "git {args:?}");
    }

    /// A new work tree at `dir` that only its own `.gitignore` files decide
    /// about. A machine whose global excludes -- `core.excludesFile`, or
    /// `$XDG_CONFIG_HOME/git/ignore`, which git reads even with no global
    /// config file -- list `.env` would otherwise ignore every file these
    /// tests need git *not* to ignore. tw's own git calls inherit this
    /// process's environment, so the repository's own `core.excludesFile`
    /// (an empty file) is what overrides them: it wins over the global
    /// setting, and once set, the XDG file is not read.
    fn repo(dir: &Path) {
        git(dir, &["init", "-q"]);
        let git_dir = dir.join(".git");
        std::fs::create_dir_all(git_dir.join("info")).unwrap();
        std::fs::write(git_dir.join("info").join("exclude"), "").unwrap();
        std::fs::write(git_dir.join("no-config"), "").unwrap();
        let none = git_dir.join("no-excludes");
        std::fs::write(&none, "").unwrap();
        git(
            dir,
            &["config", "core.excludesFile", &none.to_string_lossy()],
        );
    }

    fn scratch(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("tw-dotenv-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn a_file_git_does_not_ignore_is_refused_and_its_values_never_shown() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let d = scratch("unignored");
        repo(&d);
        std::fs::write(d.join(".env"), "FORGEJO_TOKEN=s3cret-value\n").unwrap();
        let err = DotEnv::load(&d).unwrap_err();
        assert!(err.contains("Add a line `.env`"), "{err}");
        assert!(!err.contains("s3cret"), "{err}");

        std::fs::write(d.join(".gitignore"), "node_modules/\n.env\n").unwrap();
        let env = DotEnv::load(&d).unwrap().unwrap();
        assert_eq!(env.file_value("FORGEJO_TOKEN"), Some("s3cret-value"));

        // Tracked despite the ignore line: check-ignore says "not ignored".
        git(&d, &["add", "-f", ".env"]);
        let err = DotEnv::load(&d).unwrap_err();
        assert!(err.contains("git rm --cached .env"), "{err}");
        assert!(!err.contains("s3cret"), "{err}");
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn no_file_is_no_env_and_needs_no_git() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let d = scratch("none");
        assert!(DotEnv::load(&d).unwrap().is_none());
        // Outside a work tree, a file that is there is refused.
        std::fs::write(d.join(".env"), "A=1\n").unwrap();
        let err = DotEnv::load(&d).unwrap_err();
        assert!(err.contains("could not ask git"), "{err}");
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn a_byte_order_mark_is_dropped_and_utf16_or_nul_is_refused() {
        let p = Path::new("/c/.env");
        let text = decode(b"\xEF\xBB\xBFFORGEJO_TOKEN=t\r\n", p).unwrap();
        assert_eq!(DotEnv::parse(&text).file_value("FORGEJO_TOKEN"), Some("t"));
        let mut utf16 = vec![0xFF, 0xFE];
        for u in "A=1\r\n".encode_utf16() {
            utf16.extend_from_slice(&u.to_le_bytes());
        }
        let err = decode(&utf16, p).unwrap_err();
        assert!(
            err.contains("UTF-16") && err.contains("save it as UTF-8"),
            "{err}"
        );
        let err = decode(b"A=SEK\0RET\n", p).unwrap_err();
        assert!(
            err.contains("NUL") && err.contains("save it as UTF-8"),
            "{err}"
        );
        assert!(!err.contains("SEK"), "{err}");
    }

    #[test]
    fn a_file_that_is_not_utf8_is_refused_whole_not_patched() {
        let p = Path::new("/c/.env");
        // A Latin-1 e-acute, as Windows PowerShell 5.1's Set-Content writes
        // it: one byte, 0xE9, which is not UTF-8.
        let err = decode(b"A=1\nT=s3cret-\xE9tok\n", p).unwrap_err();
        assert!(
            err.contains("not UTF-8 text")
                && err.contains("byte 14")
                && err.contains("save it as UTF-8"),
            "{err}"
        );
        assert!(
            !err.contains("s3cret") && !err.contains('\u{fffd}'),
            "{err}"
        );
        // After a byte-order mark too; the byte is counted in the file.
        let err = decode(b"\xEF\xBB\xBFT=\xE9\n", p).unwrap_err();
        assert!(err.contains("byte 6"), "{err}");
        // UTF-8 proper, the same letter as two bytes, is read.
        let text = decode("T=s3cret-\u{e9}tok\n".as_bytes(), p).unwrap();
        assert_eq!(
            DotEnv::parse(&text).file_value("T"),
            Some("s3cret-\u{e9}tok")
        );
    }

    #[test]
    fn a_no_break_space_around_a_bare_value_is_trimmed() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let env = DotEnv::parse("T=abc\u{a0}\nU=\u{a0}def \nQ=\"x\u{a0}\"\n");
        assert_eq!(env.file_value("T"), Some("abc"));
        assert_eq!(env.file_value("U"), Some("def"));
        // Quoted: kept exactly.
        assert_eq!(env.file_value("Q"), Some("x\u{a0}"));
    }

    #[test]
    fn a_directory_named_env_is_refused() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let d = scratch("dir");
        repo(&d);
        std::fs::create_dir(d.join(".env")).unwrap();
        let err = DotEnv::load(&d).unwrap_err();
        assert!(err.contains("is a directory"), "{err}");
        let _ = std::fs::remove_dir_all(&d);
    }

    #[cfg(unix)]
    #[test]
    fn a_linked_env_is_judged_by_its_target() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let d = scratch("link");
        repo(&d);
        std::fs::write(d.join(".gitignore"), ".env\n").unwrap();
        std::fs::write(d.join("tokens.txt"), "FORGEJO_TOKEN=s3cret\n").unwrap();
        std::os::unix::fs::symlink("tokens.txt", d.join(".env")).unwrap();
        // The link is ignored; its target, untracked, is not.
        let err = DotEnv::load(&d).unwrap_err();
        assert!(
            err.contains("tokens.txt") && err.contains("Add a line `tokens.txt`"),
            "{err}"
        );
        assert!(!err.contains("s3cret"), "{err}");
        // A tracked target: refused with the git rm advice.
        git(&d, &["add", "tokens.txt"]);
        let err = DotEnv::load(&d).unwrap_err();
        assert!(err.contains("git rm --cached tokens.txt"), "{err}");
        // An ignored, untracked target is read.
        git(&d, &["rm", "-q", "--cached", "tokens.txt"]);
        std::fs::write(d.join(".gitignore"), ".env\ntokens.txt\n").unwrap();
        let env = DotEnv::load(&d).unwrap().unwrap();
        assert_eq!(env.file_value("FORGEJO_TOKEN"), Some("s3cret"));
        // A target outside the work tree is read: this git cannot commit it.
        let outside = scratch("link-outside");
        std::fs::write(outside.join("shared.env"), "A=1\n").unwrap();
        std::fs::remove_file(d.join(".env")).unwrap();
        std::os::unix::fs::symlink(outside.join("shared.env"), d.join(".env")).unwrap();
        let env = DotEnv::load(&d).unwrap().unwrap();
        assert_eq!(env.file_value("A"), Some("1"));
        // TW_DOTENV names the link, which is what an extension must judge
        // and write through -- not the target, which no git ignores.
        assert_eq!(env.handed_path(), d.join(".env"));
        // A link to nothing is said, not taken for "no .env".
        std::fs::remove_file(d.join(".env")).unwrap();
        std::os::unix::fs::symlink(d.join("missing"), d.join(".env")).unwrap();
        assert!(DotEnv::load(&d).unwrap_err().contains("not there"));
        let _ = std::fs::remove_dir_all(&d);
        let _ = std::fs::remove_dir_all(&outside);
    }

    /// A `.env` with a second name on disk -- a hard link -- is refused
    /// before it is read, wherever the other name is and whatever git says
    /// of it: git ignores `.env`, and could commit the other name with the
    /// tokens in it (the corpus check's E26). The count said is the file's
    /// (E48), a link to a file with two names is refused too (E47), and a
    /// copy, which has one name, is read.
    #[test]
    fn a_hard_linked_env_is_refused() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let d = scratch("hardlink");
        repo(&d);
        std::fs::write(d.join(".gitignore"), ".env\nother.env\n").unwrap();
        std::fs::write(d.join("other.env"), "FORGEJO_TOKEN=s3cret\n").unwrap();
        std::fs::hard_link(d.join("other.env"), d.join(".env")).unwrap();
        let err = DotEnv::load(&d).unwrap_err();
        assert!(
            err.contains("has 2 names on disk")
                && err.contains("git could commit another of them with the tokens in it")
                && err.contains("replace it with the copy"),
            "{err}"
        );
        assert!(!err.contains("s3cret"), "{err}");
        let outside = scratch("hardlink-outside");
        std::fs::hard_link(d.join(".env"), outside.join("again")).unwrap();
        let err = DotEnv::load(&d).unwrap_err();
        assert!(err.contains("has 3 names on disk"), "{err}");
        #[cfg(unix)]
        {
            std::fs::remove_file(d.join(".env")).unwrap();
            std::os::unix::fs::symlink(outside.join("again"), d.join(".env")).unwrap();
            let err = DotEnv::load(&d).unwrap_err();
            assert!(
                err.contains("is a link to") && err.contains("has 2 names on disk"),
                "{err}"
            );
            assert!(!err.contains("s3cret"), "{err}");
        }
        std::fs::remove_file(d.join(".env")).unwrap();
        std::fs::copy(d.join("other.env"), d.join(".env")).unwrap();
        let env = DotEnv::load(&d).unwrap().unwrap();
        assert_eq!(env.file_value("FORGEJO_TOKEN"), Some("s3cret"));
        let _ = std::fs::remove_dir_all(&d);
        let _ = std::fs::remove_dir_all(&outside);
    }

    /// The corpus is a subdirectory of its repository, and `.env` links to
    /// a file elsewhere in the same work tree: that file is judged by git
    /// as one inside the corpus would be.
    #[cfg(unix)]
    #[test]
    fn a_link_to_the_rest_of_the_work_tree_is_judged_there() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let d = scratch("subcorpus");
        repo(&d);
        let corpus = d.join("docs");
        std::fs::create_dir_all(corpus.join(".tooling")).unwrap();
        std::fs::write(corpus.join(".gitignore"), ".env\n").unwrap();
        std::fs::write(d.join("shared.env"), "FORGEJO_TOKEN=s3cret\n").unwrap();
        std::os::unix::fs::symlink("../shared.env", corpus.join(".env")).unwrap();
        // Untracked and not ignored (the check's M17).
        let err = DotEnv::load(&corpus).unwrap_err();
        assert!(
            err.contains("shared.env") && err.contains("Add a line `shared.env`"),
            "{err}"
        );
        assert!(!err.contains("s3cret"), "{err}");
        // Tracked (M16).
        git(&d, &["add", "-f", "shared.env"]);
        let err = DotEnv::load(&corpus).unwrap_err();
        assert!(err.contains("git rm --cached shared.env"), "{err}");
        assert!(!err.contains("s3cret"), "{err}");
        // Ignored and untracked: read.
        git(&d, &["rm", "-q", "--cached", "shared.env"]);
        std::fs::write(d.join(".gitignore"), "shared.env\n").unwrap();
        let env = DotEnv::load(&corpus).unwrap().unwrap();
        assert_eq!(env.file_value("FORGEJO_TOKEN"), Some("s3cret"));
        let _ = std::fs::remove_dir_all(&d);
    }

    /// A corpus at a new directory: `.tooling/`, a work tree, and a
    /// `.gitignore` that lists `.env`.
    fn corpus(name: &str) -> PathBuf {
        let d = scratch(name);
        repo(&d);
        std::fs::create_dir_all(d.join(".tooling")).unwrap();
        std::fs::write(d.join(".gitignore"), ".env\n").unwrap();
        d
    }

    /// Runs `body` while this process has `TW_DOTENV` and `TW_DOTENV_KEYS`
    /// naming `inherited` -- what a shell that exported them, or an outer
    /// tool, leaves tw -- and puts back what was there. The caller holds
    /// PATH_LOCK: every test that reads these variables (`for_children`)
    /// does too.
    fn inheriting<T>(inherited: &Path, body: impl FnOnce() -> T) -> T {
        let saved = [DOTENV_VAR, KEYS_VAR].map(std::env::var_os);
        // SAFETY: under PATH_LOCK, as the PATH test in extension.rs, and
        // restored below before any assertion is made.
        unsafe {
            std::env::set_var(DOTENV_VAR, inherited);
            std::env::set_var(KEYS_VAR, "TW_DOTENV_TEST_TOKEN");
        }
        let out = body();
        for (name, value) in [DOTENV_VAR, KEYS_VAR].into_iter().zip(saved) {
            // SAFETY: as above.
            unsafe {
                match value {
                    Some(v) => std::env::set_var(name, v),
                    None => std::env::remove_var(name),
                }
            }
        }
        out
    }

    /// What `hand_down` does to a child's `TW_DOTENV` and `TW_DOTENV_KEYS`:
    /// `Some(Some(v))` sets it to v, `Some(None)` removes it, and `None`
    /// leaves it alone -- so the child inherits whatever tw had.
    type Handed = (Option<Option<String>>, Option<Option<String>>);

    fn handed(command: &Command) -> Handed {
        let get = |name: &str| {
            command
                .get_envs()
                .find(|(k, _)| *k == std::ffi::OsStr::new(name))
                .map(|(_, v)| v.map(|v| v.to_string_lossy().into_owned()))
        };
        (get(DOTENV_VAR), get(KEYS_VAR))
    }

    /// The `.env` `load` reads with another corpus's `.env` inherited in
    /// `TW_DOTENV`, what `hand_down` then does to a child, and (on Unix,
    /// where there is a `sh` to ask) what that child sees:
    /// `<TW_DOTENV>|<TW_DOTENV_KEYS>`, `unset` for one it does not have.
    fn run_inheriting(
        inherited: &Path,
        load: impl FnOnce() -> Option<DotEnv>,
    ) -> (Option<PathBuf>, Handed, String) {
        inheriting(inherited, || {
            let loaded = load();
            let mut command = Command::new("sh");
            command.args([
                "-c",
                r#"printf '%s|%s' "${TW_DOTENV-unset}" "${TW_DOTENV_KEYS-unset}""#,
            ]);
            hand_down(&mut command, loaded.as_ref());
            let seen = if cfg!(unix) {
                let out = command.output().expect("sh runs");
                String::from_utf8_lossy(&out.stdout).into_owned()
            } else {
                String::new()
            };
            (loaded.map(|e| e.handed_path()), handed(&command), seen)
        })
    }

    /// The check's repro: corpus A has no `.env`, and `TW_DOTENV` names
    /// corpus B's. tw reads nothing, and the extension must not be told
    /// B's file is the `.env` -- it would send B's token to A's server.
    #[test]
    fn an_inherited_tw_dotenv_is_removed_in_a_corpus_with_no_env() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let a = corpus("inherit-a");
        let b = corpus("inherit-b");
        std::fs::write(b.join(".env"), "TW_DOTENV_TEST_TOKEN=b-s3cret\n").unwrap();
        let (read, handed, seen) = run_inheriting(&b.join(".env"), || for_run(&a).unwrap());
        assert_eq!(read, None, "tw takes no .env from TW_DOTENV");
        assert_eq!(handed, (Some(None), Some(None)), "both removed");
        if cfg!(unix) {
            assert_eq!(seen, "unset|unset");
        }
        let _ = std::fs::remove_dir_all(&a);
        let _ = std::fs::remove_dir_all(&b);
    }

    /// Outside a corpus tw reads no `.env` -- not the working directory's,
    /// not the one an inherited `TW_DOTENV` names -- and hands on neither.
    #[test]
    fn an_inherited_tw_dotenv_is_removed_outside_a_corpus() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let outside = scratch("inherit-outside");
        repo(&outside);
        std::fs::write(outside.join(".gitignore"), ".env\n").unwrap();
        std::fs::write(outside.join(".env"), "TW_DOTENV_TEST_TOKEN=o-s3cret\n").unwrap();
        let b = corpus("inherit-outside-b");
        std::fs::write(b.join(".env"), "TW_DOTENV_TEST_TOKEN=b-s3cret\n").unwrap();
        let (read, handed, seen) = run_inheriting(&b.join(".env"), || for_run(&outside).unwrap());
        assert_eq!(read, None, "no .env outside a corpus");
        assert_eq!(handed, (Some(None), Some(None)), "both removed");
        if cfg!(unix) {
            assert_eq!(seen, "unset|unset");
        }
        let _ = std::fs::remove_dir_all(&outside);
        let _ = std::fs::remove_dir_all(&b);
    }

    /// With a `.env` of its own, tw names that one and its keys, whatever
    /// it inherited. Loaded at the root as given (`for_run` would make it
    /// canonical first), as the other tests here that run git do.
    #[test]
    fn with_its_own_env_tw_names_that_one_and_not_the_inherited_one() {
        let _path = crate::PATH_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let a = corpus("own-a");
        std::fs::write(a.join(".env"), "TW_DOTENV_TEST_OWN=a-s3cret\n").unwrap();
        let b = corpus("own-b");
        std::fs::write(b.join(".env"), "TW_DOTENV_TEST_TOKEN=b-s3cret\n").unwrap();
        let (read, handed, seen) = run_inheriting(&b.join(".env"), || DotEnv::load(&a).unwrap());
        let own = a.join(".env").display().to_string();
        assert_eq!(
            read.map(|p| p.display().to_string()).as_deref(),
            Some(own.as_str())
        );
        assert_eq!(
            handed,
            (
                Some(Some(own.clone())),
                Some(Some("TW_DOTENV_TEST_OWN".to_string()))
            )
        );
        if cfg!(unix) {
            assert_eq!(seen, format!("{own}|TW_DOTENV_TEST_OWN"));
        }
        let _ = std::fs::remove_dir_all(&a);
        let _ = std::fs::remove_dir_all(&b);
    }
}