migra/migra-cli/src/config.rs

91 lines
2.4 KiB
Rust
Raw Normal View History

use migra_core::path::PathBuilder;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
2021-01-31 03:34:38 +03:00
const MIGRA_TOML_FILENAME: &str = "Migra.toml";
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct Config {
#[serde(skip)]
pub root: PathBuf,
pub directory: PathBuf,
2021-01-31 13:40:02 +03:00
pub database: DatabaseConfig,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct DatabaseConfig {
pub connection: String,
}
impl Default for Config {
fn default() -> Config {
Config {
root: PathBuf::new(),
directory: PathBuf::from("database"),
2021-01-31 13:40:02 +03:00
database: DatabaseConfig {
connection: String::new(),
},
}
}
}
2021-02-02 00:53:33 +03:00
fn recursive_find_config_file() -> io::Result<PathBuf> {
let current_dir = std::env::current_dir()?;
2021-02-02 00:53:33 +03:00
let mut read_dir = Some(current_dir.as_path());
2021-02-02 00:53:33 +03:00
loop {
if let Some(dir) = read_dir {
let migra_file_path = PathBuilder::from(dir).append(MIGRA_TOML_FILENAME).build();
if !migra_file_path.exists() {
read_dir = dir.parent();
continue;
}
2021-02-02 00:53:33 +03:00
return Ok(migra_file_path);
} else {
return Err(io::Error::from(io::ErrorKind::NotFound));
}
}
}
2021-02-02 00:53:33 +03:00
impl Config {
pub fn read(config_path: Option<PathBuf>) -> io::Result<Config> {
let config_path = match config_path {
Some(mut config_path) if config_path.is_dir() => {
config_path.push(MIGRA_TOML_FILENAME);
config_path
},
Some(config_path) => config_path,
None => recursive_find_config_file()?,
};
2021-02-02 00:53:33 +03:00
let content = fs::read_to_string(&config_path)?;
let mut config: Config = toml::from_str(&content).expect("Cannot parse Migra.toml");
config.root = config_path
.parent()
.unwrap_or_else(|| Path::new(""))
.to_path_buf();
Ok(config)
}
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(())
}
}