From ac27bfc4dd612b77c97f515ed85fade3babe5e2a Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Sun, 31 Jan 2021 03:23:43 +0300 Subject: [PATCH] feat(cli): add toml config - [x] init migra.toml with serialized default config parameters - [x] read and desirealize config from migra.toml --- migra-cli/Cargo.toml | 2 ++ migra-cli/src/config.rs | 39 +++++++++++++++++++++++++++++++++++++++ migra-cli/src/main.rs | 11 +++++++++-- 3 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 migra-cli/src/config.rs diff --git a/migra-cli/Cargo.toml b/migra-cli/Cargo.toml index fd9d00f..2aa9391 100644 --- a/migra-cli/Cargo.toml +++ b/migra-cli/Cargo.toml @@ -9,3 +9,5 @@ edition = "2018" [dependencies] migra-core = { path = '../migra-core' } structopt = "0.3.21" +serde = { version = "1.0", features = ["derive"] } +toml = "0.5.8" diff --git a/migra-cli/src/config.rs b/migra-cli/src/config.rs new file mode 100644 index 0000000..221fab1 --- /dev/null +++ b/migra-cli/src/config.rs @@ -0,0 +1,39 @@ +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::Path; + +const MIGRA_TOML_FILENAME: &str = "migra.toml"; + +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct Config { + directory: String, +} + +impl Default for Config { + fn default() -> Config { + Config { + directory: String::from("database"), + } + } +} + +impl Config { + pub fn read() -> Config { + fs::read_to_string(MIGRA_TOML_FILENAME) + .ok() + .and_then(|content| toml::from_str(&content).ok()) + .unwrap_or_default() + } + + pub fn initialize() -> Result<(), Box> { + if Path::new(MIGRA_TOML_FILENAME).exists() { + return Ok(()); + } + + let config = Config::default(); + let content = toml::to_string(&config)?; + fs::write(MIGRA_TOML_FILENAME, content)?; + + Ok(()) + } +} diff --git a/migra-cli/src/main.rs b/migra-cli/src/main.rs index 2a3a0e7..e1131e6 100644 --- a/migra-cli/src/main.rs +++ b/migra-cli/src/main.rs @@ -1,16 +1,23 @@ #![deny(clippy::all)] +mod config; mod opts; +use config::Config; use opts::{AppOpt, StructOpt}; -fn main() { +fn main() -> Result<(), Box> { let opt = AppOpt::from_args(); dbg!(&opt); + let config = Config::read(); + dbg!(&config); + match opt { AppOpt::Init => { - println!("unimplemented"); + Config::initialize()?; } } + + Ok(()) }