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