brrrty 0.0.24

Brrrty, a fast static site generator compatible with Eleventy (11ty) projects.
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
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
//! `brrrty init`: sets up an existing 11ty site to build with Brrrty.
//!
//! It adds Brrrty to `package.json` (a devDependency and the `build` and
//! `start` scripts) and writes `brrrty.config.rhai` from the 11ty config,
//! reading that without running it. Those two files, in the site's folder,
//! are all it ever writes, and it never overwrites a `brrrty.config.rhai`.

pub mod data;
mod js;
mod json;
mod port;

use std::fs;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};

pub use brrrty_config::CONFIG_FILE;

/// 11ty's config file names, in the order 11ty looks for them.
pub const ELEVENTY_CONFIGS: [&str; 4] = [
    ".eleventy.js",
    "eleventy.config.js",
    "eleventy.config.mjs",
    "eleventy.config.cjs",
];

const PACKAGE_JSON: &str = "package.json";
const VERSION: &str = env!("CARGO_PKG_VERSION");
const GETTING_STARTED: &str = "https://brrrty.com/docs/getting-started/";

/// How `brrrty init` was asked to run.
#[derive(Debug, Clone)]
pub struct Options {
    /// The site's folder.
    pub dir: PathBuf,
    /// Write without asking.
    pub yes: bool,
    /// Show the changes and write nothing.
    pub dry_run: bool,
    /// Standard input is a terminal, so Brrrty can ask.
    pub interactive: bool,
}

/// Why `brrrty init` stopped without writing anything.
#[derive(Debug)]
pub enum Refusal {
    /// The folder isn't an 11ty site (exit status 2).
    NotEleventy(String),
    /// Something Brrrty won't touch, or can't read (exit status 1).
    Refused(String),
}

/// One file `brrrty init` writes.
#[derive(Debug)]
pub struct Change {
    /// The name shown, relative to the site's folder.
    pub name: String,
    /// The file as it is, or `None` when it is new.
    pub old: Option<String>,
    pub new: String,
    /// Where the file is written: inside the site's folder, symlinks resolved.
    pub path: PathBuf,
}

/// What `brrrty init` would do.
#[derive(Debug)]
pub struct Plan {
    pub root: PathBuf,
    /// The 11ty config file read, if any.
    pub config: Option<String>,
    pub changes: Vec<Change>,
    /// `// TODO(brrrty)` markers in the new `brrrty.config.rhai`.
    pub todos: usize,
    /// JavaScript data files without a `.rhai` port, relative to the root.
    pub js_data: Vec<String>,
    /// Of those: translated to a `.rhai` beside it (the file and its port's name).
    pub js_translated: Vec<(String, String)>,
    /// Ones that only use what Brrrty has helpers for, with the helpers.
    pub js_hand: Vec<(String, Vec<&'static str>)>,
    /// Ones that need Node.
    pub js_node: Vec<String>,
    /// Things left for a person to change in `package.json`.
    pub advice: Vec<String>,
    /// `build:11ty` is in the scripts after the change.
    pub has_build_11ty: bool,
    /// The output folder, as the new config sets it.
    pub output: String,
}

/// The most `brrrty init` reads of `package.json` or an 11ty config.
pub const MAX_READ: u64 = 1 << 20;

const BOM: &str = "\u{feff}";

/// Whether `dir` looks like an 11ty site: `package.json` depends on
/// `@11ty/eleventy`, or 11ty's config file is there. Reads only regular
/// files inside `dir`, and at most [`MAX_READ`] bytes, so it can't hang or
/// fill memory.
pub fn looks_like_eleventy(dir: &Path) -> bool {
    let Ok(root) = fs::canonicalize(dir) else {
        return false;
    };
    detect(&root).is_some()
}

/// The reason `root` (canonical) is an 11ty site.
fn detect(root: &Path) -> Option<String> {
    if let Some(name) = ELEVENTY_CONFIGS.iter().find(|n| present(root, n)) {
        return Some((*name).to_string());
    }
    let text = match read_inside(root, PACKAGE_JSON) {
        Ok(Some(Read::Text(t))) => t,
        _ => return None,
    };
    let v: serde_json::Value =
        serde_json::from_str(text.strip_prefix(BOM).unwrap_or(&text)).ok()?;
    ["dependencies", "devDependencies"]
        .iter()
        .any(|k| v.get(k).and_then(|d| d.get("@11ty/eleventy")).is_some())
        .then(|| "package.json".to_string())
}

/// Whether `name` is in `root` as a file or a symlink, without opening it.
fn present(root: &Path, name: &str) -> bool {
    fs::symlink_metadata(root.join(name)).is_ok_and(|m| m.is_file() || m.file_type().is_symlink())
}

/// Whether a bare `brrrty` here should suggest `brrrty init`. Never fails.
pub fn should_hint(dir: &Path) -> bool {
    looks_like_eleventy(dir) && fs::symlink_metadata(dir.join(CONFIG_FILE)).is_err()
}

/// A file read by [`read_inside`].
enum Read {
    Text(String),
    /// Not UTF-8: its text with replacement characters.
    Lossy(String),
    /// Larger than [`MAX_READ`].
    TooBig,
}

/// Where `name` in `root` really is: a regular file inside `root`, through a
/// symlink only when it stays inside. `Ok(None)` when there is nothing there.
fn resolve_inside(root: &Path, name: &str) -> Result<Option<PathBuf>, String> {
    let p = root.join(name);
    let meta = match fs::symlink_metadata(&p) {
        Ok(m) => m,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("Brrrty can't look at {name}: {e}")),
    };
    let real = if meta.file_type().is_symlink() {
        let real = fs::canonicalize(&p)
            .map_err(|e| format!("{name} is a symlink Brrrty can't follow ({e})"))?;
        if !real.starts_with(root) {
            return Err(format!(
                "{name} is a symlink to {}, outside {}. Brrrty only reads and writes inside the site's folder",
                real.display(),
                root.display()
            ));
        }
        real
    } else {
        p
    };
    let meta = fs::metadata(&real).map_err(|e| format!("Brrrty can't look at {name}: {e}"))?;
    if !meta.is_file() {
        return Err(format!("{name} isn't a regular file"));
    }
    Ok(Some(real))
}

/// Read `name` in `root` with [`resolve_inside`]'s rules, at most [`MAX_READ`] bytes.
fn read_inside(root: &Path, name: &str) -> Result<Option<Read>, String> {
    use std::io::Read as _;
    let Some(path) = resolve_inside(root, name)? else {
        return Ok(None);
    };
    let mut options = fs::OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.custom_flags(libc::O_NONBLOCK);
    }
    let f = options
        .open(&path)
        .map_err(|e| format!("Brrrty can't read {name}: {e}"))?;
    // Checked again on the open file, in case it changed in between.
    if !f.metadata().is_ok_and(|m| m.is_file()) {
        return Err(format!("{name} isn't a regular file"));
    }
    let mut bytes = Vec::new();
    f.take(MAX_READ + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| format!("Brrrty can't read {name}: {e}"))?;
    if bytes.len() as u64 > MAX_READ {
        return Ok(Some(Read::TooBig));
    }
    Ok(Some(match String::from_utf8(bytes) {
        Ok(s) => Read::Text(s),
        Err(e) => Read::Lossy(String::from_utf8_lossy(e.as_bytes()).into_owned()),
    }))
}

/// Where `name` in `root` is written: see [`resolve_inside`].
fn target(root: &Path, name: &str) -> Result<PathBuf, Refusal> {
    match resolve_inside(root, name) {
        Ok(Some(p)) => Ok(p),
        Ok(None) => Ok(root.join(name)),
        Err(why) => Err(Refusal::Refused(format!("{why}, so nothing was written."))),
    }
}

/// Work out what `brrrty init` would change in `dir`, writing nothing.
pub fn plan(dir: &Path) -> Result<Plan, Refusal> {
    let root = fs::canonicalize(dir).map_err(|e| {
        Refusal::NotEleventy(format!(
            "Brrrty can't open the folder {}: {e}",
            dir.display()
        ))
    })?;
    if !root.is_dir() {
        return Err(Refusal::NotEleventy(format!(
            "{} isn't a folder.",
            dir.display()
        )));
    }
    if fs::symlink_metadata(root.join(CONFIG_FILE)).is_ok() {
        return Err(Refusal::Refused(format!(
            "{CONFIG_FILE} already exists in {}, and `brrrty init` never overwrites it, so nothing was written. To start again from the 11ty config, move it out of the way and run `brrrty init` again.",
            root.display()
        )));
    }
    let package_path = target(&root, PACKAGE_JSON)?;
    let config_path = target(&root, CONFIG_FILE)?;
    if detect(&root).is_none() {
        return Err(Refusal::NotEleventy(format!(
            "{} doesn't look like an 11ty site: there is no package.json that depends on @11ty/eleventy, and no eleventy.config.js, eleventy.config.mjs, eleventy.config.cjs or .eleventy.js. Run `brrrty init` in your site's folder, or point --dir at it.",
            root.display()
        )));
    }

    // package.json
    let old_package = match read_inside(&root, PACKAGE_JSON) {
        Ok(None) => None,
        Ok(Some(Read::Text(s))) => Some(s),
        Ok(Some(Read::Lossy(_))) => {
            return Err(Refusal::Refused(
                "package.json isn't UTF-8, so nothing was written.".into(),
            ));
        }
        Ok(Some(Read::TooBig)) => {
            return Err(Refusal::Refused(format!(
                "package.json is larger than {} MiB, so Brrrty didn't read it and nothing was written.",
                MAX_READ >> 20
            )));
        }
        Err(why) => return Err(Refusal::Refused(format!("{why}, so nothing was written."))),
    };
    let edited = match &old_package {
        Some(src) => match src.strip_prefix(BOM) {
            Some(rest) => {
                let mut e = edit_package(rest)?;
                e.text.insert_str(0, BOM);
                e
            }
            None => edit_package(src)?,
        },
        None => Edited {
            text: new_package(),
            advice: Vec::new(),
            has_build_11ty: false,
        },
    };

    // brrrty.config.rhai: from the config 11ty reads, which the build script's `--config`
    // may name instead of the default. What 11ty is run with is read from the scripts as
    // they are before the edit above: after it, `build` is Brrrty's, which would make
    // every 11ty run that writes elsewhere (a GitLab Pages job's `--output=public`) look
    // like a comparison with it. The `11ty flags` hash is of the scripts after the edit,
    // as a build will read them.
    let parse =
        |t: &str| serde_json::from_str::<serde_json::Value>(t.strip_prefix(BOM).unwrap_or(t)).ok();
    let before_edit = old_package
        .as_deref()
        .and_then(parse)
        .unwrap_or_else(|| serde_json::json!({}));
    let mut cli = brrrty_config::eleventy_cli::find(&before_edit, &root);
    // TODOs name the scripts as they are after the edit, which keeps 11ty's `build` as
    // `build:11ty`.
    if let (Some(c), Some(after)) = (cli.as_mut(), parse(&edited.text)) {
        for name in ["build", "start"] {
            let kept = format!("{name}:11ty");
            let was = before_edit["scripts"].get(name);
            if was.is_some()
                && after["scripts"].get(&kept) == was
                && after["scripts"].get(name) != was
            {
                let rename = |s: &mut String| {
                    if s == name {
                        *s = kept.clone();
                    } else if let Some(rest) = s.strip_prefix(&format!("{name} → ")) {
                        *s = format!("{kept} → {rest}");
                    }
                };
                rename(&mut c.script);
                let (from, to) = (
                    format!("package.json, scripts.{name} "),
                    format!("package.json, scripts.{kept} "),
                );
                for t in &mut c.todos {
                    rename(&mut t.script);
                    t.why = t.why.replace(&from, &to);
                }
            }
        }
    }
    let cli = cli.as_ref();
    let flags_hash = parse(&edited.text)
        .and_then(|v| brrrty_config::eleventy_cli::find(&v, &root))
        .map(|c| c.fingerprint());
    let named = cli.and_then(|c| c.config.clone());
    let config: Option<String> = match &named {
        Some(n) if n.is_empty() => None,
        Some(n) => Some(brrrty_config::eleventy_cli::config_path(&root, n)),
        None => ELEVENTY_CONFIGS
            .iter()
            .find(|n| present(&root, n))
            .map(|n| (*n).to_string()),
    };
    let (mut rhai, todos, input, output) = match &config {
        Some(name) => {
            let outside = !brrrty_config::markers::is_inside(name);
            let read = if outside {
                Err(format!("{name} is outside the site's folder"))
            } else {
                read_inside(&root, name)
            };
            let p = match read {
                Ok(Some(Read::Text(src))) => {
                    // The site's own modules the config uses, read with the same care.
                    let load = |path: &str| -> Result<Option<String>, String> {
                        if !brrrty_config::markers::is_inside(path) {
                            return Ok(None);
                        }
                        match read_inside(&root, path)? {
                            None => Ok(None),
                            Some(Read::Text(s)) => Ok(Some(s)),
                            Some(_) => Err(format!("{path} isn't UTF-8 text Brrrty reads")),
                        }
                    };
                    let rss = rss_version(&root, &before_edit);
                    let site = port::Site {
                        cli,
                        load: Some(&load),
                        rss: rss.as_deref().and_then(brrrty_config::rss_version::major),
                    };
                    let mut p = port::port_site(src.strip_prefix(BOM).unwrap_or(&src), name, site);
                    record_source(&mut p.text, name, src.as_bytes());
                    for (module, text) in &p.modules {
                        record_module(&mut p.text, module, text.as_bytes());
                    }
                    // The plugin's version, which a build checks again.
                    if p.uses_rss
                        && let Some(v) = &rss
                    {
                        let line = format!("{}{}\n", brrrty_config::rss_version::RSS_LINE, one_line_version(v));
                        let at = p.text.find("\n\n").map_or(p.text.len(), |i| i + 1);
                        p.text.insert_str(at, &line);
                    }
                    p
                }
                Ok(Some(Read::Lossy(src))) => port::unreadable(
                    &src,
                    name,
                    "it isn't UTF-8, so Brrrty couldn't read it",
                    cli,
                ),
                Ok(Some(Read::TooBig)) => port::unreadable(
                    "",
                    name,
                    &format!("it is larger than {} MiB, so Brrrty didn't read it", MAX_READ >> 20),
                    cli,
                ),
                Ok(None) => port::unreadable(
                    "",
                    name,
                    "package.json's build script names it with `--config`, but it doesn't exist, so 11ty stops",
                    cli,
                ),
                Err(why) if named.is_some() => port::unreadable(
                    "",
                    name,
                    &format!("package.json's build script names it with `--config`, and {why}"),
                    cli,
                ),
                Err(why) => {
                    return Err(Refusal::Refused(format!("{why}, so nothing was written.")));
                }
            };
            (p.text, p.todos, p.input, p.output)
        }
        None if cli.is_some() => {
            let p = port::no_config(cli);
            (p.text, p.todos, p.input, p.output)
        }
        None => (
            "// Written by `brrrty init`. This site has no 11ty config file, so\n// Brrrty uses 11ty's defaults, as 11ty does.\n// Reference: https://brrrty.com/docs/configuration/\n".to_string(),
            0,
            None,
            None,
        ),
    };
    if let Some(h) = &flags_hash {
        record_flags(&mut rhai, h);
    }

    let js_data = match &input {
        Some(i) => match fs::canonicalize(root.join(i)) {
            Ok(input) if input.starts_with(&root) => js_data_files(&root, &input),
            _ => Vec::new(),
        },
        None => js_data_files(&root, &root),
    };
    let mut js_translated = Vec::new();
    let mut js_hand = Vec::new();
    let mut js_node = Vec::new();
    let mut ports = Vec::new();
    // One `.rhai` stands in for every JavaScript file of its name (`site.js` and
    // `site.mjs`, which 11ty merges): such files are never translated.
    let stem = |f: &str| f.rsplit_once('.').map_or(f, |(s, _)| s).to_string();
    // In a `"type": "module"` package a `.js` file is an ES module, where
    // `module.exports` throws: 11ty can't load such a file, so it isn't
    // translated into one Brrrty can.
    let esm_package = old_package
        .as_deref()
        .and_then(|t| serde_json::from_str::<serde_json::Value>(t).ok())
        .is_some_and(|v| v.get("type").and_then(|t| t.as_str()) == Some("module"));
    for f in &js_data {
        let shared = js_data.iter().any(|g| g != f && stem(g) == stem(f));
        let class = match read_inside(&root, f) {
            _ if shared => data::DataClass::NeedsNode,
            Ok(Some(Read::Text(src)))
                if esm_package && f.ends_with(".js") && data::uses_commonjs(&src) =>
            {
                js_node.push(format!(
                    "{f} (uses `module.exports` in a \"type\": \"module\" package, which 11ty can't load either)"
                ));
                continue;
            }
            Ok(Some(Read::Text(src))) => data::classify(src.strip_prefix(BOM).unwrap_or(&src)),
            _ => data::DataClass::NeedsNode,
        };
        match class {
            data::DataClass::Translatable(r) => {
                let (stem, _) = f.rsplit_once('.').unwrap_or((f, ""));
                let port = format!("{stem}.rhai");
                let js_name = f.rsplit('/').next().unwrap_or(f);
                let port_name = port.rsplit('/').next().unwrap_or(&port).to_string();
                ports.push(Change {
                    name: port.clone(),
                    old: None,
                    new: format!(
                        "// Translated by `brrrty init` from {js_name}, whose value is this literal.\n// Brrrty reads this file instead of {js_name}. Once `brrrty doctor` says the\n// port is identical, you can delete {js_name}.\n{r}\n"
                    ),
                    path: root.join(&port),
                });
                js_translated.push((f.clone(), port_name));
            }
            data::DataClass::HandPort(helpers) => js_hand.push((f.clone(), helpers)),
            data::DataClass::NeedsNode => js_node.push(f.clone()),
        }
    }
    // JavaScript templates have no Rhai form: they run in Node too.
    let js_templates = match &input {
        Some(i) => match fs::canonicalize(root.join(i)) {
            Ok(input) if input.starts_with(&root) => js_template_files(&root, &input),
            _ => Vec::new(),
        },
        None => js_template_files(&root, &root),
    };
    // Files left in JavaScript keep running, in the site's own Node.
    if !js_hand.is_empty() || !js_node.is_empty() || !js_templates.is_empty() {
        let mut line = String::new();
        if !js_hand.is_empty() || !js_node.is_empty() {
            line.push_str(
                "// JavaScript data files Brrrty runs in your own Node, as 11ty does\n// (`brrrty init` couldn't translate them to Rhai):\n",
            );
            for f in js_hand.iter().map(|(f, _)| f).chain(&js_node) {
                line.push_str(&format!("//   {f}\n"));
            }
        }
        if !js_templates.is_empty() {
            line.push_str("// JavaScript templates Brrrty runs in your own Node, as 11ty does:\n");
            for f in &js_templates {
                line.push_str(&format!("//   {f}\n"));
            }
        }
        line.push_str("config.set_js_data(\"node\");\n\n");
        match rhai.find("\n\n") {
            Some(i) => rhai.insert_str(i + 2, &line),
            None => {
                rhai.push('\n');
                rhai.push_str(line.trim_end());
                rhai.push('\n');
            }
        }
    }

    let mut changes = Vec::new();
    // The new file first: it is the one that can't already exist.
    changes.push(Change {
        name: CONFIG_FILE.to_string(),
        old: None,
        new: rhai,
        path: config_path,
    });
    if old_package.as_deref() != Some(edited.text.as_str()) {
        changes.push(Change {
            name: PACKAGE_JSON.to_string(),
            old: old_package,
            new: edited.text,
            path: package_path,
        });
    }

    changes.extend(ports);
    Ok(Plan {
        root,
        config,
        changes,
        todos,
        js_data,
        js_translated,
        js_hand,
        js_node,
        advice: edited.advice,
        has_build_11ty: edited.has_build_11ty,
        output: output.unwrap_or_else(|| "_site".into()),
    })
}

/// Add the `Ported from` line, with `bytes`' hash, after the header's comment lines: a
/// build warns when the 11ty config no longer has that hash.
fn record_source(text: &mut String, name: &str, bytes: &[u8]) {
    use brrrty_config::markers::{PORTED_FROM, source_hash};
    let line = format!("{PORTED_FROM}{name} {}\n", source_hash(bytes));
    let at = text.find("\n\n").map_or(text.len(), |i| i + 1);
    text.insert_str(at, &line);
}

/// Add an `Also ported from` line for one of the site's modules the config
/// uses: a build warns when it changes.
fn record_module(text: &mut String, name: &str, bytes: &[u8]) {
    use brrrty_config::markers::{ALSO_PORTED_FROM, source_hash};
    let line = format!("{ALSO_PORTED_FROM}{name} {}\n", source_hash(bytes));
    let at = text.find("\n\n").map_or(text.len(), |i| i + 1);
    text.insert_str(at, &line);
}

/// The version of `@11ty/eleventy-plugin-rss` the site installs: from
/// package-lock.json, the installed package, or package.json's range.
fn rss_version(root: &Path, package: &serde_json::Value) -> Option<String> {
    use brrrty_config::rss_version::{PACKAGE, from_files};
    let text = |name: &str| -> Option<String> {
        match read_inside(root, name) {
            Ok(Some(Read::Text(t))) => Some(t),
            _ => None,
        }
    };
    from_files(
        text("package-lock.json").as_deref(),
        text(&format!("node_modules/{PACKAGE}/package.json")).as_deref(),
        Some(&package.to_string()),
    )
}

/// A version as one safe comment line.
fn one_line_version(v: &str) -> String {
    v.chars()
        .filter(|c| !c.is_control() && !matches!(c, '\u{2028}' | '\u{2029}' | '\u{85}'))
        .collect()
}

/// Add the line recording what the scripts pass to 11ty: a build warns when they change.
fn record_flags(text: &mut String, hash: &str) {
    use brrrty_config::eleventy_cli::FLAGS_LINE;
    let line = format!("{FLAGS_LINE}{hash}\n");
    let at = text.find("\n\n").map_or(text.len(), |i| i + 1);
    text.insert_str(at, &line);
}

struct Edited {
    text: String,
    advice: Vec<String>,
    has_build_11ty: bool,
}

fn new_package() -> String {
    format!(
        "{{\n  \"private\": true,\n  \"scripts\": {{\n    \"build\": \"brrrty build\",\n    \"start\": \"brrrty serve\"\n  }},\n  \"devDependencies\": {{\n    \"brrrty\": \"{VERSION}\"\n  }}\n}}\n"
    )
}

/// `text` with control characters escaped, so a hostile `package.json` or
/// config can't break a line or send escape codes to the terminal.
fn shown(text: &str) -> String {
    text.chars()
        .flat_map(|c| {
            let escaped: Vec<char> = if c.is_control() {
                c.escape_default().collect()
            } else {
                vec![c]
            };
            escaped
        })
        .collect()
}

/// [`shown`], keeping line breaks and tabs: for the diff.
fn shown_lines(text: &str) -> String {
    text.split('\n')
        .map(|l| {
            l.split('\t')
                .map(|p| shown(p.strip_suffix('\r').unwrap_or(p)))
                .collect::<Vec<_>>()
                .join("\t")
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Whether a script is exactly one plain 11ty command, which init can rewrite.
fn is_eleventy_command(cmd: &str) -> bool {
    brrrty_config::eleventy_cli::is_plain_eleventy_command(cmd)
}

/// `cmd` with the `TZ` an 11ty command sets before it, through `cross-env` when it
/// does (`TZ=Asia/Tokyo eleventy` gives `TZ=Asia/Tokyo brrrty build`).
fn with_prefix(eleventy: &str, cmd: &str) -> String {
    // Only `TZ` changes what Brrrty writes; the rest (`NODE_OPTIONS`, `NODE_ENV`) is
    // for Node, which Brrrty isn't.
    let mut tz = Vec::new();
    let mut cross_env = false;
    for w in eleventy.split_whitespace() {
        if w == "cross-env" {
            cross_env = true;
        } else if w == "env" {
            continue;
        } else if w.split_once('=').is_some_and(|(k, _)| {
            !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        }) {
            if w.starts_with("TZ=") {
                tz.push(w);
            }
        } else {
            break;
        }
    }
    match (tz.is_empty(), cross_env) {
        (true, _) => cmd.to_string(),
        (false, true) => format!("cross-env {} {cmd}", tz.join(" ")),
        (false, false) => format!("{} {cmd}", tz.join(" ")),
    }
}

/// The step of a compound script (`a && b`, `a; b`, `a | b`) that is an
/// 11ty command, if one is.
fn eleventy_step(cmd: &str) -> Option<&str> {
    cmd.split("&&")
        .flat_map(|p| p.split("||"))
        .flat_map(|p| p.split(';'))
        .flat_map(|p| p.split('|'))
        .map(str::trim)
        .find(|step| is_eleventy_command(step))
}

fn edit_package(src: &str) -> Result<Edited, Refusal> {
    let bad =
        |why: String| Refusal::Refused(format!("package.json {why}, so nothing was written."));
    let value: serde_json::Value =
        serde_json::from_str(src).map_err(|e| bad(format!("isn't valid JSON ({e})")))?;
    if !value.is_object() {
        return Err(bad("isn't a JSON object".into()));
    }
    let top = json::object_at(src, 0).ok_or_else(|| bad("couldn't be read".into()))?;
    let style = json::Style::of(src, &top);
    let mut edits = Vec::new();
    let mut advice = Vec::new();
    let mut top_append: Vec<(String, String)> = Vec::new();
    // What the file should hold afterwards, to check the edit against.
    let mut expect = value.clone();
    let set = |expect: &mut serde_json::Value, object: &str, key: &str, v: &str| {
        if let Some(o) = expect.as_object_mut() {
            let entry = o
                .entry(object.to_string())
                .or_insert_with(|| serde_json::Value::Object(Default::default()));
            if let Some(inner) = entry.as_object_mut() {
                inner.insert(key.to_string(), serde_json::Value::String(v.to_string()));
            }
        }
    };

    // Scripts.
    let wanted = [("build", "brrrty build"), ("start", "brrrty serve")];
    match top.get("scripts") {
        None => {
            top_append.push(("scripts".into(), json::new_object(1, &style, &wanted)));
            for (name, cmd) in wanted {
                set(&mut expect, "scripts", name, cmd);
            }
        }
        Some(m) => match json::object_at(src, m.value_start) {
            None => advice.push(
                "`scripts` in package.json isn't an object, so Brrrty left it alone. Add \"build\": \"brrrty build\" and \"start\": \"brrrty serve\" to it.".into(),
            ),
            Some(scripts) => {
                let string = |k: &str| {
                    value["scripts"]
                        .get(k)
                        .and_then(|v| v.as_str())
                        .map(str::to_string)
                };
                let mut append = Vec::new();
                // The 11ty `build` command's TZ goes to `brrrty serve` too, unless `start`
                // sets its own: serve writes the output folder as build does.
                let build_tz = string("build")
                    .and_then(|b| brrrty_config::eleventy_cli::rewritable_step(&b))
                    .unwrap_or_default();
                let tz_from = |name: &str, own: &str| -> String {
                    if name == "start" && !own.contains("TZ=") {
                        build_tz.clone()
                    } else {
                        own.to_string()
                    }
                };
                for (name, cmd) in wanted {
                    let Some(member) = scripts.get(name) else {
                        let cmd = &with_prefix(&tz_from(name, ""), cmd);
                        let quoted = serde_json::to_string(cmd).unwrap_or_default();
                        append.push((name.to_string(), quoted));
                        set(&mut expect, "scripts", name, cmd);
                        continue;
                    };
                    let current = string(name);
                    if current.as_deref() == Some(cmd) {
                        continue;
                    }
                    let keep = format!("{name}:11ty");
                    match current {
                        // One plain 11ty command, alone or among other commands
                        // (`sass a b && eleventy`), with nothing that changes the shell's state.
                        Some(old)
                            if brrrty_config::eleventy_cli::rewritable_step(&old).is_some() =>
                        {
                            if scripts.get(&keep).is_some() {
                                advice.push(format!(
                                    "scripts.{name} runs 11ty, and scripts.{keep} is taken, so Brrrty left both alone. Change scripts.{name} to \"{cmd}\" when you're ready."
                                ));
                                continue;
                            }
                            // Rename it to `name:11ty`, with the new script in front, run with
                            // the same environment settings (`TZ=Asia/Tokyo`), which can
                            // change the pages.
                            let step = brrrty_config::eleventy_cli::rewritable_step(&old)
                                .unwrap_or_default();
                            let brrrty = with_prefix(&tz_from(name, &step), cmd);
                            // The other steps stay, in their order: only the 11ty one
                            // becomes Brrrty's.
                            let cmd = &if is_eleventy_command(&old) {
                                brrrty
                            } else {
                                old.replacen(&step, &brrrty, 1)
                            };
                            let quoted = serde_json::to_string(cmd).unwrap_or_default();
                            let i = scripts
                                .members
                                .iter()
                                .rposition(|m| m.key == name)
                                .unwrap_or(0);
                            let prev_end = if i == 0 {
                                scripts.open + 1
                            } else {
                                scripts.members[i - 1].value_end
                            };
                            let mut e = json::insert_before(src, prev_end, member, name, &quoted);
                            e.end = member.key_end;
                            e.text.push_str(&serde_json::to_string(&keep).unwrap_or_default());
                            edits.push(e);
                            set(&mut expect, "scripts", name, cmd);
                            set(&mut expect, "scripts", &keep, &old);
                        }
                        Some(old) => match eleventy_step(&old) {
                            Some(step) => advice.push(format!(
                                "scripts.{name} runs 11ty as one step of \"{}\", so Brrrty left it alone. To use Brrrty there, copy it to scripts.{keep} (to compare with 11ty), then replace `{}` in scripts.{name} with `{}`.", shown(&old), shown(step), shown(&with_prefix(step, cmd))
                            )),
                            None => advice.push(format!(
                                "scripts.{name} runs \"{}\", which isn't an 11ty command, so Brrrty left it alone. Where it runs 11ty, run `{cmd}` instead.", shown(&old)
                            )),
                        },
                        None => advice.push(format!(
                            "scripts.{name} isn't a string, so Brrrty left it alone. Set it to \"{cmd}\"."
                        )),
                    }
                }
                if !append.is_empty() {
                    edits.push(json::append(src, &scripts, 1, &style, &append));
                }
                // Other scripts that run 11ty.
                if let Some(all) = value["scripts"].as_object() {
                    for (k, v) in all {
                        let Some(cmd) = v.as_str() else { continue };
                        if ["build", "start", "build:11ty", "start:11ty"].contains(&k.as_str()) {
                            continue;
                        }
                        if is_eleventy_command(cmd) || eleventy_step(cmd).is_some() {
                            advice.push(format!(
                                "scripts.{} runs 11ty (\"{}\"). Brrrty's commands are `brrrty build` and `brrrty serve`, if you want it to run Brrrty.", shown(k), shown(cmd)
                            ));
                        }
                    }
                }
            }
        },
    }

    // The devDependency.
    let listed = ["dependencies", "devDependencies"]
        .iter()
        .find_map(|k| value.get(k).and_then(|d| d.get("brrrty")).map(|v| (*k, v)));
    match listed {
        Some((k, v)) => {
            if v.as_str() != Some(VERSION) {
                advice.push(format!(
                    "{k} already has brrrty at {}, so Brrrty left it alone. This is brrrty {VERSION}.", shown(&v.to_string())
                ));
            }
        }
        None => {
            let dep = serde_json::to_string(VERSION).unwrap_or_default();
            match top
                .get("devDependencies")
                .and_then(|m| json::object_at(src, m.value_start))
            {
                Some(dev) => {
                    set(&mut expect, "devDependencies", "brrrty", VERSION);
                    // In order, as npm keeps them.
                    match dev.members.iter().position(|m| m.key.as_str() > "brrrty") {
                        Some(i) => {
                            let prev_end = if i == 0 {
                                dev.open + 1
                            } else {
                                dev.members[i - 1].value_end
                            };
                            edits.push(json::insert_before(
                                src,
                                prev_end,
                                &dev.members[i],
                                "brrrty",
                                &dep,
                            ));
                        }
                        None => edits.push(json::append(
                            src,
                            &dev,
                            1,
                            &style,
                            &[("brrrty".into(), dep)],
                        )),
                    }
                }
                None if top.get("devDependencies").is_some() => advice.push(format!(
                    "`devDependencies` in package.json isn't an object, so Brrrty left it alone. Add \"brrrty\": \"{VERSION}\" to it."
                )),
                None => {
                    set(&mut expect, "devDependencies", "brrrty", VERSION);
                    top_append.push((
                        "devDependencies".into(),
                        json::new_object(1, &style, &[("brrrty", VERSION)]),
                    ));
                }
            }
        }
    }
    if !top_append.is_empty() {
        edits.push(json::append(src, &top, 0, &style, &top_append));
    }
    let text = json::apply(src, edits);
    // The edit must leave exactly the original plus the intended changes.
    let check: serde_json::Value =
        serde_json::from_str(&text).map_err(|e| bad(format!("couldn't be edited safely ({e})")))?;
    if check != expect {
        return Err(bad("couldn't be edited safely".into()));
    }
    let has_build_11ty = check["scripts"]
        .get("build:11ty")
        .and_then(|v| v.as_str())
        .is_some_and(is_eleventy_command);
    Ok(Edited {
        text,
        advice,
        has_build_11ty,
    })
}

/// JavaScript data files without a `.rhai` next to them: in `_data`, and
/// `*.11tydata.js` files anywhere in the input folder.
fn js_data_files(root: &Path, input: &Path) -> Vec<String> {
    let mut found = Vec::new();
    let mut budget = 100_000usize;
    walk(input, 0, &mut budget, &mut |p| {
        let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default();
        let Some((stem, ext)) = name.rsplit_once('.') else {
            return;
        };
        if !matches!(ext, "js" | "cjs" | "mjs") {
            return;
        }
        let in_data = p.starts_with(input.join("_data"));
        if !in_data && !stem.ends_with(".11tydata") {
            return;
        }
        if p.with_file_name(format!("{stem}.rhai")).exists() {
            return;
        }
        let shown = p.strip_prefix(root).unwrap_or(p);
        found.push(shown.to_string_lossy().replace('\\', "/"));
    });
    found.sort();
    found
}

/// JavaScript templates (`.11ty.js`, `.11ty.cjs`, `.11ty.mjs`) in the input
/// folder, including JavaScript layouts.
fn js_template_files(root: &Path, input: &Path) -> Vec<String> {
    let mut found = Vec::new();
    let mut budget = 100_000usize;
    walk(input, 0, &mut budget, &mut |p| {
        let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default();
        let lower = name.to_ascii_lowercase();
        if [".11ty.js", ".11ty.cjs", ".11ty.mjs"]
            .iter()
            .any(|x| lower.ends_with(x) && lower.len() > x.len())
        {
            let shown = p.strip_prefix(root).unwrap_or(p);
            found.push(shown.to_string_lossy().replace('\\', "/"));
        }
    });
    found.sort();
    found
}

/// Visit the files under `dir` without following symlinks, giving up after
/// `budget` entries.
fn walk(dir: &Path, depth: usize, budget: &mut usize, f: &mut dyn FnMut(&Path)) {
    if depth > 32 {
        return;
    }
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };
    for e in entries.flatten() {
        if *budget == 0 {
            return;
        }
        *budget -= 1;
        let name = e.file_name();
        let name = name.to_string_lossy();
        let Ok(kind) = e.file_type() else { continue };
        if kind.is_dir() {
            if name.starts_with('.') || name == "node_modules" || name == "_site" {
                continue;
            }
            walk(&e.path(), depth + 1, budget, f);
        } else if kind.is_file() {
            f(&e.path());
        }
    }
}

/// The changes as a unified diff.
pub fn diff(plan: &Plan) -> String {
    let mut out = String::new();
    for c in &plan.changes {
        let old = c.old.as_deref().unwrap_or("");
        let a = if c.old.is_some() {
            format!("a/{}", c.name)
        } else {
            "/dev/null".into()
        };
        let b = format!("b/{}", c.name);
        let d = similar::TextDiff::from_lines(old, &c.new);
        out.push_str(
            &d.unified_diff()
                .context_radius(3)
                .header(&a, &b)
                .to_string(),
        );
    }
    out
}

/// Write the changes, each atomically.
///
/// A new file is linked into place, so one that appeared since the plan is
/// never overwritten; a changed file is written only if it still holds what
/// the plan read. The new `brrrty.config.rhai` goes first.
pub fn apply(plan: &Plan) -> io::Result<()> {
    for c in &plan.changes {
        if let Some(old) = &c.old {
            let now = fs::read(&c.path)?;
            if now != old.as_bytes() {
                return Err(io::Error::other(format!(
                    "{} changed while Brrrty was working, so it wasn't overwritten",
                    c.name
                )));
            }
        }
        write_atomic(&c.path, &c.new, c.old.is_none()).map_err(|e| {
            if e.kind() == io::ErrorKind::AlreadyExists {
                io::Error::new(
                    e.kind(),
                    format!(
                        "{} appeared while Brrrty was working, so it wasn't overwritten",
                        c.name
                    ),
                )
            } else {
                e
            }
        })?;
    }
    Ok(())
}

/// Write `path` through a temporary file. With `new`, fails rather than
/// replace a file already there. Replacing breaks a hard link to the old file.
fn write_atomic(path: &Path, text: &str, new: bool) -> io::Result<()> {
    let dir = path.parent().unwrap_or(Path::new("."));
    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file");
    let tmp = dir.join(format!(".{name}.brrrty-{}.tmp", std::process::id()));
    let result = (|| {
        let mut f = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp)?;
        if let Ok(m) = fs::metadata(path) {
            f.set_permissions(m.permissions())?;
        }
        f.write_all(text.as_bytes())?;
        f.sync_all()?;
        drop(f);
        if new {
            match fs::hard_link(&tmp, path) {
                Ok(()) => fs::remove_file(&tmp),
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Err(e),
                // A file system without hard links: check, then rename.
                Err(_) if fs::symlink_metadata(path).is_ok() => {
                    Err(io::Error::from(io::ErrorKind::AlreadyExists))
                }
                Err(_) => fs::rename(&tmp, path),
            }
        } else {
            fs::rename(&tmp, path)
        }
    })();
    if result.is_err() || new {
        let _ = fs::remove_file(&tmp);
    }
    result
}

/// What's left to do, and the next steps.
pub fn summary(plan: &Plan) -> String {
    let mut out = String::new();
    let mut todo = Vec::new();
    if plan.todos > 0 {
        let source = plan.config.as_deref().unwrap_or("the 11ty config");
        todo.push(format!(
            "{CONFIG_FILE} has {} TODO(brrrty) marker{}: parts of {source} that Brrrty can't port by itself. Each quotes the JavaScript it stands in for. Brrrty builds no pages while one is left: port each one, or decide it changes nothing Brrrty writes, then delete its TODO line. `brrrty doctor` lists them.",
            plan.todos,
            if plan.todos == 1 { "" } else { "s" }
        ));
    }
    if !plan.js_data.is_empty() {
        let mut s =
            format!("JavaScript data files ({GETTING_STARTED}#2-port-javascript-data-files):");
        if !plan.js_translated.is_empty() {
            s.push_str(&format!(
                "\n    Translated to Rhai ({}): delete each .js once `brrrty doctor` says its port is identical.",
                plan.js_translated.len()
            ));
            for (f, port) in &plan.js_translated {
                s.push_str(&format!("\n      {f} -> {port}"));
            }
        }
        if !plan.js_hand.is_empty() {
            s.push_str(&format!(
                "\n    Brrrty helpers could do it ({}): they run in Node for now; port them by hand with these helpers (see PORTING.md) if you like.",
                plan.js_hand.len()
            ));
            for (f, helpers) in &plan.js_hand {
                if helpers.is_empty() {
                    s.push_str(&format!("\n      {f} (plain code)"));
                } else {
                    s.push_str(&format!("\n      {f} ({})", helpers.join("; ")));
                }
            }
        }
        if !plan.js_node.is_empty() {
            s.push_str(&format!(
                "\n    Need Node ({}): `config.set_js_data(\"node\")` runs them in your own Node, as 11ty does.",
                plan.js_node.len()
            ));
            for f in &plan.js_node {
                s.push_str(&format!("\n      {f}"));
            }
        }
        todo.push(s);
    }
    todo.extend(plan.advice.iter().cloned());
    if !todo.is_empty() {
        out.push_str("\nTo do by hand:\n");
        for t in todo {
            out.push_str(&format!("  - {t}\n"));
        }
    }
    out.push_str("\nNext steps:\n  npm install\n  npm run build\n");
    if plan.has_build_11ty {
        out.push_str(&format!(
            "  npm run build:11ty -- --output=_site-11ty\n  diff -r _site-11ty {}\n",
            plan.output
        ));
    } else {
        out.push_str(&format!(
            "  npx @11ty/eleventy --output=_site-11ty\n  diff -r _site-11ty {}\n",
            plan.output
        ));
    }
    out.push_str(&format!(
        "The last two build the site with 11ty and compare. See {GETTING_STARTED}#5-check-the-output-against-11ty\n"
    ));
    out
}

/// Run `brrrty init`; returns the exit status.
pub fn run(opts: &Options) -> u8 {
    let plan = match plan(&opts.dir) {
        Ok(p) => p,
        Err(Refusal::NotEleventy(why)) => {
            crate::say_err!("{why}");
            return 2;
        }
        Err(Refusal::Refused(why)) => {
            crate::say_err!("{why}");
            return 1;
        }
    };
    let from = plan.config.as_deref().unwrap_or("package.json");
    crate::say!(
        "Brrrty found an 11ty site in {} ({from}).\n",
        plan.root.display()
    );
    crate::say!("{}", shown_lines(diff(&plan).trim_end()));
    let write = if opts.dry_run {
        crate::say!("\nDry run: nothing was written.");
        false
    } else if opts.yes {
        true
    } else if !opts.interactive {
        crate::say!(
            "\nNothing was written: there is no terminal to ask in. Run `brrrty init --yes` to make these changes."
        );
        false
    } else {
        print!("\nMake these changes? [y/N] ");
        let _ = io::stdout().flush();
        let mut line = String::new();
        let _ = io::stdin().lock().read_line(&mut line);
        let yes = matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes");
        if !yes {
            crate::say!("Nothing was written.");
            return 0;
        }
        true
    };
    if write {
        if let Err(e) = apply(&plan) {
            crate::say_err!("Brrrty couldn't write the changes: {e}");
            return 1;
        }
        let names: Vec<&str> = plan.changes.iter().map(|c| c.name.as_str()).collect();
        let list = match names.split_last() {
            Some((last, rest)) if !rest.is_empty() => format!("{} and {last}", rest.join(", ")),
            _ => names.join(""),
        };
        crate::say!("\nWrote {list}.");
    }
    crate::say!("{}", shown_lines(summary(&plan).trim_end()));
    0
}

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

    #[test]
    fn spots_scripts_that_are_11ty() {
        for yes in [
            "eleventy",
            "npx @11ty/eleventy --serve --port 8080",
            "npx -y @11ty/eleventy@3.1.2",
            "npx eleventy --input=src",
            "NODE_ENV=production eleventy",
            "cross-env ELEVENTY_ENV=prod eleventy --quiet",
            "./node_modules/.bin/eleventy",
        ] {
            assert!(is_eleventy_command(yes), "{yes}");
        }
        for no in [
            "vite build",
            "npm-run-all build:*",
            "eleventy-dev-server",
            "npm run css && eleventy && npm run pagefind",
            "echo building with eleventy",
            "node --run eleventy",
            "rm -rf _site; eleventy",
            "eleventy > log.txt",
        ] {
            assert!(!is_eleventy_command(no), "{no}");
        }
        assert_eq!(
            eleventy_step("npm run css && eleventy --quiet && npm run pagefind"),
            Some("eleventy --quiet")
        );
        assert_eq!(eleventy_step("echo building with eleventy"), None);
    }

    #[test]
    fn edits_scripts_and_dev_dependencies() {
        let src = "{\n  \"name\": \"site\",\n  \"scripts\": {\n    \"build\": \"eleventy\",\n    \"start\": \"vite\"\n  },\n  \"devDependencies\": {\n    \"@11ty/eleventy\": \"^3.1.2\",\n    \"prettier\": \"3\"\n  }\n}\n";
        let e = edit_package(src).unwrap();
        assert_eq!(
            e.text,
            format!(
                "{{\n  \"name\": \"site\",\n  \"scripts\": {{\n    \"build\": \"brrrty build\",\n    \"build:11ty\": \"eleventy\",\n    \"start\": \"vite\"\n  }},\n  \"devDependencies\": {{\n    \"@11ty/eleventy\": \"^3.1.2\",\n    \"brrrty\": \"{VERSION}\",\n    \"prettier\": \"3\"\n  }}\n}}\n"
            )
        );
        assert!(e.has_build_11ty);
        assert_eq!(e.advice.len(), 1, "{:?}", e.advice);
        assert!(e.advice[0].contains("scripts.start runs \"vite\""));
    }

    #[test]
    fn adds_missing_objects() {
        let src =
            "{\n    \"name\": \"site\",\n    \"dependencies\": { \"@11ty/eleventy\": \"3\" }\n}";
        let e = edit_package(src).unwrap();
        assert_eq!(
            e.text,
            format!(
                "{{\n    \"name\": \"site\",\n    \"dependencies\": {{ \"@11ty/eleventy\": \"3\" }},\n    \"scripts\": {{\n        \"build\": \"brrrty build\",\n        \"start\": \"brrrty serve\"\n    }},\n    \"devDependencies\": {{\n        \"brrrty\": \"{VERSION}\"\n    }}\n}}"
            )
        );
    }

    #[test]
    fn leaves_a_package_already_set_up_alone() {
        let src = format!(
            "{{\"scripts\":{{\"build\":\"brrrty build\",\"start\":\"brrrty serve\"}},\"devDependencies\":{{\"brrrty\":\"{VERSION}\"}}}}"
        );
        let e = edit_package(&src).unwrap();
        assert_eq!(e.text, src);
        assert!(e.advice.is_empty());
    }
}