cuno-cli 0.1.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
//! `cuno new`: a new package, ready to build, test and run
//! (`docs/en/specs/commands.md`, "`cuno new <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,
}

/// `--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 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,
    },
    /// 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::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::Exists { .. }
            | NewError::EditionMismatch { .. } => ExitClass::Usage,
            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::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")
}

/// 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"). 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) -> Vec<(&'static str, String)> {
    let manifest = format!(
        "[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nlang = \"{}\"\nedition = \"{}\"\n",
        lang.as_str(),
        edition.as_str()
    );
    let mut files = vec![("cuno.toml", manifest)];
    match lang {
        Lang::Cxx => {
            // Every edition named, so a new one has to choose its sample.
            let calc = match edition {
                Edition::Cxx17 => include_str!("../templates/cxx/calc17.cpp"),
                Edition::Cxx20 | Edition::Cxx23 => include_str!("../templates/cxx/calc.cpp"),
                Edition::C11 | Edition::C17 | Edition::C23 => {
                    unreachable!("a C edition with the C++ language")
                }
            };
            files.push((
                lang.default_entry(),
                include_str!("../templates/cxx/main.cpp").into(),
            ));
            files.push(("src/calc.h", include_str!("../templates/cxx/calc.h").into()));
            files.push(("src/calc.cpp", calc.into()));
        }
        Lang::C => {
            files.push((
                lang.default_entry(),
                include_str!("../templates/c/main.c").into(),
            ));
            files.push(("src/calc.h", include_str!("../templates/c/calc.h").into()));
            files.push(("src/calc.c", include_str!("../templates/c/calc.c").into()));
        }
    }
    files
}

/// 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(&cwd.join(&args.path));
    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 });
    }
    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) {
        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(())
}

#[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);
        assert_eq!(
            cxx[0],
            (
                "cuno.toml",
                "[package]\nname = \"app\"\nversion = \"0.1.0\"\nlang = \"c++\"\nedition = \"c++20\"\n"
                    .to_owned()
            )
        );
        let names: Vec<&str> = cxx.iter().map(|(n, _)| *n).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);
        assert!(cxx17[3].1.contains("<cuno/test.h>"));
        let c = files("app", Lang::C, Edition::C17);
        let names: Vec<&str> = c.iter().map(|(n, _)| *n).collect();
        assert_eq!(
            names,
            ["cuno.toml", "src/main.c", "src/calc.h", "src/calc.c"]
        );
    }

    /// 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);
    }
}