migra/migra-cli/src/config.rs

53 lines
1.2 KiB
Rust
Raw Normal View History

use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
2021-01-31 03:34:38 +03:00
const MIGRA_TOML_FILENAME: &str = "Migra.toml";
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct Config {
2021-01-31 13:40:02 +03:00
pub directory: String,
pub database: DatabaseConfig,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct DatabaseConfig {
pub connection: String
}
impl Default for Config {
fn default() -> Config {
Config {
directory: String::from("database"),
2021-01-31 13:40:02 +03:00
database: DatabaseConfig {
connection: String::new(),
}
}
}
}
2021-01-31 13:40:02 +03:00
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<dyn std::error::Error>> {
if Path::new(MIGRA_TOML_FILENAME).exists() {
2021-01-31 03:34:38 +03:00
println!("{} already exists", MIGRA_TOML_FILENAME);
return Ok(());
}
let config = Config::default();
let content = toml::to_string(&config)?;
fs::write(MIGRA_TOML_FILENAME, content)?;
2021-01-31 03:34:38 +03:00
println!("Created {}", MIGRA_TOML_FILENAME);
Ok(())
}
}