cuno-cli 0.3.0

Everything C/C++ development needs, in one tool.
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
//! `cuno new` and `cuno init`: a package ready to build, test and run, in
//! a new directory or an existing one (`docs/en/specs/commands.md`, "`cuno
//! new <path>`" and "`cuno init [path]`").

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

use cuno_core::{CunoError, ExitClass, Shell};
use cuno_manifest::valid_package_name;
use cuno_toolchain::flags::{Edition, Lang};

/// The options of `cuno new`.
#[derive(Debug)]
pub struct NewArgs {
    /// Where to make the package, as given: relative to the current
    /// directory, or absolute.
    pub path: PathBuf,
    /// `--lang`; C++ when neither it nor `--edition` is given.
    pub lang: Option<Lang>,
    /// `--edition`; the language's default when not given.
    pub edition: Option<Edition>,
    /// `--name`; the directory's name when not given.
    pub name: Option<String>,
    /// `--vcs`; Git by default.
    pub vcs: Vcs,
    /// `--lib`: a library package.
    pub lib: bool,
}

/// `--vcs`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Vcs {
    /// A Git repository with a `.gitignore`.
    Git,
    /// No version control.
    None,
}

/// What stops `cuno new`. Every one is exit code 2 but a file that cannot
/// be written, which is the setup's (`commands.md`, "`cuno new <path>`").
#[derive(Debug)]
pub enum NewError {
    /// A name Windows keeps for devices (`con`, `nul`, ...).
    ReservedName {
        /// The name.
        name: String,
    },
    /// A name the code `--lib` writes cannot carry.
    NotALibraryName {
        /// The name.
        name: String,
        /// Why, as the message ends.
        why: &'static str,
    },
    /// A package name the rule does not allow.
    InvalidName {
        /// The name.
        name: String,
        /// Whether it came from the directory's name rather than `--name`.
        from_directory: bool,
    },
    /// A path that depends on the current drive on Windows (`/x`, `C:x`),
    /// refused as every path argument is (`commands.md`, "`cuno new
    /// <path>`").
    DriveRelative(crate::DriveRelativePath),
    /// The destination is already there.
    Exists {
        /// The destination as the user gave it, which the message shows.
        path: PathBuf,
    },
    /// `--edition` is not a standard of `--lang`.
    EditionMismatch {
        /// The edition.
        edition: Edition,
        /// The language.
        lang: Lang,
    },
    /// A file or directory that could not be made.
    Write {
        /// The file or directory, in full.
        path: PathBuf,
        /// Why.
        reason: String,
    },
}

/// The language's name as messages write it (`C++`), where the manifest
/// writes `c++`.
fn lang_name(lang: Lang) -> &'static str {
    match lang {
        Lang::C => "C",
        Lang::Cxx => "C++",
    }
}

impl fmt::Display for NewError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NewError::InvalidName { name, .. } => {
                write!(f, "`{name}` is not a valid package name")
            }
            NewError::ReservedName { name } => {
                write!(f, "`{name}` is a reserved name on Windows")
            }
            NewError::NotALibraryName { name, why } => {
                write!(f, "`{name}` cannot name a library: {why}")
            }
            NewError::DriveRelative(error) => error.fmt(f),
            NewError::Exists { path } => write!(f, "`{}` already exists", path.display()),
            NewError::EditionMismatch { edition, lang } => write!(
                f,
                "`{}` is not a standard of {}",
                edition.as_str(),
                lang_name(*lang)
            ),
            NewError::Write { path, reason } => {
                write!(f, "cannot write {}: {reason}", path.display())
            }
        }
    }
}

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

impl CunoError for NewError {
    fn exit_class(&self) -> ExitClass {
        match self {
            NewError::InvalidName { .. }
            | NewError::ReservedName { .. }
            | NewError::NotALibraryName { .. }
            | NewError::Exists { .. }
            | NewError::EditionMismatch { .. } => ExitClass::Usage,
            NewError::DriveRelative(error) => error.exit_class(),
            NewError::Write { .. } => ExitClass::Setup,
        }
    }

    fn help(&self) -> Option<String> {
        match self {
            NewError::InvalidName { from_directory, .. } => {
                let rule =
                    "a package name starts with a letter and has only letters, digits, - and _";
                Some(if *from_directory {
                    format!("{rule}\nhelp: name the package with --name")
                } else {
                    rule.to_owned()
                })
            }
            NewError::EditionMismatch { edition, lang } => {
                let editions: Vec<&str> = Edition::ALL
                    .iter()
                    .filter(|(e, _)| e.lang() == *lang)
                    .map(|(_, text)| *text)
                    .collect();
                Some(format!(
                    "use --lang {}, or an edition of {}: {}",
                    edition.lang().as_str(),
                    lang_name(*lang),
                    editions.join(", ")
                ))
            }
            NewError::ReservedName { .. } => Some("choose another name".to_owned()),
            NewError::NotALibraryName { .. } => Some("name the package with --name".to_owned()),
            NewError::DriveRelative(error) => error.help(),
            NewError::Exists { .. } | NewError::Write { .. } => None,
        }
    }
}

/// Whether `name` is one Windows keeps for devices, in any case, which
/// cannot name a file or directory there (`commands.md`, "`cuno new
/// <path>`").
pub fn reserved_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    let numbered = |prefix: &str| {
        lower
            .strip_prefix(prefix)
            .is_some_and(|n| n.len() == 1 && n.as_bytes()[0].is_ascii_digit() && n != "0")
    };
    ["con", "prn", "aux", "nul"].contains(&lower.as_str()) || numbered("com") || numbered("lpt")
}

/// Why `name` cannot name a library package, if it cannot: the code `--lib`
/// writes uses it as a C++ namespace, a C prefix and a file name, so it must
/// not be a keyword of C or C++, the standard library's namespace, a macro
/// cuno or the standard library defines, cuno's own, `main`, which would
/// make the source an entry file, or give an identifier C and C++ reserve (`commands.md`, "Files generated with
/// `--lib`").
pub fn not_a_library_name(name: &str) -> Option<&'static str> {
    // C23 and C++23, the alternative operator names included.
    const KEYWORDS: &[&str] = &[
        "alignas",
        "alignof",
        "and",
        "and_eq",
        "asm",
        "auto",
        "bitand",
        "bitor",
        "bool",
        "break",
        "case",
        "catch",
        "char",
        "char8_t",
        "char16_t",
        "char32_t",
        "class",
        "compl",
        "concept",
        "const",
        "consteval",
        "constexpr",
        "constinit",
        "const_cast",
        "continue",
        "co_await",
        "co_return",
        "co_yield",
        "decltype",
        "default",
        "delete",
        "do",
        "double",
        "dynamic_cast",
        "else",
        "enum",
        "explicit",
        "export",
        "extern",
        "false",
        "float",
        "for",
        "friend",
        "goto",
        "if",
        "inline",
        "int",
        "long",
        "mutable",
        "namespace",
        "new",
        "noexcept",
        "not",
        "not_eq",
        "nullptr",
        "operator",
        "or",
        "or_eq",
        "private",
        "protected",
        "public",
        "register",
        "reinterpret_cast",
        "requires",
        "restrict",
        "return",
        "short",
        "signed",
        "sizeof",
        "static",
        "static_assert",
        "static_cast",
        "struct",
        "switch",
        "template",
        "this",
        "thread_local",
        "throw",
        "true",
        "try",
        "typedef",
        "typeid",
        "typename",
        "typeof",
        "typeof_unqual",
        "union",
        "unsigned",
        "using",
        "virtual",
        "void",
        "volatile",
        "wchar_t",
        "while",
        "xor",
        "xor_eq",
    ];
    // What a source sees defined: cuno's, and the standard headers' that
    // the samples and the test runtime include.
    const MACROS: &[&str] = &[
        "NDEBUG", "assert", "errno", "NULL", "EOF", "stdin", "stdout", "stderr", "offsetof",
        "setjmp", "va_arg", "va_copy", "va_end", "va_start",
    ];
    let lower = name.to_ascii_lowercase();
    if KEYWORDS.contains(&name) {
        Some("it is a keyword of C or C++")
    } else if name == "std" {
        Some("it is the C++ standard library's namespace")
    } else if MACROS.contains(&name) {
        Some("it is a macro the standard library or cuno defines")
    } else if lower == "cuno" || lower.starts_with("cuno_") || lower.starts_with("cuno-") {
        Some("names beginning with cuno are cuno's own")
    } else if lower == "main" {
        Some("src/main.* would be the program's entry file, not the library")
    } else if name.replace('-', "_").contains("__") || name.ends_with(['_', '-']) {
        Some("its identifier would be one C and C++ reserve")
    } else {
        None
    }
}

/// The language and the edition: `--lang` (C++ by default) and its default
/// edition, or the edition given, whose language `--lang` must be when it
/// is given too.
pub fn resolve(lang: Option<Lang>, edition: Option<Edition>) -> Result<(Lang, Edition), NewError> {
    match (lang, edition) {
        (Some(lang), Some(edition)) if edition.lang() != lang => {
            Err(NewError::EditionMismatch { edition, lang })
        }
        (_, Some(edition)) => Ok((edition.lang(), edition)),
        (lang, None) => {
            let lang = lang.unwrap_or(Lang::Cxx);
            Ok((lang, lang.default_edition()))
        }
    }
}

/// Whether `dir` lies in a Git repository: a `.git` in it or above it.
pub fn inside_repository(dir: &Path) -> bool {
    dir.ancestors().any(|d| d.join(".git").exists())
}

/// The files of a new package named `name` in `lang` and `edition`, by
/// their path in the package (`commands.md`, "Generated files"), or of a
/// library package with `lib` ("Files generated with `--lib`"). `edition`
/// is one of `lang`'s, as [`resolve`] gives them. The sample's tests
/// use the entry its standard selects (`testing.md`, "Writing tests: two
/// entry points").
pub fn files(name: &str, lang: Lang, edition: Edition, lib: bool) -> Vec<(String, String)> {
    let mut manifest = format!(
        "[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nlang = \"{}\"\nedition = \"{}\"\n",
        lang.as_str(),
        edition.as_str()
    );
    if lib {
        manifest.push_str("\n[lib]\nkind = \"static\"\n");
    }
    debug_assert_eq!(edition.lang(), lang, "an edition of another language");
    let mut files = vec![(cuno_manifest::MANIFEST.to_owned(), manifest)];
    let ext = match lang {
        Lang::Cxx => "cpp",
        Lang::C => "c",
    };
    if lib {
        files.extend(library_files(name, edition, ext));
        return files;
    }
    // Every edition named, so a new one has to choose its samples: the
    // modern test API needs C++20, `std::println` C++23.
    let (calc, main, header) = match edition {
        Edition::Cxx17 => (
            include_str!("../templates/cxx/calc17.cpp"),
            include_str!("../templates/cxx/main.cpp"),
            include_str!("../templates/cxx/calc.h"),
        ),
        Edition::Cxx20 => (
            include_str!("../templates/cxx/calc.cpp"),
            include_str!("../templates/cxx/main.cpp"),
            include_str!("../templates/cxx/calc.h"),
        ),
        Edition::Cxx23 => (
            include_str!("../templates/cxx/calc.cpp"),
            include_str!("../templates/cxx/main23.cpp"),
            include_str!("../templates/cxx/calc.h"),
        ),
        Edition::C11 | Edition::C17 | Edition::C23 => (
            include_str!("../templates/c/calc.c"),
            include_str!("../templates/c/main.c"),
            include_str!("../templates/c/calc.h"),
        ),
    };
    files.push((lang.default_entry().to_owned(), main.into()));
    files.push(("src/calc.h".to_owned(), header.into()));
    files.push((format!("src/calc.{ext}"), calc.into()));
    files
}

/// The files `--lib` writes besides the manifest, as the language writes a
/// library (`commands.md`, "Files generated with `--lib`"): a public header
/// under `include/<name>/`, its source and an integration test, both reading
/// it as `<name>/<name>.h` as a dependent would. C++ puts `add` in a
/// namespace named after the package; C declares it `extern "C"`, so a C++
/// package can link it.
fn library_files(name: &str, edition: Edition, ext: &str) -> Vec<(String, String)> {
    let api = cuno_manifest::api_macro(name);
    // For `my-lib`: the identifier `my_lib` (C++'s namespace, C's prefix),
    // and the guard `MY_LIB_MY_LIB_H` of `my-lib/my-lib.h`.
    let ident = name.replace('-', "_");
    let upper = ident.to_ascii_uppercase();
    let guard = format!("{upper}_{upper}_H");
    let fill = |template: &str| {
        template
            .replace("@name@", name)
            .replace("@ident@", &ident)
            .replace("@API@", &api)
            .replace("@GUARD@", &guard)
    };
    // As in `files`: the modern test API needs C++20.
    let (header, source, tests) = match edition {
        Edition::Cxx17 => (
            include_str!("../templates/cxx/lib/lib.h.in"),
            include_str!("../templates/cxx/lib/lib17.cpp.in"),
            include_str!("../templates/cxx/lib/tests17.cpp.in"),
        ),
        Edition::Cxx20 | Edition::Cxx23 => (
            include_str!("../templates/cxx/lib/lib.h.in"),
            include_str!("../templates/cxx/lib/lib.cpp.in"),
            include_str!("../templates/cxx/lib/tests.cpp.in"),
        ),
        Edition::C11 | Edition::C17 | Edition::C23 => (
            include_str!("../templates/c/lib/lib.h.in"),
            include_str!("../templates/c/lib/lib.c.in"),
            include_str!("../templates/c/lib/tests.c.in"),
        ),
    };
    vec![
        (format!("include/{name}/{name}.h"), fill(header)),
        (format!("src/{name}.{ext}"), fill(source)),
        (format!("tests/{name}.{ext}"), fill(tests)),
    ]
}

/// The `.gitignore` of a package under Git.
const GITIGNORE: &str = include_str!("../templates/gitignore");

/// Makes the package `args` describe, `args.path` taken from `cwd`. Every
/// refusal comes before anything is written; a file that cannot be written
/// half way stops it there, leaving what was made for the user to see.
pub fn new(args: NewArgs, cwd: &Path, shell: &mut Shell) -> Result<(), NewError> {
    // `..` resolved, so the directories above it are the ones it will be in.
    let dir = cuno_core::paths::lexical(
        &crate::argument_path(&args.path, cwd).map_err(NewError::DriveRelative)?,
    );
    let (name, from_directory) = match &args.name {
        Some(name) => (name.clone(), false),
        None => (
            dir.file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default(),
            true,
        ),
    };
    if !valid_package_name(&name) {
        return Err(NewError::InvalidName {
            name,
            from_directory,
        });
    }
    if reserved_name(&name) {
        return Err(NewError::ReservedName { name });
    }
    if args.lib
        && let Some(why) = not_a_library_name(&name)
    {
        return Err(NewError::NotALibraryName { name, why });
    }
    let (lang, edition) = resolve(args.lang, args.edition)?;
    if dir.exists() {
        return Err(NewError::Exists { path: args.path });
    }
    let write = |relative: &str, content: &str| -> Result<(), NewError> {
        let path = dir.join(relative);
        let made = path
            .parent()
            .map_or(Ok(()), std::fs::create_dir_all)
            .and_then(|()| std::fs::write(&path, content));
        made.map_err(|e| NewError::Write {
            path,
            reason: e.to_string(),
        })
    };
    // Looked for before the package's own directory exists, so it never
    // counts as the repository it is in.
    let in_repository = inside_repository(&dir);
    for (relative, content) in files(&name, lang, edition, args.lib) {
        write(&relative, &content)?;
    }
    // `commands.md`, "`cuno new <path>`": a `.gitignore` goes with a
    // repository, the package's own or the one it is in; with no repository (no
    // git, or `git init` failing), neither is made, and a warning says why.
    if args.vcs == Vcs::Git {
        if in_repository {
            // No repository of its own: it is part of the one it is in.
            write(".gitignore", GITIGNORE)?;
        } else {
            match std::process::Command::new("git")
                .args(["init", "--quiet"])
                .current_dir(&dir)
                .output()
            {
                Ok(output) if output.status.success() => write(".gitignore", GITIGNORE)?,
                Ok(output) => {
                    let said = String::from_utf8_lossy(&output.stderr);
                    shell.warning(format!("git init failed: {}", said.trim()));
                }
                Err(_) => {
                    shell.warning("git was not found; the package is not under version control")
                }
            }
        }
    }
    shell.status("Created", format!("`{name}` package"));
    Ok(())
}

/// The options of `cuno init`: those of `cuno new`, the path being an
/// existing directory, the current one by default.
#[derive(Debug)]
pub struct InitArgs {
    /// The directory, as given: relative to the current directory, or
    /// absolute.
    pub path: PathBuf,
    /// `--lang`; from the sources in `src/` when neither it nor `--edition`
    /// is given.
    pub lang: Option<Lang>,
    /// `--edition`; the language's default when not given.
    pub edition: Option<Edition>,
    /// `--name`; the directory's name when not given.
    pub name: Option<String>,
    /// `--vcs`; Git by default.
    pub vcs: Vcs,
    /// `--lib`: a library package.
    pub lib: bool,
}

/// What stops `cuno init`, besides what stops `cuno new`. Every one is exit
/// code 2, and comes before anything is written (`commands.md`, "`cuno init
/// [path]`").
#[derive(Debug)]
pub enum InitError {
    /// Nothing is at the path.
    NoDirectory {
        /// As the user gave it.
        path: PathBuf,
    },
    /// Something other than a directory is at the path.
    NotADirectory {
        /// As the user gave it.
        path: PathBuf,
    },
    /// The directory is a package already.
    AlreadyPackage {
        /// As the user gave it.
        path: PathBuf,
    },
    /// Sources, none of them in `src/`.
    SourcesElsewhere {
        /// The first few, from the directory, with `/`.
        found: Vec<String>,
        /// How many more there are.
        more: usize,
    },
    /// Sources in `src/`, and nothing that becomes an executable.
    NoExecutable,
    /// Something is where a file it would write, or a directory above one,
    /// goes.
    Exists {
        /// From the directory, with `/`.
        path: String,
    },
    /// The `.gitignore` there cannot be added to.
    Gitignore {
        /// Why.
        reason: String,
    },
}

impl fmt::Display for InitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InitError::NoDirectory { path } => write!(f, "`{}` does not exist", path.display()),
            InitError::NotADirectory { path } => {
                write!(f, "`{}` is not a directory", path.display())
            }
            InitError::AlreadyPackage { path } => {
                write!(f, "`{}` already has a Cuno.toml", path.display())
            }
            InitError::SourcesElsewhere { found, more } => {
                write!(f, "sources found outside src/: {}", found.join(", "))?;
                if *more > 0 {
                    write!(f, " and {more} more")?;
                }
                Ok(())
            }
            InitError::NoExecutable => f.write_str("src/ has no executable to build"),
            InitError::Exists { path } => write!(f, "{path} already exists"),
            InitError::Gitignore { reason } => write!(f, "cannot add to .gitignore: {reason}"),
        }
    }
}

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

impl CunoError for InitError {
    fn exit_class(&self) -> ExitClass {
        ExitClass::Usage
    }

    fn help(&self) -> Option<String> {
        let help = match self {
            InitError::NoDirectory { .. } => "use cuno new to create a package in a new directory",
            InitError::NotADirectory { .. } | InitError::AlreadyPackage { .. } => return None,
            InitError::SourcesElsewhere { .. } => {
                "move them under src/, with the program's main in src/main.cpp (or src/main.c)"
            }
            InitError::NoExecutable => {
                "put the program's main in src/main.cpp (or src/main.c), or each program in src/bin/"
            }
            InitError::Exists { .. } => {
                "cuno init writes no file that is there; move it aside, or add Cuno.toml by hand"
            }
            InitError::Gitignore { .. } => "make it a text file in UTF-8, or use --vcs none",
        };
        Some(help.to_owned())
    }
}

/// How many sources a message names before it counts the rest.
const SHOWN_SOURCES: usize = 5;

/// The sources in `dir` outside `src/`, by their path from it with `/`. The
/// package body comes from `src/` alone, so what is here only matters as
/// sources a template must not be written beside; what cuno makes (the
/// top-level `target/`), hidden directories (`.git/`, `.cuno/`), links and
/// other packages (a directory with its own `Cuno.toml`) are not looked in.
/// The top-level `src/` is the build's walk's, so it is left out here; it
/// and `target/` are told as the file system tells names apart (`case`)
/// (`docs/en/specs/commands.md`, "`cuno init [path]`").
fn sources_outside_src(dir: &Path, case: cuno_core::NameCase) -> Vec<String> {
    fn walk(dir: &Path, from: &str, case: cuno_core::NameCase, out: &mut Vec<String>) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        let mut entries: Vec<_> = entries.flatten().collect();
        entries.sort_by_key(|e| e.file_name());
        for entry in entries {
            let name = entry.file_name().to_string_lossy().into_owned();
            let relative = if from.is_empty() {
                name.clone()
            } else {
                format!("{from}/{name}")
            };
            let Ok(kind) = entry.file_type() else {
                continue;
            };
            if kind.is_dir() {
                let skipped = name.starts_with('.')
                    || (from.is_empty() && (case.same(&name, "target") || case.same(&name, "src")))
                    || !matches!(
                        cuno_manifest::manifest_in(&entry.path(), case),
                        cuno_manifest::ManifestIn::None
                    );
                if !skipped {
                    walk(&entry.path(), &relative, case, out);
                }
            } else if kind.is_file() && cuno_build::sources::language(&entry.path()).is_some() {
                out.push(relative);
            }
        }
    }
    let mut all = Vec::new();
    walk(dir, "", case, &mut all);
    all
}

/// What becomes of the `.gitignore` at `path`, decided before anything is
/// written.
enum Gitignore {
    /// None there: cuno's is made.
    Make,
    /// These lines go at its end.
    Add(String),
    /// It has every line already.
    Keep,
}

/// What `.gitignore` at `path` needs: made when there is none, or given the
/// lines of cuno's it lacks, in its own line ending, after its last line;
/// its lines and a byte order mark stay as they are. Why it cannot be added
/// to, otherwise.
fn plan_gitignore(path: &Path) -> Result<Gitignore, String> {
    if cuno_tools::write::absent(path).is_ok() {
        return Ok(Gitignore::Make);
    }
    cuno_tools::write::appendable(path).map_err(|refusal| refusal.to_string())?;
    let held = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
    let text = held.strip_prefix('\u{feff}').unwrap_or(&held);
    let have: Vec<&str> = text.lines().map(str::trim).collect();
    let missing: Vec<&str> = GITIGNORE
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty() && !l.starts_with('#') && !have.contains(l))
        .collect();
    if missing.is_empty() {
        return Ok(Gitignore::Keep);
    }
    let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
    let mut added = String::new();
    if !text.is_empty() && !text.ends_with('\n') {
        added += newline;
    }
    for line in missing {
        added += line;
        added += newline;
    }
    Ok(Gitignore::Add(added))
}

/// Where `relative`, a file `cuno init` writes in `dir`, is blocked: the
/// first of the directories above it that is something other than a
/// directory, or the file itself when anything is there.
fn blocked(dir: &Path, relative: &str) -> Option<String> {
    let parts: Vec<&str> = relative.split('/').collect();
    for end in 1..=parts.len() {
        let prefix = parts[..end].join("/");
        let path = dir.join(&prefix);
        let last = end == parts.len();
        let in_the_way = if last {
            cuno_tools::write::absent(&path).is_err()
        } else {
            // A directory above it may be there, as it is; a link or a file
            // may not.
            std::fs::symlink_metadata(&path).is_ok_and(|m| !m.file_type().is_dir())
        };
        if in_the_way {
            return Some(prefix);
        }
    }
    None
}

/// Makes the existing directory `args` describe into a package, `args.path`
/// taken from `cwd`: `Cuno.toml`, the sample when there are no sources, and
/// the `.gitignore` lines cuno needs. Every refusal comes before anything
/// is written (`docs/en/specs/commands.md`, "`cuno init [path]`").
pub fn init(
    args: InitArgs,
    cwd: &Path,
    host: cuno_toolchain::HostOs,
    shell: &mut Shell,
) -> Result<(), Box<dyn CunoError>> {
    let boxed = |e: InitError| Box::new(e) as Box<dyn CunoError>;
    let dir =
        crate::argument_path(&args.path, cwd).map_err(|e| Box::new(e) as Box<dyn CunoError>)?;
    let dir = cuno_core::paths::lexical(&dir);
    match std::fs::metadata(&dir) {
        Err(_) => return Err(boxed(InitError::NoDirectory { path: args.path })),
        Ok(meta) if !meta.is_dir() => {
            return Err(boxed(InitError::NotADirectory { path: args.path }));
        }
        Ok(_) => {}
    }
    match cuno_manifest::manifest_in(&dir, host.name_case()) {
        cuno_manifest::ManifestIn::Found(_) => {
            return Err(boxed(InitError::AlreadyPackage { path: args.path }));
        }
        cuno_manifest::ManifestIn::WrongCase(file) => {
            return Err(Box::new(cuno_manifest::wrong_case(&file)));
        }
        cuno_manifest::ManifestIn::None => {}
    }
    let (name, from_directory) = match &args.name {
        Some(name) => (name.clone(), false),
        None => (
            dir.file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default(),
            true,
        ),
    };
    if !valid_package_name(&name) {
        return Err(Box::new(NewError::InvalidName {
            name,
            from_directory,
        }));
    }
    if reserved_name(&name) {
        return Err(Box::new(NewError::ReservedName { name }));
    }
    if args.lib
        && let Some(why) = not_a_library_name(&name)
    {
        return Err(Box::new(NewError::NotALibraryName { name, why }));
    }

    // `src/` by the build's own walk, so that init and the build never
    // disagree on what is there, and with its errors: `src/` that is
    // another package, or a directory in it that cannot be read, stops init
    // here, before anything else is judged. The walk reads the manifest only
    // for the package's `path` dependencies, which a manifest not yet
    // written has none of, so `[package]` alone serves; its warnings are
    // the build's to give. The rest of the directory by init's own walk.
    let probe = cuno_manifest::parse_manifest(
        &format!(
            "[package]
name = \"{name}\"
version = \"0.1.0\"
"
        ),
        &dir.join(cuno_manifest::MANIFEST),
        &dir,
    )
    .map_err(|e| Box::new(e) as Box<dyn CunoError>)?
    .value;
    let in_src = cuno_build::sources::sources_in_src(
        &dir,
        &probe,
        &cuno_manifest::OutputDir::default_in(&dir),
        host,
    )
    .map_err(|e| Box::new(e) as Box<dyn CunoError>)?;
    let elsewhere = sources_outside_src(&dir, host.name_case());
    if in_src.is_empty() && !elsewhere.is_empty() {
        return Err(boxed(InitError::SourcesElsewhere {
            more: elsewhere.len().saturating_sub(SHOWN_SOURCES),
            found: elsewhere.into_iter().take(SHOWN_SOURCES).collect(),
        }));
    }
    // The language of the sources there are, when not given: C++ if any is
    // C++, C if all are C, and C++ with none, as for `cuno new`.
    let lang = args.lang.or_else(|| {
        (args.edition.is_none() && !in_src.is_empty()).then(|| {
            let cxx = in_src
                .iter()
                .any(|s| cuno_build::sources::language(Path::new(s)) == Some(Lang::Cxx));
            if cxx { Lang::Cxx } else { Lang::C }
        })
    });
    let (lang, edition) =
        resolve(lang, args.edition).map_err(|e| Box::new(e) as Box<dyn CunoError>)?;
    let mut written = files(&name, lang, edition, args.lib);
    if !in_src.is_empty() {
        // Only the manifest: the sources are the user's. Whether they make
        // an executable is the build's own rule, asked of the manifest to be.
        written.truncate(1);
        let manifest =
            cuno_manifest::parse_manifest(&written[0].1, &dir.join(cuno_manifest::MANIFEST), &dir)
                .map_err(|e| Box::new(e) as Box<dyn CunoError>)?
                .value;
        match cuno_build::sources::classify(
            &dir,
            &manifest,
            &cuno_manifest::OutputDir::default_in(&dir),
            host,
        ) {
            Ok(_) => {}
            Err(cuno_build::BuildError::NoExecutable { .. }) => {
                return Err(boxed(InitError::NoExecutable));
            }
            Err(error) => return Err(Box::new(error)),
        }
    }
    for (relative, _) in &written {
        if let Some(path) = blocked(&dir, relative) {
            return Err(boxed(InitError::Exists { path }));
        }
    }
    let gitignore_path = dir.join(".gitignore");
    let gitignore = match args.vcs {
        Vcs::Git => Some(
            plan_gitignore(&gitignore_path)
                .map_err(|reason| boxed(InitError::Gitignore { reason }))?,
        ),
        Vcs::None => None,
    };

    let failed = |path: PathBuf, e: std::io::Error| {
        Box::new(NewError::Write {
            path,
            reason: e.to_string(),
        }) as Box<dyn CunoError>
    };
    let create = |path: &Path, content: &str| -> std::io::Result<()> {
        use std::io::Write;
        path.parent().map_or(Ok(()), std::fs::create_dir_all)?;
        std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(path)?
            .write_all(content.as_bytes())
    };
    let in_repository = inside_repository(&dir);
    for (relative, content) in &written {
        let path = dir.join(relative);
        create(&path, content).map_err(|e| failed(path, e))?;
    }
    if let Some(gitignore) = gitignore {
        let repository = in_repository || {
            match std::process::Command::new("git")
                .args(["init", "--quiet"])
                .current_dir(&dir)
                .output()
            {
                Ok(output) if output.status.success() => true,
                Ok(output) => {
                    let said = String::from_utf8_lossy(&output.stderr);
                    shell.warning(format!("git init failed: {}", said.trim()));
                    false
                }
                Err(_) => {
                    shell.warning("git was not found; the package is not under version control");
                    false
                }
            }
        };
        if repository {
            let path = gitignore_path;
            let done = match gitignore {
                Gitignore::Make => create(&path, GITIGNORE),
                Gitignore::Add(added) => {
                    use std::io::Write;
                    std::fs::OpenOptions::new()
                        .append(true)
                        .open(&path)
                        .and_then(|mut f| f.write_all(added.as_bytes()))
                }
                Gitignore::Keep => Ok(()),
            };
            done.map_err(|e| failed(path, e))?;
        }
    }
    shell.status("Created", format!("`{name}` package"));
    Ok(())
}

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

    /// The language decides the edition, an edition alone decides the
    /// language, and two that disagree are an error saying what to do.
    ///
    /// Mutation: default to another language or edition, ignore an edition
    /// given alone, or accept a mismatch; this test fails.
    #[test]
    fn language_and_edition_agree() {
        assert_eq!(resolve(None, None).unwrap(), (Lang::Cxx, Edition::Cxx20));
        assert_eq!(
            resolve(Some(Lang::C), None).unwrap(),
            (Lang::C, Edition::C17)
        );
        assert_eq!(
            resolve(None, Some(Edition::C11)).unwrap(),
            (Lang::C, Edition::C11)
        );
        assert_eq!(
            resolve(Some(Lang::Cxx), Some(Edition::Cxx17)).unwrap(),
            (Lang::Cxx, Edition::Cxx17)
        );
        let err = resolve(Some(Lang::Cxx), Some(Edition::C17)).unwrap_err();
        assert_eq!(err.to_string(), "`c17` is not a standard of C++");
        assert_eq!(
            err.help().as_deref(),
            Some("use --lang c, or an edition of C++: c++17, c++20, c++23")
        );
        assert_eq!(err.exit_class(), ExitClass::Usage);
        let c = resolve(Some(Lang::C), Some(Edition::Cxx17)).unwrap_err();
        assert_eq!(c.to_string(), "`c++17` is not a standard of C");
        assert_eq!(
            c.help().as_deref(),
            Some("use --lang c++, or an edition of C: c11, c17, c23")
        );
    }

    /// The manifest names the package, version 0.1.0, its language and
    /// edition, and nothing else; C++17 gets the macro API's sample and
    /// C++20 the modern one.
    ///
    /// Mutation: write anything else into `Cuno.toml`, or give C++17 the
    /// sample that needs C++20; this test fails.
    #[test]
    fn the_files_fit_the_language_and_edition() {
        let cxx = files("app", Lang::Cxx, Edition::Cxx20, false);
        assert_eq!(
            cxx[0],
            (
                "Cuno.toml".to_owned(),
                "[package]\nname = \"app\"\nversion = \"0.1.0\"\nlang = \"c++\"\nedition = \"c++20\"\n"
                    .to_owned()
            )
        );
        let names: Vec<&str> = cxx.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(
            names,
            ["Cuno.toml", "src/main.cpp", "src/calc.h", "src/calc.cpp"]
        );
        assert!(cxx[3].1.contains("<cuno/test.hpp>"));
        let cxx17 = files("app", Lang::Cxx, Edition::Cxx17, false);
        assert!(cxx17[3].1.contains("<cuno/test.h>"));
        // The sample prints as its standard would: `std::cout` with '\n'
        // (never `std::endl`, which flushes each line) before C++23,
        // `std::println` from it.
        for edition in [Edition::Cxx17, Edition::Cxx20] {
            let main = &files("app", Lang::Cxx, edition, false)[1].1;
            assert!(
                main.contains("std::cout << ") && main.contains("<< '\\n';"),
                "{main}"
            );
            assert!(
                !main.contains("std::endl") && !main.contains("println"),
                "{main}"
            );
        }
        let main = &files("app", Lang::Cxx, Edition::Cxx23, false)[1].1;
        assert!(
            main.contains("#include <print>") && main.contains("std::println("),
            "{main}"
        );
        let c = files("app", Lang::C, Edition::C17, false);
        let names: Vec<&str> = c.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(
            names,
            ["Cuno.toml", "src/main.c", "src/calc.h", "src/calc.c"]
        );
    }

    /// A library package is `[lib] kind = "static"`, a public header under
    /// `include/<name>/` declaring with `<NAME>_API`, the sample's source
    /// reading it as `<name>/<name>.h`, and an integration test reading only
    /// that header in the test API its standard selects; no `main` (the file
    /// list holds it). C++ puts `add` in the namespace `my_lib`; C names it
    /// `my_lib_add` and declares it `extern "C"` for a C++ package that uses
    /// it.
    ///
    /// Mutation: leave out `[lib]` in either language, write a `main`, put
    /// the header in `src/`, leave `<NAME>_API` off the declaration, include
    /// the header by another name or not at all, give C++17 the modern test
    /// API, or drop the namespace, the C prefix or `extern "C"`; this test
    /// fails.
    #[test]
    fn a_library_package_has_a_public_header_and_no_main() {
        let cxx = files("my-lib", Lang::Cxx, Edition::Cxx20, true);
        let names: Vec<&str> = cxx.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(
            names,
            [
                "Cuno.toml",
                "include/my-lib/my-lib.h",
                "src/my-lib.cpp",
                "tests/my-lib.cpp"
            ]
        );
        assert!(
            cxx[0].1.ends_with("\n[lib]\nkind = \"static\"\n"),
            "{}",
            cxx[0].1
        );
        assert_eq!(
            cxx[1].1,
            "#pragma once\n\nnamespace my_lib {\n\nMY_LIB_API int add(int a, int b);\n\n} // namespace my_lib\n"
        );
        assert!(cxx[3].1.contains("my_lib::add("), "{}", cxx[3].1);
        for (file, text) in &cxx[2..] {
            assert!(
                text.contains("#include <my-lib/my-lib.h>\n"),
                "{file}: {text}"
            );
            assert!(!text.contains("calc"), "{file}: {text}");
        }
        assert!(cxx[3].1.contains("<cuno/test.hpp>"));
        let cxx17 = files("my-lib", Lang::Cxx, Edition::Cxx17, true);
        assert!(cxx17[2].1.contains("<cuno/test.h>"));
        assert!(cxx17[3].1.contains("<cuno/test.h>"));

        let c = files("my-lib", Lang::C, Edition::C17, true);
        let names: Vec<&str> = c.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(
            names,
            [
                "Cuno.toml",
                "include/my-lib/my-lib.h",
                "src/my-lib.c",
                "tests/my-lib.c"
            ]
        );
        assert_eq!(
            c[1].1,
            "#ifndef MY_LIB_MY_LIB_H\n#define MY_LIB_MY_LIB_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nMY_LIB_API int my_lib_add(int a, int b);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
        );
        assert!(
            c[0].1.ends_with("\n[lib]\nkind = \"static\"\n"),
            "{}",
            c[0].1
        );
        for (file, text) in &c[2..] {
            assert!(
                text.contains("#include <my-lib/my-lib.h>\n"),
                "{file}: {text}"
            );
            assert!(text.contains("my_lib_add("), "{file}: {text}");
        }
    }

    /// A name the code `--lib` writes cannot carry is refused, with why;
    /// any other valid name is not, and without `--lib` none of these is
    /// refused.
    ///
    /// Mutation: drop any of the six rules, compare `main` or the `cuno`
    /// prefix with case, `std` without, or refuse without `--lib`; this
    /// test fails.
    #[test]
    fn a_library_name_must_survive_the_code_it_names() {
        for (name, why) in [
            ("int", "it is a keyword of C or C++"),
            ("class", "it is a keyword of C or C++"),
            ("and_eq", "it is a keyword of C or C++"),
            ("std", "it is the C++ standard library's namespace"),
            (
                "NDEBUG",
                "it is a macro the standard library or cuno defines",
            ),
            (
                "errno",
                "it is a macro the standard library or cuno defines",
            ),
            ("cuno", "names beginning with cuno are cuno's own"),
            ("CUNO_TEST", "names beginning with cuno are cuno's own"),
            ("Cuno-x", "names beginning with cuno are cuno's own"),
            (
                "main",
                "src/main.* would be the program's entry file, not the library",
            ),
            (
                "MAIN",
                "src/main.* would be the program's entry file, not the library",
            ),
            ("a__b", "its identifier would be one C and C++ reserve"),
            ("a-_b", "its identifier would be one C and C++ reserve"),
            ("a_", "its identifier would be one C and C++ reserve"),
            ("a-", "its identifier would be one C and C++ reserve"),
        ] {
            assert_eq!(not_a_library_name(name), Some(why), "{name}");
        }
        for name in [
            "my-lib", "my_lib", "a-b-c", "test", "eq", "mainly", "cunology", "Int", "Std",
        ] {
            assert_eq!(not_a_library_name(name), None, "{name}");
        }

        let dir = tempfile::tempdir().unwrap();
        let env = cuno_core::Env::from_pairs([], cuno_core::NameCase::host());
        let mut shell = Shell::new(Box::new(std::io::sink()), None, &env, false);
        let args = |lib| NewArgs {
            path: PathBuf::from("int"),
            lang: None,
            edition: None,
            name: None,
            vcs: Vcs::None,
            lib,
        };
        let refused = new(args(true), dir.path(), &mut shell).unwrap_err();
        assert_eq!(
            refused.to_string(),
            "`int` cannot name a library: it is a keyword of C or C++"
        );
        assert_eq!(refused.exit_class(), ExitClass::Usage);
        assert_eq!(
            refused.help().as_deref(),
            Some("name the package with --name")
        );
        assert!(!dir.path().join("int").exists(), "written before refusing");
        assert!(new(args(false), dir.path(), &mut shell).is_ok());
    }

    /// Mutation: look only in the directory itself, or not at all; this
    /// test fails.
    #[test]
    fn a_repository_above_counts() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(".git")).unwrap();
        assert!(inside_repository(&dir.path().join("a").join("app")));
    }

    /// Windows' device names are refused in any case; names that only start
    /// like one are not.
    ///
    /// Mutation: compare with case, drop a family, or refuse `com0` or
    /// `console`; this test fails.
    #[test]
    fn device_names_are_reserved() {
        for name in ["con", "PRN", "Aux", "nul", "com1", "COM9", "lpt5"] {
            assert!(reserved_name(name), "{name}");
        }
        for name in ["console", "com0", "com10", "lpt", "nulls", "auxiliary"] {
            assert!(!reserved_name(name), "{name}");
        }
    }

    /// Mutation: change any message, help or exit class; this test fails.
    #[test]
    fn the_errors_read_as_the_spec_says() {
        let named = NewError::InvalidName {
            name: "1app".into(),
            from_directory: false,
        };
        assert_eq!(named.to_string(), "`1app` is not a valid package name");
        assert_eq!(
            named.help().as_deref(),
            Some("a package name starts with a letter and has only letters, digits, - and _")
        );
        let from_dir = NewError::InvalidName {
            name: "my game".into(),
            from_directory: true,
        };
        assert!(
            from_dir
                .help()
                .unwrap()
                .ends_with("\nhelp: name the package with --name")
        );
        let exists = NewError::Exists {
            path: PathBuf::from("app"),
        };
        assert_eq!(exists.to_string(), "`app` already exists");
        for e in [named, from_dir, exists] {
            assert_eq!(e.exit_class(), ExitClass::Usage);
        }
        let reserved = NewError::ReservedName { name: "con".into() };
        assert_eq!(reserved.to_string(), "`con` is a reserved name on Windows");
        assert_eq!(reserved.help().as_deref(), Some("choose another name"));
        assert_eq!(reserved.exit_class(), ExitClass::Usage);
        let write = NewError::Write {
            path: PathBuf::from("x"),
            reason: "denied".into(),
        };
        assert_eq!(write.to_string(), "cannot write x: denied");
        assert_eq!(write.exit_class(), ExitClass::Setup);
    }

    /// Where names differ by case, `cuno init` in a directory holding the
    /// manifest in another case gives the error finding the project gives,
    /// and writes nothing.
    ///
    /// Mutation: take it as no manifest, or as `Cuno.toml`; this test fails.
    #[test]
    fn init_refuses_a_manifest_in_another_case() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("cuno.toml"), "").unwrap();
        let env = cuno_core::Env::from_pairs([], cuno_core::NameCase::host());
        let mut shell = Shell::new(Box::new(std::io::sink()), None, &env, false);
        let args = InitArgs {
            path: PathBuf::from("."),
            lang: None,
            edition: None,
            name: Some("app".to_owned()),
            vcs: Vcs::None,
            lib: false,
        };
        let err = init(args, dir.path(), cuno_toolchain::HostOs::Other, &mut shell).unwrap_err();
        assert!(err.to_string().starts_with("found cuno.toml in "), "{err}");
        let names: Vec<String> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, ["cuno.toml"]);
    }
}