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
//! The dependency commands: `cuno add`, `remove`, `update`, `tree` and
//! `fetch` (`docs/en/specs/commands.md`, "`cuno add`" to "`cuno fetch`").
//! Each resolves the graph as a build does; `add` and `remove` write
//! `Cuno.toml` only once resolving the changed one has succeeded.

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

use cuno_core::{CunoError, Env, Shell};
use cuno_deps::{Forget, LockMode, LockedSource, Network, ResolveOptions, Resolved};
use cuno_manifest::{
    ConfigError, DependencyKey, DependencySource, GitReference, MANIFEST, ResolvedPackage,
    Settings, WrittenDependency,
};
use cuno_toolchain::HostOs;

use crate::Fetching;
use crate::build::{boxed, in_project};

/// The dependency `cuno add` adds, as its options say.
pub(crate) struct NewDependency {
    /// `--git`.
    pub(crate) git: Option<String>,
    /// `--tag`, `--rev` or `--branch`.
    pub(crate) reference: GitReference,
    /// `--url`.
    pub(crate) url: Option<String>,
    /// `--path`.
    pub(crate) path: Option<PathBuf>,
    /// `--version`.
    pub(crate) version: Option<String>,
}

/// A usage error of `cuno add` that clap does not give (exit code 2):
/// `--tag`, `--rev` or `--branch` without `--git`, which clap's `requires`
/// on the argument group lets through when another source is given; and
/// no source and no name, which clap would report as a missing name.
#[derive(Debug)]
pub(crate) enum AddUsage {
    ReferenceWithoutGit,
    NothingToAdd,
}

impl std::fmt::Display for AddUsage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            AddUsage::ReferenceWithoutGit => {
                "--tag, --rev and --branch can be given only with --git"
            }
            AddUsage::NothingToAdd => "give one of --git, --url and --path",
        })
    }
}

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

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

/// Resolves `package` as `fetching` and `forget` allow, with `prefetched`
/// records used as if the lock held them.
#[allow(clippy::too_many_arguments)]
fn resolve(
    package: ResolvedPackage,
    settings: &Settings,
    fetching: Fetching,
    forget: Forget,
    prefetched: &[(String, LockedSource)],
    env: &Env,
    host: HostOs,
    cwd: &Path,
    shell: &mut Shell,
) -> Result<Resolved, ConfigError> {
    with_resolve_options(
        settings,
        fetching,
        forget,
        prefetched,
        env,
        host,
        cwd,
        |options| cuno_deps::resolve(package, options, shell),
    )
}

/// Runs `body` with the options resolving takes, made from `settings` and
/// the environment as every command makes them.
#[allow(clippy::too_many_arguments)]
pub(crate) fn with_resolve_options<T>(
    settings: &Settings,
    fetching: Fetching,
    forget: Forget,
    prefetched: &[(String, LockedSource)],
    env: &Env,
    host: HostOs,
    cwd: &Path,
    body: impl FnOnce(&ResolveOptions<'_>) -> T,
) -> T {
    let runner = cuno_toolchain::SystemRunner::with_limit(cuno_deps::GIT_TIMEOUT);
    let curl = cuno_fetch::Curl::find(env).map(cuno_fetch::Curl::allowing_files);
    let options = ResolveOptions {
        case: host.name_case(),
        os: cuno_build::target_os(host),
        cwd,
        home: &settings.home,
        env,
        runner: &runner,
        downloader: curl
            .as_ref()
            .map(|c| c as &dyn cuno_fetch::Fetch)
            .map_err(ToString::to_string),
        network: fetching.network,
        lock: fetching.lock,
        forget,
        prefetched,
    };
    body(&options)
}

/// The project `settings` were read in, with its `Cuno.toml`'s path.
fn project(settings: &Settings) -> (&ResolvedPackage, PathBuf) {
    let package = settings
        .project
        .as_ref()
        .expect("in_project found the project the settings were read from");
    let file = package.root().join(MANIFEST);
    (package, file)
}

/// Reads the `Cuno.toml` at `file`.
fn read(file: &Path) -> Result<String, ConfigError> {
    std::fs::read_to_string(file).map_err(|e| ConfigError {
        message: format!("cannot read {}: {e}", file.display()),
        location: None,
        help: None,
    })
}

/// Writes `text` as the `Cuno.toml` at `file`, beside it first and renamed
/// into place, so that a failed write leaves the old one.
fn write(file: &Path, text: &str) -> Result<(), ConfigError> {
    let failed = |e: std::io::Error| ConfigError {
        message: format!("cannot write {}: {e}", file.display()),
        location: None,
        help: None,
    };
    let mut beside = file.as_os_str().to_owned();
    beside.push(".tmp");
    let beside = PathBuf::from(beside);
    std::fs::write(&beside, text).map_err(failed)?;
    std::fs::rename(&beside, file).map_err(|e| {
        let _ = std::fs::remove_file(&beside);
        failed(e)
    })
}

/// `Cuno.lock` as `resolved` decided it, once `Cuno.toml` is written: only
/// when it changed.
fn write_lock(
    package: &ResolvedPackage,
    resolved: &Resolved,
    cwd: &Path,
) -> Result<(), Box<dyn CunoError>> {
    if resolved.changes.is_empty() {
        return Ok(());
    }
    cuno_deps::write_lockfile(package.root(), &resolved.lock, cwd).map_err(boxed)
}

/// An error about the changed `Cuno.toml`, which is not on disk: without a
/// place in it, which would name a line the user's file does not have.
fn unlocated(error: ConfigError) -> Box<dyn CunoError> {
    boxed(ConfigError {
        location: None,
        ..error
    })
}

/// The root package as `text`, a changed `Cuno.toml`, says it is.
fn reread(
    package: &ResolvedPackage,
    file: &Path,
    text: &str,
    cwd: &Path,
) -> Result<ResolvedPackage, ConfigError> {
    let shown = cuno_manifest::shown_path(file, cwd);
    let manifest = cuno_manifest::parse_manifest(text, &shown, package.root())?.value;
    Ok(ResolvedPackage::new(package.root(), manifest))
}

/// Prints what changed in `Cuno.lock`, then what resolving warns about.
fn print_resolved(resolved: &Resolved, warnings: bool, shell: &mut Shell) {
    for (verb, text) in &resolved.changes {
        shell.status(verb, text);
    }
    if warnings {
        for warning in &resolved.warnings {
            shell.warning(warning);
        }
    }
}

/// `cuno add`: fetches the source `added` names to learn its package,
/// writes it into `[dependencies]` under that name, and resolves; nothing
/// is written unless all of it succeeds.
#[allow(clippy::too_many_arguments)]
pub(crate) fn add(
    name: Option<String>,
    added: NewDependency,
    offline: bool,
    settings: Result<Settings, ConfigError>,
    env: &Env,
    host: HostOs,
    cwd: &Path,
    shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
    if added.git.is_none() && added.reference != GitReference::DefaultBranch {
        return Err(Box::new(AddUsage::ReferenceWithoutGit));
    }
    if name.is_none() && added.git.is_none() && added.url.is_none() && added.path.is_none() {
        return Err(Box::new(AddUsage::NothingToAdd));
    }
    let settings = in_project(settings, cwd)?;
    let (package, file) = project(&settings);
    // The checks `Cuno.toml`'s `[dependencies]` gets, before anything is
    // fetched, each value by its key and named by its option
    // (`docs/en/specs/commands.md`, "`cuno add`"). The manifest's parser
    // lists `Cuno.toml`'s values the same way.
    let reference = match &added.reference {
        GitReference::Tag(tag) => Some((DependencyKey::Tag, "--tag", tag.as_str())),
        GitReference::Rev(rev) => Some((DependencyKey::Rev, "--rev", rev.as_str())),
        GitReference::Branch(branch) => Some((DependencyKey::Branch, "--branch", branch.as_str())),
        GitReference::DefaultBranch => None,
    };
    let given = [
        added
            .git
            .as_deref()
            .map(|v| (DependencyKey::Git, "--git", v)),
        reference,
        added
            .url
            .as_deref()
            .map(|v| (DependencyKey::Url, "--url", v)),
    ];
    for (key, option, value) in given.into_iter().flatten() {
        if let Some(refusal) = cuno_manifest::dependency_value_refusal(key, value) {
            return Err(boxed(ConfigError {
                message: format!("{option} {}", refusal.said_of(value)),
                location: None,
                help: None,
            }));
        }
    }
    if let Some(text) = &added.version
        && let Err(e) = cuno_manifest::version_requirement(text)
    {
        return Err(boxed(ConfigError {
            message: format!("--version \"{text}\" is not a version requirement: {e}"),
            location: None,
            help: None,
        }));
    }
    let path = match &added.path {
        Some(path) => {
            Some(crate::argument_path(path, cwd).map_err(|e| Box::new(e) as Box<dyn CunoError>)?)
        }
        None => None,
    };
    let (source, mut keys) = match (added.git, added.url, path) {
        (Some(url), None, None) => {
            let mut keys = vec![("git", url.clone())];
            keys.extend(
                added
                    .reference
                    .written()
                    .map(|(key, value)| (key, value.to_owned())),
            );
            let source = DependencySource::Git {
                url,
                reference: added.reference,
            };
            (source, keys)
        }
        (None, Some(url), None) => (
            DependencySource::Url { url: url.clone() },
            vec![("url", url)],
        ),
        (None, None, Some(path)) => {
            let path = cuno_core::paths::lexical(&path);
            let written = cuno_deps::relative_path(&path, package.root(), host.name_case());
            (DependencySource::Path(path), vec![("path", written)])
        }
        // A name alone, which clap lets through: what stage 2's index will
        // take.
        _ => {
            return Err(boxed(ConfigError {
                message: format!(
                    "adding `{}` by its name alone is not available yet",
                    name.unwrap_or_default()
                ),
                location: None,
                help: Some("give --git, --url or --path".to_owned()),
            }));
        }
    };
    if let Some(version) = added.version {
        keys.push(("version", version));
    }
    let fetching = Fetching {
        network: if offline {
            Network::Offline
        } else {
            Network::Online
        },
        lock: LockMode::Write,
    };
    let identified = with_resolve_options(
        &settings,
        fetching,
        Forget::Nothing,
        &[],
        env,
        host,
        cwd,
        |options| cuno_deps::identify(&source, package.root(), options, shell),
    )
    .map_err(boxed)?;
    let text = read(&file).map_err(boxed)?;
    let shown = cuno_manifest::shown_path(&file, cwd);
    let (changed, existed) =
        cuno_manifest::set_dependency(&text, &shown, &identified.name, &WrittenDependency { keys })
            .map_err(boxed)?;
    let root = reread(package, &file, &changed, cwd).map_err(unlocated)?;
    let prefetched: Vec<(String, LockedSource)> = identified
        .record
        .iter()
        .map(|r| (identified.name.clone(), r.clone()))
        .collect();
    let deferred = Fetching {
        lock: LockMode::Deferred,
        ..fetching
    };
    let resolved = resolve(
        root,
        &settings,
        deferred,
        Forget::Nothing,
        &prefetched,
        env,
        host,
        cwd,
        shell,
    )
    .map_err(unlocated)?;
    write(&file, &changed).map_err(boxed)?;
    write_lock(package, &resolved, cwd)?;
    if existed {
        shell.status("Replacing", format!("{} in Cuno.toml", identified.name));
    } else {
        let source = resolved
            .lock
            .get(&identified.name)
            .map(|p| cuno_deps::shown_source(&p.source))
            .unwrap_or_default();
        shell.status(
            "Adding",
            format!("{} v{} ({source})", identified.name, identified.version),
        );
    }
    print_resolved(&resolved, true, shell);
    Ok(0)
}

/// `cuno remove`: removes `names` from `[dependencies]` and resolves; any
/// name not there removes none.
pub(crate) fn remove(
    names: &[String],
    offline: bool,
    settings: Result<Settings, ConfigError>,
    env: &Env,
    host: HostOs,
    cwd: &Path,
    shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
    let settings = in_project(settings, cwd)?;
    let (package, file) = project(&settings);
    // Each name once, in the order given.
    let mut names = names.to_vec();
    let mut seen = std::collections::BTreeSet::new();
    names.retain(|n| seen.insert(n.clone()));
    let text = read(&file).map_err(boxed)?;
    let shown = cuno_manifest::shown_path(&file, cwd);
    let changed = cuno_manifest::remove_dependencies(&text, &shown, &names).map_err(boxed)?;
    let root = reread(package, &file, &changed, cwd).map_err(unlocated)?;
    let fetching = Fetching {
        network: if offline {
            Network::Offline
        } else {
            Network::Online
        },
        lock: LockMode::Deferred,
    };
    let resolved = resolve(
        root,
        &settings,
        fetching,
        Forget::Nothing,
        &[],
        env,
        host,
        cwd,
        shell,
    )
    .map_err(unlocated)?;
    write(&file, &changed).map_err(boxed)?;
    write_lock(package, &resolved, cwd)?;
    for name in &names {
        shell.status("Removing", format!("{name} from Cuno.toml"));
    }
    print_resolved(&resolved, true, shell);
    Ok(0)
}

/// `cuno update [name]`: resolves without the records of every dependency,
/// or of `name` and what is reached through it, and rewrites `Cuno.lock`.
pub(crate) fn update(
    name: Option<String>,
    settings: Result<Settings, ConfigError>,
    env: &Env,
    host: HostOs,
    cwd: &Path,
    shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
    let settings = in_project(settings, cwd)?;
    let (package, file) = project(&settings);
    let forget = match name {
        None => Forget::Everything,
        Some(name) if package.manifest.dependencies.contains_key(&name) => Forget::Below(name),
        Some(name) => {
            return Err(boxed(ConfigError {
                message: format!(
                    "`{name}` is not a dependency in {}",
                    cuno_manifest::shown_path(&file, cwd).display()
                ),
                location: None,
                help: Some("cuno tree shows the dependencies".to_owned()),
            }));
        }
    };
    let resolved = resolve(
        package.clone(),
        &settings,
        Fetching::default(),
        forget,
        &[],
        env,
        host,
        cwd,
        shell,
    )
    .map_err(boxed)?;
    print_resolved(&resolved, true, shell);
    Ok(0)
}

/// `cuno fetch`: resolves, fetching what is missing, and writes
/// `Cuno.lock`; prints only the fetching and `Cuno.lock` lines.
pub(crate) fn fetch(
    fetching: Fetching,
    settings: Result<Settings, ConfigError>,
    env: &Env,
    host: HostOs,
    cwd: &Path,
    shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
    let settings = in_project(settings, cwd)?;
    let (package, _) = project(&settings);
    let resolved = resolve(
        package.clone(),
        &settings,
        fetching,
        Forget::Nothing,
        &[],
        env,
        host,
        cwd,
        shell,
    )
    .map_err(boxed)?;
    print_resolved(&resolved, false, shell);
    Ok(0)
}

/// `cuno tree`: resolves as a build does, then writes the graph to `out`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn tree(
    fetching: Fetching,
    settings: Result<Settings, ConfigError>,
    env: &Env,
    host: HostOs,
    cwd: &Path,
    out: &mut dyn Write,
    shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
    let settings = in_project(settings, cwd)?;
    let (package, _) = project(&settings);
    let resolved = resolve(
        package.clone(),
        &settings,
        fetching,
        Forget::Nothing,
        &[],
        env,
        host,
        cwd,
        shell,
    )
    .map_err(boxed)?;
    print_resolved(&resolved, true, shell);
    // A tree nobody reads (a closed pipe) is no failure of cuno's.
    let _ = out.write_all(render_tree(&resolved).as_bytes());
    let _ = out.flush();
    Ok(0)
}

/// The graph of `resolved` as `cuno tree` prints it: the root, then each
/// package under the one that depends on it, children in name order; a
/// package shown before is marked `(*)`, and what lies below it left out.
fn render_tree(resolved: &Resolved) -> String {
    fn line(package: &ResolvedPackage, resolved: &Resolved) -> String {
        let name = &package.manifest.package.name;
        let source = resolved
            .lock
            .get(name)
            .map(|p| cuno_deps::shown_source(&p.source))
            .unwrap_or_default();
        format!("{name} v{} ({source})", package.manifest.package.version)
    }
    fn below(
        package: &ResolvedPackage,
        resolved: &Resolved,
        indent: &str,
        seen: &mut std::collections::BTreeSet<String>,
        out: &mut String,
    ) {
        let count = package.dependencies.len();
        for (i, child) in package.dependencies.iter().enumerate() {
            let last = i + 1 == count;
            let (branch, next) = if last {
                ("└── ", "    ")
            } else {
                ("├── ", "│   ")
            };
            let name = child.manifest.package.name.clone();
            if seen.insert(name) {
                out.push_str(&format!("{indent}{branch}{}\n", line(child, resolved)));
                below(child, resolved, &format!("{indent}{next}"), seen, out);
            } else {
                out.push_str(&format!("{indent}{branch}{} (*)\n", line(child, resolved)));
            }
        }
    }
    let root = &resolved.root;
    let mut out = format!(
        "{} v{}\n",
        root.manifest.package.name, root.manifest.package.version
    );
    below(
        root,
        resolved,
        "",
        &mut std::collections::BTreeSet::new(),
        &mut out,
    );
    out
}