Skip to content

Instantly share code, notes, and snippets.

@mirhec
Created June 20, 2019 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mirhec/a5c3fdbbbb70bc0bb75696d6f4bd7ecf to your computer and use it in GitHub Desktop.
Save mirhec/a5c3fdbbbb70bc0bb75696d6f4bd7ecf to your computer and use it in GitHub Desktop.
extern crate structopt;
extern crate ini;
use structopt::StructOpt;
use std::path::{Path, PathBuf};
use ini::Ini;
use std::fs::{self, DirEntry};
#[derive(StructOpt, Debug)]
#[structopt(name = "type-cli")]
enum Cli {
#[structopt(name = "copy-section")]
CopySection {
#[structopt(long = "input-folder")]
input: String,
#[structopt(long = "source-ini-file")]
source_ini: String,
#[structopt(long = "section-to-copy")]
section: String,
#[structopt(long = "out-folder", default_value = "out")]
output: String,
},
}
fn main() {
match Cli::from_args() {
Cli::CopySection { input, source_ini, section, output } => {
match copySection(input, source_ini, section, output) {
Err(e) => println!("Error: {}", e),
_ => println!("Done"),
}
},
}
}
fn copySection(input: String, source_ini: String, section: String, output: String) -> Result<(), String> {
let conf = Ini::load_from_file(source_ini.clone()).map_err(|e| e.to_string())?;
if !Path::new(&input).is_dir() {
return Err(format!("{} is not a directory or does not exist!", input));
}
if !Path::new(&output.clone()).is_dir() {
fs::create_dir_all(output.clone()).map_err(|e| e.to_string())?;
}
let sec = conf.section(Some(section.clone())).ok_or("The section does not exist".to_string()).map_err(|e| e.to_string())?;
println!("Should copy section {} ...", section);
for file in fs::read_dir(&input).unwrap() {
let file: DirEntry = file.map_err(|e| e.to_string())?;
let name = format!("{}", file.file_name().to_str().unwrap());
println!("Copy section {} from {} to {}", section, source_ini, file.path().display());
let mut dest = Ini::load_from_file(PathBuf::from(format!("{}/{}", input, name))).map_err(|e| e.to_string())?;
for key in sec.keys() {
let val = sec.get(key).unwrap();
dest.with_section(Some(section.to_string()))
.set(key.to_string(), val.to_string());
}
dest.write_to_file(PathBuf::from(format!("{}/{}", output, name))).map_err(|e| e.to_string())?;
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment