cli/descriptor/
cargo_alias.rs

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
//! # cargo_alias
//!
//! Dynamically creates tasks based on alias information in the cargo config.
//!

#[cfg(test)]
#[path = "cargo_alias_test.rs"]
mod cargo_alias_test;

use crate::error::CargoMakeError;
use crate::io;
use crate::types::{InstallCrate, Task};
use std::collections::HashMap;
use std::path::Path;

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum AliasValue {
    String(String),
    List(Vec<String>),
}

#[derive(Serialize, Deserialize, Debug)]
struct CargoConfig {
    alias: Option<HashMap<String, AliasValue>>,
}

fn load_from_file(file: &str) -> Result<Vec<(String, Task)>, CargoMakeError> {
    let file_path = Path::new(file);

    let mut tasks = vec![];
    if file_path.exists() {
        if file_path.is_file() {
            let text = io::read_text_file(&file_path.to_path_buf())?;

            if !text.is_empty() {
                let cargo_config: CargoConfig = match toml::from_str(&text) {
                    Ok(value) => value,
                    Err(error) => {
                        warn!("Unable to parse cargo config file, {}", error);
                        CargoConfig { alias: None }
                    }
                };

                if let Some(aliases) = cargo_config.alias {
                    for (key, _value) in aliases {
                        let mut task = Task::new();
                        task.command = Some("cargo".to_string());
                        task.args = Some(vec![key.to_string()]);
                        task.install_crate = Some(InstallCrate::Enabled(false));

                        tasks.push((key, task));
                    }
                }
            }
        } else {
            error!("Invalid config file path provided: {}", &file);
        }
    }

    Ok(tasks)
}

pub(crate) fn load() -> Result<Vec<(String, Task)>, CargoMakeError> {
    load_from_file("./.cargo/config.toml")
}