feat: add gen toml
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
use std::fs;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use clap::{ArgMatches, SubCommand, App, Arg};
|
||||
use crates_io_api::{SyncClient, CrateResponse};
|
||||
@@ -19,9 +21,65 @@ impl Command for CommandImpl {
|
||||
"cargotool (https://hatter.me/)", Duration::from_millis(1000)
|
||||
)?;
|
||||
|
||||
let toml_str = match fs::read_to_string("Cargo.toml") {
|
||||
Ok(s) => s, Err(e) => {
|
||||
failure!("Read file Cargo.toml failed: {}", e);
|
||||
return Ok(());
|
||||
},
|
||||
};
|
||||
let mut toml: toml::Value = match toml_str.parse() {
|
||||
Ok(t) => t, Err(e) => {
|
||||
failure!("Parse Cargo.toml failed: {}", e);
|
||||
return Ok(());
|
||||
},
|
||||
};
|
||||
|
||||
let mut exists_dependencies_map: HashMap<String, String> = HashMap::new();
|
||||
if let toml::Value::Table(cargo_map) = &toml {
|
||||
if let Some(toml::Value::Table(dependencies)) = cargo_map.get("dependencies") {
|
||||
for (k, v) in dependencies.iter() {
|
||||
match v {
|
||||
toml::Value::String(s) => {
|
||||
exists_dependencies_map.insert(k.clone(), s.clone());
|
||||
},
|
||||
toml::Value::Table(t) => {
|
||||
if let Some(toml::Value::String(version)) = t.get("version") {
|
||||
exists_dependencies_map.insert(k.clone(), version.clone());
|
||||
}
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut is_updated = false;
|
||||
if let Some(add_crates) = sub_arg_matches.values_of("add") {
|
||||
for c in add_crates {
|
||||
find_create(&crate_io_client, c);
|
||||
if exists_dependencies_map.contains_key(c) {
|
||||
warning!("Crate: {} exists!", c);
|
||||
} else {
|
||||
if let Some(crate_response) = find_create(&crate_io_client, c) {
|
||||
if let toml::Value::Table(cargo_map) = &mut toml {
|
||||
if let Some(toml::Value::Table(dependencies)) = cargo_map.get_mut("dependencies") {
|
||||
is_updated = true;
|
||||
let crate_data = crate_response.crate_data;
|
||||
dependencies.insert(crate_data.id, toml::Value::String(crate_data.max_version));
|
||||
success!("Adding crate: {}", c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if is_updated {
|
||||
match toml::to_string_pretty(&toml) {
|
||||
Err(e) => failure!("Generate toml failed: {}", e),
|
||||
Ok(t) => match fs::write("Cargo.toml.new", t) {
|
||||
Err(e) => failure!("Write to file: Carto.toml, failed: {}", e),
|
||||
Ok(_) => success!("Write to file: Cargo.toml success!"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user