Skip to main content

mk_lib/schema/
use_cargo.rs

1use hashbrown::HashMap;
2use serde::Deserialize;
3
4use crate::utils::resolve_path;
5
6use super::{
7  CommandRunner,
8  LocalRun,
9  Task,
10  TaskArgs,
11};
12
13#[derive(Debug, Deserialize)]
14pub struct UseCargoArgs {
15  /// The working directory to run the command in
16  #[serde(default)]
17  pub work_dir: Option<String>,
18}
19
20#[derive(Debug, Deserialize)]
21#[serde(untagged)]
22pub enum UseCargo {
23  Bool(bool),
24  UseCargo(Box<UseCargoArgs>),
25}
26
27impl UseCargo {
28  pub fn capture(&self) -> anyhow::Result<HashMap<String, Task>> {
29    self.capture_in_dir(std::path::Path::new("."))
30  }
31
32  pub fn capture_in_dir(&self, base_dir: &std::path::Path) -> anyhow::Result<HashMap<String, Task>> {
33    match self {
34      UseCargo::Bool(true) => self.capture_tasks_in_dir(base_dir),
35      UseCargo::UseCargo(args) => args.capture_tasks_in_dir(base_dir),
36      _ => Ok(HashMap::new()),
37    }
38  }
39
40  fn capture_tasks_in_dir(&self, base_dir: &std::path::Path) -> anyhow::Result<HashMap<String, Task>> {
41    UseCargoArgs { work_dir: None }.capture_tasks_in_dir(base_dir)
42  }
43}
44
45impl UseCargoArgs {
46  pub fn capture_tasks(&self) -> anyhow::Result<HashMap<String, Task>> {
47    self.capture_tasks_in_dir(std::path::Path::new("."))
48  }
49
50  pub fn capture_tasks_in_dir(&self, base_dir: &std::path::Path) -> anyhow::Result<HashMap<String, Task>> {
51    let resolved_work_dir = self
52      .work_dir
53      .as_ref()
54      .map(|work_dir| resolve_path(base_dir, work_dir));
55    let cargo_commands = [
56      "add",
57      "bench",
58      "build",
59      "check",
60      "clean",
61      "clippy",
62      "doc",
63      "fix",
64      "fmt",
65      "init",
66      "install",
67      "miri",
68      "new",
69      "publish",
70      "remove",
71      "report",
72      "run",
73      "search",
74      "test",
75      "uninstall",
76      "update",
77    ];
78
79    let hm: HashMap<String, Task> = cargo_commands
80      .iter()
81      .map(|cmd| {
82        let command = format!("cargo {}", cmd);
83        let task = Task::Task(Box::new(TaskArgs {
84          commands: vec![CommandRunner::LocalRun(LocalRun {
85            command,
86            shell: None,
87            test: None,
88            work_dir: resolved_work_dir
89              .as_ref()
90              .map(|work_dir| work_dir.to_string_lossy().into_owned()),
91            interactive: Some(true),
92            ignore_errors: None,
93            save_output_as: None,
94            verbose: None,
95          })],
96          ..Default::default()
97        }));
98        (cmd.to_string(), task)
99      })
100      .collect();
101    Ok(hm)
102  }
103}