rustuse-cli 0.2.0-beta.1

Command-line tooling for adopting, managing, and maintaining RustUse crates.
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
//! Guided interactive menu shown when `rustuse` runs without a subcommand.
//!
//! The menu collects command arguments and delegates execution to the
//! corresponding command modules.

use std::io::IsTerminal;
use std::path::PathBuf;

use anyhow::{Result, bail};
use dialoguer::{Confirm, Input, Select, theme::ColorfulTheme};

use crate::output::Output;

use super::NamedCommandArgs;
use super::add::{self, AddArgs, AddMode};
use super::catalog::{
    self, CatalogArgs, CatalogCommand, CatalogGenerateArgs, CatalogInfoArgs, CatalogPathArgs,
    CatalogSearchArgs,
};
use super::check::{self, CheckArgs};
use super::ci::check::{CheckCiArgs, CheckKind};
use super::ci::{self, CiArgs, CiCommand};
use super::dev::{self, DevArgs};
use super::diff::{self, DiffArgs};
use super::docs::{self, DocsArgs};
use super::doctor::{self, DoctorArgs};
use super::ferris::{self, FerrisArgs};
use super::info::{self, InfoArgs};
use super::init::{self, InitArgs};
use super::list::{self, ListArgs};
use super::outdated::{self, OutdatedArgs};
use super::remove::{self, RemoveArgs};
use super::search::{self, SearchArgs};
use super::update::{self, UpdateArgs};
use super::upgrade::{self, UpgradeArgs};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum MenuAction {
    Search,
    Info,
    Add,
    Catalog,
    Check,
    Diff,
    Docs,
    Doctor,
    Init,
    List,
    Outdated,
    Remove,
    Update,
    Upgrade,
    DevelopmentAndCi,
    Ferris,
    Exit,
}

impl MenuAction {
    const ALL: [Self; 17] = [
        Self::Search,
        Self::Info,
        Self::Add,
        Self::Catalog,
        Self::Check,
        Self::Diff,
        Self::Docs,
        Self::Doctor,
        Self::Init,
        Self::List,
        Self::Outdated,
        Self::Remove,
        Self::Update,
        Self::Upgrade,
        Self::DevelopmentAndCi,
        Self::Ferris,
        Self::Exit,
    ];

    const fn label(self) -> &'static str {
        match self {
            Self::Search => "Search RustUse crates",
            Self::Info => "Show crate or primitive info",
            Self::Add => "Add a RustUse crate",
            Self::Catalog => "Manage the RustUse catalog",
            Self::Check => "Check a RustUse repository",
            Self::Diff => "Diff a RustUse repository",
            Self::Docs => "Show RustUse documentation",
            Self::Doctor => "Run doctor checks",
            Self::Init => "Initialize RustUse tracking",
            Self::List => "List RustUse entries",
            Self::Outdated => "Check for outdated RustUse dependencies",
            Self::Remove => "Remove a RustUse dependency",
            Self::Update => "Update RustUse dependencies",
            Self::Upgrade => "Upgrade a RustUse repository",
            Self::DevelopmentAndCi => "Development and CI tools",
            Self::Ferris => "Ask Ferris",
            Self::Exit => "Exit",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CatalogAction {
    Discover,
    Generate,
    Check,
    Info,
    Search,
    Back,
}

impl CatalogAction {
    const ALL: [Self; 6] = [
        Self::Discover,
        Self::Generate,
        Self::Check,
        Self::Info,
        Self::Search,
        Self::Back,
    ];

    const fn label(self) -> &'static str {
        match self {
            Self::Discover => "Discover local catalog entries",
            Self::Generate => "Generate catalog artifacts",
            Self::Check => "Check catalog consistency",
            Self::Info => "Show a catalog entry",
            Self::Search => "Search catalog entries",
            Self::Back => "Back",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DocsKind {
    Website,
    Api,
    Workspace,
}

impl DocsKind {
    const ALL: [Self; 3] = [Self::Website, Self::Api, Self::Workspace];

    const fn label(self) -> &'static str {
        match self {
            Self::Website => "RustUse documentation",
            Self::Api => "API documentation",
            Self::Workspace => "Workspace documentation",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ToolAction {
    Development,
    Ci,
    Back,
}

impl ToolAction {
    const ALL: [Self; 3] = [Self::Development, Self::Ci, Self::Back];

    const fn label(self) -> &'static str {
        match self {
            Self::Development => "RustUse development tools",
            Self::Ci => "Run CI validation",
            Self::Back => "Back",
        }
    }
}

pub(crate) fn run(output: Output, non_interactive: bool, yes: bool) -> Result<()> {
    validate_interactive_mode(
        non_interactive,
        yes,
        output.is_json(),
        std::io::stdin().is_terminal(),
    )?;

    let action = prompt_menu_action()?;
    run_action(action, output)
}

fn validate_interactive_mode(
    non_interactive: bool,
    yes: bool,
    json: bool,
    stdin_is_terminal: bool,
) -> Result<()> {
    if non_interactive {
        bail!("a command is required when running non-interactively; try `rustuse --help`");
    }

    if yes {
        bail!("a command is required when using `--yes`; try `rustuse --help`");
    }

    if json {
        bail!("a command is required when using `--json`; try `rustuse --help`");
    }

    if !stdin_is_terminal {
        bail!("a command is required when running non-interactively; try `rustuse --help`");
    }

    Ok(())
}

fn prompt_menu_action() -> Result<MenuAction> {
    let actions = MenuAction::ALL;
    let labels = actions.map(MenuAction::label);
    let selected = prompt_select("What do you want to do?", &labels, 0)?;

    Ok(actions[selected])
}

fn run_action(action: MenuAction, output: Output) -> Result<()> {
    match action {
        MenuAction::Search => run_search(output),
        MenuAction::Info => run_info(output),
        MenuAction::Add => run_add(output),
        MenuAction::Catalog => run_catalog(output),
        MenuAction::Check => run_check(output),
        MenuAction::Diff => run_diff(output),
        MenuAction::Docs => run_docs(output),
        MenuAction::Doctor => run_doctor(output),
        MenuAction::Init => run_init(output),
        MenuAction::List => run_list(output),
        MenuAction::Outdated => run_outdated(output),
        MenuAction::Remove => run_remove(output),
        MenuAction::Update => run_update(output),
        MenuAction::Upgrade => run_upgrade(output),
        MenuAction::DevelopmentAndCi => run_development_and_ci(output),
        MenuAction::Ferris => ferris::run(FerrisArgs {}, output),
        MenuAction::Exit => Ok(()),
    }
}

fn run_search(output: Output) -> Result<()> {
    search::run(
        SearchArgs {
            query: prompt_text("Search query")?,
            limit: prompt_limit("Maximum results", 20)?,
        },
        output,
    )
}

fn run_info(output: Output) -> Result<()> {
    info::run(
        InfoArgs {
            name: NamedCommandArgs {
                name: prompt_text("Crate or primitive name")?,
            },
        },
        output,
    )
}

fn run_add(output: Output) -> Result<()> {
    add::run(
        AddArgs {
            name: NamedCommandArgs {
                name: prompt_text("Crate name")?,
            },
            mode: AddMode::Cargo,
            dry_run: prompt_confirm("Preview without writing changes?", true)?,
        },
        output,
    )
}

fn run_catalog(output: Output) -> Result<()> {
    let actions = CatalogAction::ALL;
    let labels = actions.map(CatalogAction::label);
    let selected = prompt_select("What catalog task do you want to run?", &labels, 0)?;

    let command = match actions[selected] {
        CatalogAction::Discover => CatalogCommand::Discover(CatalogPathArgs {
            path: prompt_path("RustUse root path", ".")?,
        }),
        CatalogAction::Generate => CatalogCommand::Generate(CatalogGenerateArgs {
            path: prompt_path("RustUse root path", ".")?,
            output: prompt_optional_path(
                "Output file or directory; leave blank to print the generated catalog",
            )?,
        }),
        CatalogAction::Check => CatalogCommand::Check(CatalogPathArgs {
            path: prompt_path("RustUse root path", ".")?,
        }),
        CatalogAction::Info => CatalogCommand::Info(CatalogInfoArgs {
            name: prompt_text("Catalog entry name")?,
        }),
        CatalogAction::Search => CatalogCommand::Search(CatalogSearchArgs {
            query: prompt_text("Catalog search query")?,
            limit: prompt_limit("Maximum results", 20)?,
        }),
        CatalogAction::Back => return Ok(()),
    };

    catalog::run(CatalogArgs { command }, output)
}

fn run_check(output: Output) -> Result<()> {
    check::run(
        CheckArgs {
            path: prompt_path("Repository to check", ".")?,
        },
        output,
    )
}

fn run_diff(output: Output) -> Result<()> {
    diff::run(
        DiffArgs {
            path: prompt_path("Repository to diff", ".")?,
        },
        output,
    )
}

fn run_docs(output: Output) -> Result<()> {
    let kinds = DocsKind::ALL;
    let labels = kinds.map(DocsKind::label);
    let selected = prompt_select("Which documentation do you want?", &labels, 0)?;
    let kind = kinds[selected];

    let name = match kind {
        DocsKind::Website => {
            prompt_optional_text("Crate, primitive, or facade name; leave blank for rustuse.org")?
        },
        DocsKind::Api | DocsKind::Workspace => {
            Some(prompt_text("Crate, primitive, or facade name")?)
        },
    };

    let (api, workspace) = match kind {
        DocsKind::Website => (false, false),
        DocsKind::Api => (true, false),
        DocsKind::Workspace => (false, true),
    };

    docs::run(
        DocsArgs {
            name,
            api,
            workspace,
        },
        output,
    )
}

fn run_doctor(output: Output) -> Result<()> {
    doctor::run(
        DoctorArgs {
            path: prompt_path("Directory to inspect", ".")?,
        },
        output,
    )
}

fn run_init(output: Output) -> Result<()> {
    let path = prompt_path("Directory to initialize", ".")?;
    let cargo_first = prompt_confirm("Prefer Cargo-mode defaults?", true)?;
    let dry_run = prompt_confirm("Preview without writing files?", true)?;
    let force = !dry_run && prompt_confirm("Overwrite an existing rustuse.toml?", false)?;

    init::run(
        InitArgs {
            path,
            cargo_first,
            dry_run,
            force,
        },
        output,
    )
}

fn run_list(output: Output) -> Result<()> {
    list::run(
        ListArgs {
            all: prompt_confirm("Show all catalog entries?", false)?,
            path: prompt_path("Project directory", ".")?,
        },
        output,
    )
}

fn run_outdated(output: Output) -> Result<()> {
    outdated::run(
        OutdatedArgs {
            path: prompt_path("Repository to inspect", ".")?,
        },
        output,
    )
}

fn run_remove(output: Output) -> Result<()> {
    let path = prompt_path("Repository to remove from", ".")?;

    if !prompt_confirm("Continue with removal?", false)? {
        return Ok(());
    }

    remove::run(RemoveArgs { path }, output)
}

fn run_update(output: Output) -> Result<()> {
    update::run(
        UpdateArgs {
            path: prompt_path("Repository to update", ".")?,
        },
        output,
    )
}

fn run_upgrade(output: Output) -> Result<()> {
    upgrade::run(
        UpgradeArgs {
            dry_run: prompt_confirm("Preview the upgrade command?", false)?,
        },
        output,
    )
}

fn run_development_and_ci(output: Output) -> Result<()> {
    let actions = ToolAction::ALL;
    let labels = actions.map(ToolAction::label);
    let selected = prompt_select(
        "Which development or CI workflow do you want to run?",
        &labels,
        0,
    )?;

    match actions[selected] {
        ToolAction::Development => dev::run(DevArgs { command: None }, output, false, false),
        ToolAction::Ci => run_ci(output),
        ToolAction::Back => Ok(()),
    }
}

fn run_ci(output: Output) -> Result<()> {
    ci::run(
        CiArgs {
            command: CiCommand::Check(CheckCiArgs {
                path: prompt_path("Path to validate", ".")?,
                kind: CheckKind::Auto,
                deny_warnings: prompt_confirm("Fail when warnings are found?", false)?,
            }),
        },
        output,
    )
}

fn prompt_text(prompt: &str) -> Result<String> {
    let value = Input::<String>::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .validate_with(|value: &String| {
            if value.trim().is_empty() {
                Err("a value is required")
            } else {
                Ok(())
            }
        })
        .interact_text()?;

    Ok(value.trim().to_owned())
}

fn prompt_optional_text(prompt: &str) -> Result<Option<String>> {
    let value = Input::<String>::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .allow_empty(true)
        .interact_text()?;

    let value = value.trim();

    if value.is_empty() {
        Ok(None)
    } else {
        Ok(Some(value.to_owned()))
    }
}

fn prompt_path(prompt: &str, default: &str) -> Result<PathBuf> {
    let value = Input::<String>::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .default(default.to_owned())
        .interact_text()?;

    Ok(PathBuf::from(value))
}

fn prompt_optional_path(prompt: &str) -> Result<Option<PathBuf>> {
    Ok(prompt_optional_text(prompt)?.map(PathBuf::from))
}

fn prompt_limit(prompt: &str, default: usize) -> Result<usize> {
    let value = Input::<usize>::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .default(default)
        .validate_with(|value: &usize| {
            if *value == 0 {
                Err("the limit must be greater than zero")
            } else {
                Ok(())
            }
        })
        .interact_text()?;

    Ok(value)
}

fn prompt_confirm(prompt: &str, default: bool) -> Result<bool> {
    Ok(Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .default(default)
        .interact()?)
}

fn prompt_select(prompt: &str, items: &[&str], default: usize) -> Result<usize> {
    Ok(Select::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .items(items)
        .default(default)
        .interact()?)
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::{CatalogAction, DocsKind, MenuAction, ToolAction, validate_interactive_mode};

    #[test]
    fn menu_labels_are_non_empty_and_unique() {
        let labels = MenuAction::ALL.map(MenuAction::label);
        assert_labels_are_valid(&labels);
    }

    #[test]
    fn catalog_labels_are_non_empty_and_unique() {
        let labels = CatalogAction::ALL.map(CatalogAction::label);
        assert_labels_are_valid(&labels);
    }

    #[test]
    fn docs_labels_are_non_empty_and_unique() {
        let labels = DocsKind::ALL.map(DocsKind::label);
        assert_labels_are_valid(&labels);
    }

    #[test]
    fn tool_labels_are_non_empty_and_unique() {
        let labels = ToolAction::ALL.map(ToolAction::label);
        assert_labels_are_valid(&labels);
    }

    #[test]
    fn navigation_actions_are_last() {
        assert_eq!(MenuAction::ALL.last().copied(), Some(MenuAction::Exit));
        assert_eq!(
            CatalogAction::ALL.last().copied(),
            Some(CatalogAction::Back)
        );
        assert_eq!(ToolAction::ALL.last().copied(), Some(ToolAction::Back));
    }

    #[test]
    fn interactive_mode_accepts_a_terminal_session() {
        assert!(validate_interactive_mode(false, false, false, true).is_ok());
    }

    #[test]
    fn interactive_mode_rejects_non_interactive_execution() {
        assert!(validate_interactive_mode(true, false, false, true).is_err());
    }

    #[test]
    fn interactive_mode_rejects_yes_without_a_command() {
        assert!(validate_interactive_mode(false, true, false, true).is_err());
    }

    #[test]
    fn interactive_mode_rejects_json_without_a_command() {
        assert!(validate_interactive_mode(false, false, true, true).is_err());
    }

    #[test]
    fn interactive_mode_rejects_non_terminal_input() {
        assert!(validate_interactive_mode(false, false, false, false).is_err());
    }

    fn assert_labels_are_valid(labels: &[&str]) {
        assert!(labels.iter().all(|label| !label.trim().is_empty()));

        let unique: HashSet<_> = labels.iter().copied().collect();
        assert_eq!(unique.len(), labels.len());
    }
}