cli/descriptor/
cargo_alias.rs

1//! # cargo_alias
2//!
3//! Dynamically creates tasks based on alias information in the cargo config.
4//!
5
6#[cfg(test)]
7#[path = "cargo_alias_test.rs"]
8mod cargo_alias_test;
9
10use crate::error::CargoMakeError;
11use crate::io;
12use crate::types::{InstallCrate, Task};
13use std::collections::HashMap;
14use std::path::Path;
15
16#[derive(Serialize, Deserialize, Debug)]
17#[serde(untagged)]
18enum AliasValue {
19    String(String),
20    List(Vec<String>),
21}
22
23#[derive(Serialize, Deserialize, Debug)]
24struct CargoConfig {
25    alias: Option<HashMap<String, AliasValue>>,
26}
27
28fn load_from_file(file: &str) -> Result<Vec<(String, Task)>, CargoMakeError> {
29    let file_path = Path::new(file);
30
31    let mut tasks = vec![];
32    if file_path.exists() {
33        if file_path.is_file() {
34            let text = io::read_text_file(&file_path.to_path_buf())?;
35
36            if !text.is_empty() {
37                let cargo_config: CargoConfig = match toml::from_str(&text) {
38                    Ok(value) => value,
39                    Err(error) => {
40                        warn!("Unable to parse cargo config file, {}", error);
41                        CargoConfig { alias: None }
42                    }
43                };
44
45                if let Some(aliases) = cargo_config.alias {
46                    for (key, _value) in aliases {
47                        let mut task = Task::new();
48                        task.command = Some("cargo".to_string());
49                        task.args = Some(vec![key.to_string()]);
50                        task.install_crate = Some(InstallCrate::Enabled(false));
51
52                        tasks.push((key, task));
53                    }
54                }
55            }
56        } else {
57            error!("Invalid config file path provided: {}", &file);
58        }
59    }
60
61    Ok(tasks)
62}
63
64pub(crate) fn load() -> Result<Vec<(String, Task)>, CargoMakeError> {
65    load_from_file("./.cargo/config.toml")
66}