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
//! Read crate information from `Cargo.toml`

use std::fs::File;
use std::io::Read;
use std::path::Path;

use toml;

/// Cargo.toml crate information
#[derive(Clone, Deserialize)]
pub struct Cargo {
    pub package: CargoPackage,
    pub lib: Option<CargoLib>,
    pub bin: Option<Vec<CargoLib>>,
}

/// Cargo.toml crate package information
#[derive(Clone, Deserialize)]
pub struct CargoPackage {
    pub name: String,
    pub license: Option<String>,
}

/// Cargo.toml crate lib information
#[derive(Clone, Deserialize)]
pub struct CargoLib {
    pub path: String,
}

/// Try to get crate name and license from Cargo.toml
pub fn get_cargo_info(project_root: &Path) -> Result<Cargo, String> {
    let mut cargo_toml = match File::open(project_root.join("Cargo.toml")) {
        Ok(file) => file,
        Err(e) => return Err(format!("Could not read Cargo.toml: {}", e)),
    };

    let mut buf = String::new();
    match cargo_toml.read_to_string(&mut buf) {
        Err(e) => return Err(format!("{}", e)),
        Ok(_) => {}
    }

    match toml::from_str(&buf) {
        Err(e) => return Err(format!("{}", e)),
        Ok(cargo) => Ok(cargo),
    }
}