navree-kernel 1.3.0

Navree kernel: module graph, type-keyed DI container, lifecycle and command runner.
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
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
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
//! Publishing the files a plugin ships into the app: the rule every published
//! path follows, the checked writer every publishing command writes through,
//! and the work of the `plugin:publish` built-in.

use std::collections::HashSet;
use std::fmt;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::Path;

use crate::BoxError;
use crate::graph::Graph;
use crate::plugin::{PublishTag, destination};
use crate::plugin_graph::shipped;

/// Whether `path` is a safe relative path inside a publish folder: non-empty,
/// at most 255 bytes, with `/` as the only separator; every segment non-empty,
/// at most 128 bytes and neither `.` nor `..`; no `\`, `:` or control
/// character; none of `<>"|?*`; no segment ending in `.` or a space; no
/// segment whose part before its first `.`, without trailing spaces, is
/// `CON`, `PRN`, `AUX`, `NUL`, `CONIN$`, `CONOUT$`, `COM0` to `COM9`,
/// `LPT0` to `LPT9`, or `COM` or `LPT` followed by `¹`, `²` or `³`, in any
/// case. Not public API; the boot check, `plugin:publish` and Navree's own
/// macros use it.
pub fn is_safe_relative_path(path: &str) -> bool {
    !path.is_empty()
        && path.len() <= 255
        && !path.chars().any(is_refused_char)
        && path.split('/').all(is_safe_segment)
}

/// A character no published path holds: `\`, `:`, `<>"|?*` or a control
/// character.
fn is_refused_char(c: char) -> bool {
    c.is_control() || matches!(c, '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*')
}

/// Whether one segment of a published path is safe (see
/// [`is_safe_relative_path`]).
fn is_safe_segment(segment: &str) -> bool {
    !segment.is_empty()
        && segment.len() <= 128
        && segment != "."
        && segment != ".."
        && !segment.ends_with('.')
        && !segment.ends_with(' ')
        && !is_device_name(segment)
}

/// Whether `segment` names a Windows device: its part before the first `.`,
/// without trailing spaces, is `CON`, `PRN`, `AUX`, `NUL`, `CONIN$`,
/// `CONOUT$`, `COM0` to `COM9`, `LPT0` to `LPT9`, or `COM` or `LPT` followed
/// by a superscript one, two or three (`¹`, `²`, `³`), ignoring ASCII case.
fn is_device_name(segment: &str) -> bool {
    let stem = segment
        .split_once('.')
        .map_or(segment, |(stem, _)| stem)
        .trim_end_matches(' ')
        .to_ascii_uppercase();
    match stem.as_bytes() {
        b"CON" | b"PRN" | b"AUX" | b"NUL" | b"CONIN$" | b"CONOUT$" => true,
        [b'C', b'O', b'M', digit] | [b'L', b'P', b'T', digit] => digit.is_ascii_digit(),
        // `¹` (U+00B9), `²` (U+00B2) and `³` (U+00B3) are `C2 B9`, `C2 B2`
        // and `C2 B3` in UTF-8.
        [b'C', b'O', b'M', 0xC2, last] | [b'L', b'P', b'T', 0xC2, last] => {
            matches!(*last, 0xB9 | 0xB2 | 0xB3)
        }
        _ => false,
    }
}

/// Whether `path`, a file under the `locales` tag, starts with a locale: at
/// least two segments, the first a language of 2 to 8 letters followed by any
/// number of `-` and 1 to 8 letters or digits (`en`, `pa-IN`, `zh-Hant-TW`).
pub(crate) fn is_locale_path(path: &str) -> bool {
    let Some((locale, _)) = path.split_once('/') else {
        return false;
    };
    let mut parts = locale.split('-');
    parts.next().is_some_and(|language| {
        (2..=8).contains(&language.len()) && language.bytes().all(|b| b.is_ascii_alphabetic())
    }) && parts.all(|part| {
        (1..=8).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphanumeric())
    })
}

/// The first of `paths` that equals an earlier one once both are lower-cased,
/// or once both are upper-cased (file systems fold case differently, and
/// `ß` upper-cases to `SS`): on a disk that ignores case, the two are one
/// file. Names that differ only in how an accent is composed are not caught.
pub(crate) fn first_case_collision<'a>(
    paths: impl IntoIterator<Item = &'a str>,
) -> Option<&'a str> {
    let mut lower = HashSet::new();
    let mut upper = HashSet::new();
    paths.into_iter().find(|path| {
        // Both sets take the path, even when the first already had it.
        let seen_lower = !lower.insert(path.to_lowercase());
        let seen_upper = !upper.insert(path.to_uppercase());
        seen_lower || seen_upper
    })
}

/// The first of `paths` that another of them needs as a folder (`admin` and
/// `admin/edit.html`), with that other path. Case is ignored as
/// [`first_case_collision`] ignores it: `Admin` is the folder of
/// `admin/edit.html` on a disk that ignores case.
pub(crate) fn first_file_and_folder<'a>(paths: &[&'a str]) -> Option<(&'a str, &'a str)> {
    let folded: Vec<(String, String)> = paths
        .iter()
        .map(|path| {
            (
                format!("{}/", path.to_lowercase()),
                format!("{}/", path.to_uppercase()),
            )
        })
        .collect();
    paths
        .iter()
        .zip(&folded)
        .find_map(|(&file, (lower, upper))| {
            paths.iter().find_map(|&inside| {
                (inside.to_lowercase().starts_with(lower.as_str())
                    || inside.to_uppercase().starts_with(upper.as_str()))
                .then_some((file, inside))
            })
        })
}

/// What [`publish_files`] did with one file, or with a dry run would do. Not
/// public API; the commands that publish files use it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Published {
    /// The file was written: it was new, or it was replaced with `force`.
    Written,
    /// The file exists and was kept (no `force`).
    Kept,
    /// A dry run: the file is new and would be written.
    WouldBeWritten,
    /// A dry run: the file exists and would be kept (no `force`).
    WouldBeKept,
    /// A dry run: the file exists and would be replaced (`force`).
    WouldBeReplaced,
}

impl Published {
    /// The line a command prints for the file `path`: `<path>: written`,
    /// `<path>: exists, kept (use --force to replace it)`,
    /// `<path>: would be written`,
    /// `<path>: exists, would be kept (use --force to replace it)` or
    /// `<path>: exists, would be replaced`.
    pub fn line(&self, path: &str) -> String {
        let outcome = match self {
            Published::Written => "written",
            Published::Kept => "exists, kept (use --force to replace it)",
            Published::WouldBeWritten => "would be written",
            Published::WouldBeKept => "exists, would be kept (use --force to replace it)",
            Published::WouldBeReplaced => "exists, would be replaced",
        };
        format!("{path}: {outcome}")
    }
}

/// Why [`publish_files`] refused to write, or stopped writing: the text a
/// command prints after its `<command>: ` prefix. Not public API; the
/// commands that publish files use it.
#[derive(Debug)]
pub struct PublishRefused(String);

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

impl std::error::Error for PublishRefused {}

/// Writes `files`, each a path relative to `root` (the app's folder),
/// `/`-separated, and its bytes, and says what happened to each, in path
/// order. Not public API; `plugin:publish` and the commands that publish a
/// plugin's configuration or translations write through it, some without
/// the boot check, so it checks every path itself.
///
/// Nothing is written before every file has passed every check:
///
/// 1. every path is a safe relative path (the rule the boot applies to the
///    files a plugin ships);
/// 2. no two paths are one file on a disk that ignores case (their
///    lower-case forms or their upper-case forms are equal, which also
///    refuses a path given twice), and no path is also the folder of
///    another (`admin` and `admin/edit.html`);
/// 3. every folder below `root` on the way to a file is a folder, not a file
///    and not a symbolic link or a junction, and the file itself is not a
///    link and not a folder. `root` and the folders above it are not
///    checked, so an app inside a linked folder publishes.
///
/// An existing file is kept unless `force` is set. With `dry_run` nothing is
/// written and the result says what would be. A file is written as a new
/// file beside its destination and renamed over it: an existing file is
/// never opened for writing, so a hard link to it elsewhere keeps its
/// content, and a link put in its place after the check is replaced, not
/// followed. Each folder is checked again as it is used, and the new file
/// must still be below `root`, links resolved, just before it is renamed
/// into place. On Windows, a rename that another program (a virus scanner,
/// an indexer) blocks for a moment is tried again for up to a second. An
/// error while writing stops at that file; the files before it are written,
/// and the error says so.
pub fn publish_files(
    root: &Path,
    files: &[(&str, &[u8])],
    force: bool,
    dry_run: bool,
) -> Result<Vec<(String, Published)>, PublishRefused> {
    let mut files = files.to_vec();
    files.sort_by_key(|&(path, _)| path);
    if let Some(&(path, _)) = files
        .iter()
        .find(|&&(path, _)| !is_safe_relative_path(path))
    {
        return Err(PublishRefused(format!(
            "{path} is not a safe relative path; nothing was written"
        )));
    }
    let paths: Vec<&str> = files.iter().map(|&(path, _)| path).collect();
    if let Some(path) = first_case_collision(paths.iter().copied()) {
        return Err(PublishRefused(format!(
            "{path} is the same file as another one on a disk that ignores case; nothing was written"
        )));
    }
    if let Some((file, inside)) = first_file_and_folder(&paths) {
        return Err(PublishRefused(format!(
            "{file} would be both a file and the folder of {inside}; nothing was written"
        )));
    }
    let mut outcomes = Vec::with_capacity(files.len());
    for &(path, _) in &files {
        let published = match (file_exists(root, path)?, force, dry_run) {
            (false, _, false) | (true, true, false) => Published::Written,
            (false, _, true) => Published::WouldBeWritten,
            (true, false, false) => Published::Kept,
            (true, false, true) => Published::WouldBeKept,
            (true, true, true) => Published::WouldBeReplaced,
        };
        outcomes.push((path.to_owned(), published));
    }
    if dry_run {
        return Ok(outcomes);
    }
    let to_write: Vec<(&str, &[u8])> = files
        .iter()
        .zip(&outcomes)
        .filter(|(_, (_, published))| *published == Published::Written)
        .map(|(&file, _)| file)
        .collect();
    let Some(&(first, _)) = to_write.first() else {
        return Ok(outcomes);
    };
    // The app's folder with its links resolved: every new file must still be
    // below it when it is renamed into place.
    let real_root = fs::canonicalize(root).map_err(|error| cannot_write(first, &error))?;
    for (path, bytes) in to_write {
        write_file(root, &real_root, path, bytes)?;
    }
    Ok(outcomes)
}

/// Whether the file `path` exists below `root`, once each folder on the way
/// to it has passed [`folder_problem`] and the file itself is neither a link
/// nor a folder. The first missing folder ends the walk: the file is new.
fn file_exists(root: &Path, path: &str) -> Result<bool, PublishRefused> {
    for (end, _) in path.match_indices('/') {
        let folder = &path[..end];
        match fs::symlink_metadata(root.join(folder)) {
            Ok(metadata) => {
                if let Some(problem) = folder_problem(folder, &metadata) {
                    return Err(PublishRefused(format!("{problem}; nothing was written")));
                }
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(error) => return Err(cannot_write(path, &error)),
        }
    }
    match fs::symlink_metadata(root.join(path)) {
        Ok(metadata) if metadata.file_type().is_symlink() => Err(inside_a_link(path)),
        Ok(metadata) if metadata.is_dir() => Err(PublishRefused(format!(
            "{path} is a folder where a file would be written; nothing was written"
        ))),
        Ok(_) => Ok(true),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(cannot_write(path, &error)),
    }
}

/// What is wrong with `folder` (relative to the app's folder) on the way to a
/// file: `<folder> is a symbolic link or inside one` for a symbolic link or a
/// junction (`is_symlink` holds for both), `<folder> is a file where a folder
/// is needed` for anything that is not a folder; `None` for a folder.
fn folder_problem(folder: &str, metadata: &fs::Metadata) -> Option<String> {
    if metadata.file_type().is_symlink() {
        Some(format!("{folder} is a symbolic link or inside one"))
    } else if metadata.is_dir() {
        None
    } else {
        Some(format!("{folder} is a file where a folder is needed"))
    }
}

/// A refusal met while writing, when the files before `path` may already be
/// written: `<problem>; it changed while publishing, and the files before
/// <path> were written`.
fn changed_while_writing(problem: &str, path: &str) -> PublishRefused {
    PublishRefused(format!(
        "{problem}; it changed while publishing, and the files before {path} were written"
    ))
}

/// Writes `bytes` to `path` below `root`: creates each missing folder (one
/// that turns out to exist is checked again), writes the bytes to a new file
/// beside the destination, checks that the new file's folder, links
/// resolved, is still below `real_root` (`root` with its links resolved),
/// and renames the new file over the destination. A refused or failed file
/// is removed.
fn write_file(
    root: &Path,
    real_root: &Path,
    path: &str,
    bytes: &[u8],
) -> Result<(), PublishRefused> {
    for (end, _) in path.match_indices('/') {
        let folder = &path[..end];
        match fs::create_dir(root.join(folder)) {
            Ok(()) => {}
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
                let metadata = fs::symlink_metadata(root.join(folder))
                    .map_err(|error| cannot_write(path, &error))?;
                if let Some(problem) = folder_problem(folder, &metadata) {
                    return Err(changed_while_writing(&problem, path));
                }
            }
            Err(error) => return Err(cannot_write(path, &error)),
        }
    }
    let destination = root.join(path);
    let name = path.rsplit_once('/').map_or(path, |(_, name)| name);
    let temporary =
        destination.with_file_name(format!(".{name}.navree-publish-{}.tmp", std::process::id()));
    // `create_new` never opens a file or a link that is already there.
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&temporary)
        .map_err(|error| cannot_write(path, &error))?;
    let written = file.write_all(bytes);
    // Closed before the rename, which Windows needs.
    drop(file);
    let folder = temporary.parent().unwrap_or(root);
    let refused = match written.and_then(|()| fs::canonicalize(folder)) {
        Err(error) => Some(cannot_write(path, &error)),
        // A folder on the way was swapped for a link after it was checked:
        // the new file is not below the app's folder.
        Ok(real_folder) if !real_folder.starts_with(real_root) => Some(changed_while_writing(
            &format!("the folder of {path} is a symbolic link or inside one"),
            path,
        )),
        Ok(_) => rename(&temporary, &destination)
            .err()
            .map(|error| cannot_write(path, &error)),
    };
    if let Some(refused) = refused {
        let _ = fs::remove_file(&temporary);
        return Err(refused);
    }
    Ok(())
}

/// `fs::rename`, tried again for a moment on Windows, where a program that
/// has just opened the new file (a virus scanner, an indexer) makes it fail
/// with "access is denied" (os error 5) or a sharing violation (os error
/// 32): four more tries, after 10, 40, 160 and 640 milliseconds.
#[cfg(windows)]
fn rename(from: &Path, to: &Path) -> io::Result<()> {
    for wait in [10, 40, 160, 640] {
        match fs::rename(from, to) {
            Err(error) if matches!(error.raw_os_error(), Some(5 | 32)) => {
                std::thread::sleep(std::time::Duration::from_millis(wait));
            }
            other => return other,
        }
    }
    fs::rename(from, to)
}

/// `fs::rename`: elsewhere a rename is not blocked by an open file.
#[cfg(not(windows))]
fn rename(from: &Path, to: &Path) -> io::Result<()> {
    fs::rename(from, to)
}

/// `<path> is a symbolic link or inside one; nothing was written`.
fn inside_a_link(path: &str) -> PublishRefused {
    PublishRefused(format!(
        "{path} is a symbolic link or inside one; nothing was written"
    ))
}

/// `cannot write <path>: <error>`.
fn cannot_write(path: &str, error: &io::Error) -> PublishRefused {
    PublishRefused(format!("cannot write {path}: {error}"))
}

/// The usage line `plugin:publish` repeats in its refusals.
const USAGE: &str =
    "usage: plugin:publish <plugin> [--tag views|locales|config|files] [--force] [--dry-run]";

/// The tags `plugin:publish` takes, as its refusals list them.
const TAGS: &str = "tags: views, locales, config, files";

/// What `plugin:publish` will do, every file checked and none written yet:
/// `run_with_args` runs the app's `config:publish` from `config_args` first,
/// then [`write`] writes the files, so a refusal from either check leaves
/// nothing written.
pub(crate) struct PublishRun {
    /// The arguments of the app's `config:publish` to run before the files
    /// are written (`--plugin <namespace>`, and `--force` when given): set
    /// when the config tag is asked for, the app has that command and this is
    /// no dry run.
    pub(crate) config_args: Option<Vec<String>>,
    /// Whether `--dry-run` was given.
    pub(crate) dry_run: bool,
    /// Whether `--force` was given.
    force: bool,
    /// The plugin's files under the tags asked for: their places in the app
    /// and their bytes.
    files: Vec<(String, &'static [u8])>,
    /// What the check found, one line per file in path order, as a dry run
    /// prints it.
    checked: Vec<String>,
    /// The lines printed after the files: what was left out.
    notes: Vec<String>,
}

/// `plugin:publish <plugin> [--tag views|locales|config|files] [--force]
/// [--dry-run]` with `args` (the words after the command), against `graph`,
/// for the app's folder `root`. `<plugin>` is a namespace or a plugin's
/// name; without `--tag`, every tag. Every file is checked by
/// [`publish_files`] as a dry run; nothing is written and nothing printed.
/// The config tag is the app's `config:publish --plugin <namespace>`, which
/// the caller runs from `config_args` before [`write`].
pub(crate) fn run(graph: &Graph, args: &[String], root: &Path) -> Result<PublishRun, BoxError> {
    let mut plugin: Option<&str> = None;
    let mut tag: Option<&str> = None;
    let (mut force, mut dry_run) = (false, false);
    let mut words = args.iter();
    while let Some(arg) = words.next() {
        match arg.as_str() {
            "--tag" if tag.is_none() => match words.next() {
                Some(word) => tag = Some(word.as_str()),
                None => return Err(format!("plugin:publish: --tag needs a tag ({TAGS})").into()),
            },
            "--force" => force = true,
            "--dry-run" => dry_run = true,
            word if plugin.is_none() && !word.starts_with('-') => plugin = Some(word),
            other => {
                return Err(
                    format!("plugin:publish: unexpected argument `{other}`; {USAGE}").into(),
                );
            }
        }
    }
    let Some(word) = plugin else {
        return Err(format!("plugin:publish: name the plugin to publish; {USAGE}").into());
    };
    // The file tags asked for, and whether the config tag is.
    let (tags, config): (Vec<PublishTag>, bool) = match tag {
        None => (PublishTag::ALL.to_vec(), true),
        Some("config") => (Vec::new(), true),
        Some(name) => match PublishTag::from_name(name) {
            Some(tag) => (vec![tag], false),
            None => {
                return Err(format!("plugin:publish: unknown tag `{name}` ({TAGS})").into());
            }
        },
    };

    let report = graph.plugins_report();
    let found = report
        .plugins
        .iter()
        .find(|plugin| plugin.info.namespace == word)
        .or_else(|| {
            report
                .plugins
                .iter()
                .find(|plugin| plugin.info.name == word)
        });
    let Some(found) = found else {
        let namespaces: Vec<&str> = report
            .plugins
            .iter()
            .map(|plugin| plugin.info.namespace)
            .collect();
        let known = if namespaces.is_empty() {
            "none".to_owned()
        } else {
            namespaces.join(", ")
        };
        return Err(
            format!("plugin:publish: no plugin is named `{word}` (plugins: {known})").into(),
        );
    };
    let (name, namespace) = (found.info.name, found.info.namespace);

    // Every file of the plugin under the tags asked for: its modules in
    // dependency order, then their files in registration order.
    let mut files: Vec<(String, &'static [u8])> = Vec::new();
    for &m in &graph.order {
        let module = &graph.modules[m];
        if module.plugin.as_ref().map(|info| info.name) != Some(name) {
            continue;
        }
        for publishable in shipped(module) {
            let tag = publishable.tag();
            if tags.contains(&tag) {
                files.extend(
                    publishable
                        .files()
                        .map(|(path, bytes)| (destination(tag, namespace, path), bytes)),
                );
            }
        }
    }

    let has_config = graph.has_command("config:publish");
    let mut notes = Vec::new();
    let checked = if files.is_empty() {
        match tag {
            Some(asked) if asked != "config" => {
                notes.push(format!(
                    "{asked}: plugin `{namespace}` has nothing to publish"
                ));
            }
            // Nothing at all will be published; with a `config:publish`
            // command, its own lines say whether a section was written.
            None if !has_config => {
                notes.push(format!(
                    "{namespace}: plugin `{namespace}` has nothing to publish"
                ));
            }
            _ => {}
        }
        Vec::new()
    } else {
        // Every check of the writer, as a dry run: nothing is written yet.
        publish_lines(root, &files, force, true)?
    };

    let mut config_args = None;
    if config {
        if !has_config {
            notes
                .push("config: the app has no ConfigModule, so no section is published".to_owned());
        } else if dry_run {
            notes.push(format!(
                "config: would run config:publish --plugin {namespace}"
            ));
        } else {
            let mut forwarded = vec!["--plugin".to_owned(), namespace.to_owned()];
            if force {
                forwarded.push("--force".to_owned());
            }
            config_args = Some(forwarded);
        }
    }
    Ok(PublishRun {
        config_args,
        dry_run,
        force,
        files,
        checked,
        notes,
    })
}

/// [`publish_files`] on `files` below `root`, as a dry run (it writes
/// nothing) or for real: the line of each file, in path order, or the
/// refusal after `plugin:publish: `.
fn publish_lines(
    root: &Path,
    files: &[(String, &'static [u8])],
    force: bool,
    dry_run: bool,
) -> Result<Vec<String>, BoxError> {
    let listed: Vec<(&str, &[u8])> = files
        .iter()
        .map(|(path, bytes)| (path.as_str(), *bytes))
        .collect();
    let published = publish_files(root, &listed, force, dry_run)
        .map_err(|refused| format!("plugin:publish: {refused}"))?;
    Ok(published
        .iter()
        .map(|(path, outcome)| outcome.line(path))
        .collect())
}

/// Writes the files [`run`] checked, below `root` (unless it was a dry run),
/// and gives the lines to print: one per file in path order, then what was
/// left out.
pub(crate) fn write(root: &Path, planned: &PublishRun) -> Result<Vec<String>, BoxError> {
    let mut lines = if planned.dry_run || planned.files.is_empty() {
        planned.checked.clone()
    } else {
        publish_lines(root, &planned.files, planned.force, false)?
    };
    lines.extend(planned.notes.iter().cloned());
    Ok(lines)
}

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

    use super::*;
    use crate::Publishable;

    /// A new, empty folder `navree-kernel-<name>-<process id>` in the
    /// system's temporary folder, removed on drop.
    struct TempFolder(PathBuf);

    impl TempFolder {
        fn new(name: &str) -> TempFolder {
            let path =
                std::env::temp_dir().join(format!("navree-kernel-{name}-{}", std::process::id()));
            let _ = fs::remove_dir_all(&path);
            fs::create_dir_all(&path).expect("a temporary folder");
            TempFolder(path)
        }
    }

    impl Drop for TempFolder {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    /// The line each outcome prints.
    fn lines(out: &[(String, Published)]) -> Vec<String> {
        out.iter()
            .map(|(path, published)| published.line(path))
            .collect()
    }

    /// Paths the rule accepts.
    fn accepted_paths() -> Vec<String> {
        let mut paths: Vec<String> = [
            "list.html",
            "admin/list.html",
            ".gitkeep",
            "a.b.c",
            "console.html",
            "con-list.html",
            "com10.css",
            "lpt.txt",
            "ਸੂਚਨਾ.html",
            "conin.html",
            "com⁴.css",
        ]
        .map(String::from)
        .to_vec();
        paths.push("a".repeat(128));
        paths.push(format!("{}/{}", "a".repeat(127), "b".repeat(127)));
        paths
    }

    /// Paths the rule refuses, one or more per shape.
    fn refused_paths() -> Vec<String> {
        let mut paths: Vec<String> = [
            "",
            "/",
            "/etc/navree.css",
            "../x",
            "a/../x",
            "./x",
            "a/./x",
            "a//b",
            "a/",
            "a\\b",
            "c:/x",
            "C:x",
            "banner.css:hidden",
            "a\u{1}b",
            "a\tb",
            "a\u{7f}b",
            "a<b",
            "a>b",
            "a\"b",
            "a|b",
            "a?b",
            "a*b",
            "list.html.",
            "list.html ",
            "...",
            ". ",
            "a/.../b",
            "con",
            "CON",
            "con.html",
            "Con.tar.gz",
            "nul",
            "aux.txt",
            "prn",
            "com0",
            "com1.css",
            "COM9",
            "lpt0",
            "lpt9",
            "Lpt5.log",
            "con .txt",
            "conin$",
            "CONIN$.log",
            "conout$",
            "CONOUT$.txt",
            "com¹",
            "emails/COM¹",
            "Com².css",
            "com³",
            "lpt¹",
            "lpt².html",
            "LPT³.txt",
        ]
        .map(String::from)
        .to_vec();
        paths.push("a".repeat(129));
        paths.push(format!("{}/{}", "a".repeat(128), "b".repeat(127)));
        paths
    }

    #[test]
    fn the_publish_path_rule_accepts_plain_paths_and_refuses_every_unsafe_shape() {
        for good in accepted_paths() {
            assert!(is_safe_relative_path(&good), "{good:?}");
        }
        for bad in refused_paths() {
            assert!(!is_safe_relative_path(&bad), "{bad:?}");
        }
        for good in [
            "en/announcements.ftl",
            "pa-IN/admin/announcements.ftl",
            "zh-Hant-TW/x.ftl",
        ] {
            assert!(is_locale_path(good), "{good}");
        }
        for bad in [
            "announcements.ftl",
            "e/x.ftl",
            "en_GB/x.ftl",
            "123/x.ftl",
            "en-/x.ftl",
        ] {
            assert!(!is_locale_path(bad), "{bad}");
        }
        assert_eq!(
            first_case_collision(["list.html", "show.html", "List.html"]),
            Some("List.html")
        );
        assert_eq!(
            first_case_collision(["list.html", "list.html"]),
            Some("list.html")
        );
        assert_eq!(first_case_collision(["a/list.html", "b/list.html"]), None);
        // `ß` upper-cases to `SS` but lower-cases to itself: only the
        // upper-case comparison catches this pair.
        assert_eq!(
            first_case_collision(["straße.html", "STRASSE.html"]),
            Some("STRASSE.html")
        );
        // The Kelvin sign lower-cases to `k` but upper-cases to itself: only
        // the lower-case comparison catches this pair.
        assert_eq!(
            first_case_collision(["k.html", "\u{212A}.html"]),
            Some("\u{212A}.html")
        );
        // Names that differ only in how an accent is composed (`é` as one
        // character, or `e` and a combining accent) are not caught: the
        // kernel has no normalisation table.
    }

    #[test]
    fn the_writer_writes_new_files_and_keeps_existing_ones_without_force() {
        let root = TempFolder::new("writer-keep");
        let banner = root.0.join("resources/announcements/banner.css");
        fs::create_dir_all(banner.parent().unwrap()).unwrap();
        fs::write(&banner, "/* Simran Kaur */").unwrap();
        let files = [
            ("resources/announcements/banner.css", &b"body{}"[..]),
            ("resources/announcements/print.css", &b"@media print{}"[..]),
        ];
        let out = publish_files(&root.0, &files, false, false).expect("published");
        assert_eq!(
            lines(&out),
            [
                "resources/announcements/banner.css: exists, kept (use --force to replace it)",
                "resources/announcements/print.css: written",
            ]
        );
        assert_eq!(fs::read_to_string(&banner).unwrap(), "/* Simran Kaur */");
        let out = publish_files(&root.0, &files, true, true).expect("dry run");
        assert_eq!(
            lines(&out),
            [
                "resources/announcements/banner.css: exists, would be replaced",
                "resources/announcements/print.css: exists, would be replaced",
            ]
        );
        assert_eq!(
            fs::read_to_string(&banner).unwrap(),
            "/* Simran Kaur */",
            "a dry run writes nothing"
        );
        fs::remove_file(root.0.join("resources/announcements/print.css")).unwrap();
        let out = publish_files(&root.0, &files, false, true).expect("dry run");
        assert_eq!(
            lines(&out),
            [
                "resources/announcements/banner.css: exists, would be kept (use --force to replace it)",
                "resources/announcements/print.css: would be written",
            ]
        );
        assert!(!root.0.join("resources/announcements/print.css").exists());
        let out = publish_files(&root.0, &files, true, false).expect("forced");
        assert_eq!(
            lines(&out)[0],
            "resources/announcements/banner.css: written"
        );
        assert_eq!(fs::read_to_string(&banner).unwrap(), "body{}");
    }

    #[test]
    fn the_writer_checks_every_file_before_the_first_write() {
        let root = TempFolder::new("writer-check");
        let unsafe_late = [
            ("resources/a/one.css", &b"x"[..]),
            ("resources/a/../two.css", &b"y"[..]),
        ];
        let refused = publish_files(&root.0, &unsafe_late, false, false).expect_err("refused");
        assert_eq!(
            refused.to_string(),
            "resources/a/../two.css is not a safe relative path; nothing was written"
        );
        assert!(!root.0.join("resources").exists(), "nothing was written");
        fs::create_dir_all(root.0.join("resources")).unwrap();
        fs::write(root.0.join("resources/a"), "a file").unwrap();
        let refused = publish_files(&root.0, &unsafe_late[..1], false, false).expect_err("refused");
        assert_eq!(
            refused.to_string(),
            "resources/a is a file where a folder is needed; nothing was written"
        );
        fs::remove_file(root.0.join("resources/a")).unwrap();
        fs::create_dir_all(root.0.join("resources/a/one.css")).unwrap();
        let refused = publish_files(&root.0, &unsafe_late[..1], true, false).expect_err("refused");
        assert_eq!(
            refused.to_string(),
            "resources/a/one.css is a folder where a file would be written; nothing was written"
        );
    }

    /// Two paths that would be one file, or a file that another path needs as its folder: the
    /// writer refuses them itself, before anything is written.
    #[test]
    fn the_writer_refuses_two_paths_that_would_be_one_file_or_a_file_and_its_folder() {
        let root = TempFolder::new("writer-conflicts");
        for (paths, refusal) in [
            (
                [
                    "resources/views/announcements/list.html",
                    "resources/views/announcements/List.html",
                ],
                "resources/views/announcements/list.html is the same file as another one on a disk that ignores case; nothing was written",
            ),
            (
                ["config/announcements.toml", "config/announcements.toml"],
                "config/announcements.toml is the same file as another one on a disk that ignores case; nothing was written",
            ),
            (
                [
                    "resources/views/announcements/admin",
                    "resources/views/announcements/admin/edit.html",
                ],
                "resources/views/announcements/admin would be both a file and the folder of resources/views/announcements/admin/edit.html; nothing was written",
            ),
            (
                [
                    "resources/views/announcements/Admin",
                    "resources/views/announcements/admin/edit.html",
                ],
                "resources/views/announcements/Admin would be both a file and the folder of resources/views/announcements/admin/edit.html; nothing was written",
            ),
        ] {
            let files = [
                (paths[0], &b"<ul></ul>"[..]),
                (paths[1], &b"<form></form>"[..]),
            ];
            for (force, dry_run) in [(false, false), (true, false), (false, true)] {
                let refused = publish_files(&root.0, &files, force, dry_run).expect_err(refusal);
                assert_eq!(refused.to_string(), refusal);
            }
            assert_eq!(
                fs::read_dir(&root.0).unwrap().count(),
                0,
                "nothing was written for {paths:?}"
            );
        }
        assert_eq!(
            first_file_and_folder(&["a/b", "a/b/c.html", "a"]),
            Some(("a/b", "a/b/c.html"))
        );
        assert_eq!(
            first_file_and_folder(&["admin.html", "admin/edit.html"]),
            None
        );
    }

    /// A folder that became a file after the check, met while writing: the refusal says that
    /// the files before it were written, which is what is true at that point.
    #[test]
    fn a_folder_that_changed_while_writing_is_refused_without_saying_nothing_was_written() {
        let root = TempFolder::new("writer-changed");
        fs::create_dir(root.0.join("resources")).unwrap();
        fs::write(root.0.join("resources/a"), "a file").unwrap();
        let real_root = fs::canonicalize(&root.0).unwrap();
        let refused =
            write_file(&root.0, &real_root, "resources/a/one.css", b"x").expect_err("a file");
        assert_eq!(
            refused.to_string(),
            "resources/a is a file where a folder is needed; it changed while publishing, and the files before resources/a/one.css were written"
        );
    }

    /// A new file whose folder, links resolved, is no longer below the app's folder just
    /// before the rename (a folder swapped for a link after it was checked) is not renamed
    /// into place, and the new file is removed.
    #[test]
    fn a_file_whose_folder_left_the_app_while_writing_is_not_put_in_place() {
        let root = TempFolder::new("writer-swapped");
        fs::create_dir(root.0.join("app")).unwrap();
        fs::create_dir(root.0.join("elsewhere")).unwrap();
        // As if the app's folder, links resolved, were `elsewhere`.
        let elsewhere = fs::canonicalize(root.0.join("elsewhere")).unwrap();
        let refused = write_file(
            &root.0.join("app"),
            &elsewhere,
            "resources/banner.css",
            b"body{}",
        )
        .expect_err("outside the app");
        assert_eq!(
            refused.to_string(),
            "the folder of resources/banner.css is a symbolic link or inside one; it changed while publishing, and the files before resources/banner.css were written"
        );
        assert_eq!(
            fs::read_dir(root.0.join("app/resources")).unwrap().count(),
            0,
            "neither the file nor the new file beside it is left"
        );
    }

    /// `config:publish --plugin` and `i18n:publish <plugin>` reach the writer without the
    /// boot check, and a section key is free text: the writer refuses every shape itself.
    #[test]
    fn the_writer_refuses_every_unsafe_shape_itself() {
        let root = TempFolder::new("writer-shapes");
        for path in refused_paths() {
            for force in [false, true] {
                let refused = publish_files(&root.0, &[(path.as_str(), b"x")], force, false)
                    .expect_err(&path);
                assert_eq!(
                    refused.to_string(),
                    format!("{path} is not a safe relative path; nothing was written")
                );
            }
            assert_eq!(
                fs::read_dir(&root.0).unwrap().count(),
                0,
                "nothing was written for {path:?}"
            );
        }
    }

    /// The link check covers the app's folder and below it, not the folders above it.
    #[cfg(unix)]
    #[test]
    fn plugin_publish_works_in_an_app_inside_a_linked_folder() {
        let root = TempFolder::new("writer-linked-app");
        fs::create_dir(root.0.join("real")).unwrap();
        std::os::unix::fs::symlink(root.0.join("real"), root.0.join("app")).unwrap();
        publish_files(
            &root.0.join("app"),
            &[("resources/announcements/banner.css", b"body{}")],
            false,
            false,
        )
        .expect("an app inside a linked folder publishes");
        assert!(
            root.0
                .join("real/resources/announcements/banner.css")
                .is_file()
        );
    }

    /// A plugin with the namespace `announcements` and one views file,
    /// `list.html`.
    struct Notices;

    impl crate::Module for Notices {
        fn register(&self, m: &mut crate::ModuleBuilder) {
            m.plugin(crate::plugin_info!(namespace = "announcements"))
                .contribute(Publishable::new(PublishTag::Views).file("list.html", b"<ul></ul>"));
        }
    }

    /// A plugin with the namespace `announcements` and no file.
    struct Empty;

    impl crate::Module for Empty {
        fn register(&self, m: &mut crate::ModuleBuilder) {
            m.plugin(crate::plugin_info!(namespace = "announcements"));
        }
    }

    /// A module with an offline `config:publish` command, as `ConfigModule`
    /// has.
    struct ConfigCommand;

    impl crate::Module for ConfigCommand {
        fn register(&self, m: &mut crate::ModuleBuilder) {
            m.command(
                crate::CommandSpec::new("config:publish", "Write a section's file", |_, _| async {
                    Ok(())
                })
                .offline(),
            );
        }
    }

    /// The validated graph of an app of `roots`.
    fn graph(roots: Vec<Box<dyn crate::Module>>) -> Graph {
        Graph::build(&roots, &[]).expect("a valid graph")
    }

    #[test]
    fn the_publish_lines_say_what_was_done_and_what_was_left() {
        let root = TempFolder::new("publish-lines");
        let args = |list: &[&str]| list.iter().map(|a| (*a).to_owned()).collect::<Vec<_>>();
        let no_config = "config: the app has no ConfigModule, so no section is published";
        let notices = graph(vec![Box::new(Notices)]);
        let planned = run(&notices, &args(&["announcements"]), &root.0).expect("checked");
        assert!(
            !root.0.join("resources").exists(),
            "run checks every file and writes none"
        );
        assert_eq!(
            (planned.config_args.clone(), planned.dry_run),
            (None, false)
        );
        assert_eq!(
            write(&root.0, &planned).expect("published"),
            [
                "resources/views/announcements/list.html: written",
                no_config
            ]
        );
        let planned = run(
            &notices,
            &args(&["announcements", "--tag", "files"]),
            &root.0,
        )
        .expect("nothing");
        assert_eq!(
            write(&root.0, &planned).expect("nothing"),
            ["files: plugin `announcements` has nothing to publish"]
        );
        let planned = run(
            &notices,
            &args(&["announcements", "--dry-run", "--force"]),
            &root.0,
        )
        .expect("dry run");
        assert!(planned.dry_run);
        assert_eq!(
            write(&root.0, &planned).expect("dry run"),
            [
                "resources/views/announcements/list.html: exists, would be replaced",
                no_config,
            ]
        );

        let empty = graph(vec![Box::new(Empty)]);
        let planned = run(&empty, &args(&["announcements"]), &root.0).expect("nothing at all");
        assert_eq!(
            write(&root.0, &planned).expect("nothing at all"),
            [
                "announcements: plugin `announcements` has nothing to publish",
                no_config,
            ]
        );

        let configured = graph(vec![Box::new(Empty), Box::new(ConfigCommand)]);
        let planned =
            run(&configured, &args(&["announcements", "--force"]), &root.0).expect("config");
        assert_eq!(
            planned.config_args,
            Some(args(&["--plugin", "announcements", "--force"]))
        );
        assert!(
            write(&root.0, &planned).expect("config").is_empty(),
            "config:publish says itself whether a section was written"
        );
        let planned =
            run(&configured, &args(&["announcements", "--dry-run"]), &root.0).expect("dry run");
        assert_eq!(planned.config_args, None);
        assert_eq!(
            write(&root.0, &planned).expect("dry run"),
            ["config: would run config:publish --plugin announcements"]
        );
    }
}