migra/migra-cli/src/config.rs

164 lines
4.7 KiB
Rust
Raw Normal View History

2021-02-10 01:13:27 +03:00
use crate::error::{Error, ErrorKind};
use crate::migration::Migration;
2021-02-05 01:37:25 +03:00
use crate::path::PathBuilder;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::{env, fs, io};
2021-01-31 03:34:38 +03:00
const MIGRA_TOML_FILENAME: &str = "Migra.toml";
const DEFAULT_DATABASE_CONNECTION_ENV: &str = "$DATABASE_URL";
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct Config {
#[serde(skip)]
root: PathBuf,
directory: PathBuf,
#[serde(default)]
database: DatabaseConfig,
2021-01-31 13:40:02 +03:00
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2021-01-31 13:40:02 +03:00
pub(crate) struct DatabaseConfig {
pub connection: Option<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: Some(String::from(DEFAULT_DATABASE_CONNECTION_ENV)),
},
}
}
}
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);
Some(config_path)
}
Some(config_path) => Some(config_path),
None => recursive_find_config_file().ok(),
2021-02-02 00:53:33 +03:00
};
match config_path {
None => Ok(Config::default()),
Some(config_path) => {
let content = fs::read_to_string(&config_path)?;
2021-02-02 00:53:33 +03:00
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();
2021-02-02 00:53:33 +03:00
Ok(config)
}
}
}
pub fn initialize(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
let config_path = config_path
.map(|mut config_path| {
let ext = config_path.extension();
if config_path.is_dir() || ext.is_none() {
config_path.push(MIGRA_TOML_FILENAME);
}
config_path
})
.unwrap_or_else(|| PathBuf::from(MIGRA_TOML_FILENAME));
if config_path.exists() {
println!("{} already exists", config_path.to_str().unwrap());
return Ok(());
} else if let Some(dirs) = config_path.parent() {
fs::create_dir_all(dirs)?;
}
let config = Config::default();
let content = toml::to_string(&config)?;
fs::write(&config_path, content)?;
println!("Created {}", config_path.to_str().unwrap());
2021-01-31 03:34:38 +03:00
Ok(())
}
}
impl Config {
pub fn directory_path(&self) -> PathBuf {
PathBuilder::from(&self.root)
.append(&self.directory)
.build()
}
2021-02-10 01:13:27 +03:00
pub fn database_connection_string(&self) -> crate::error::Result<String> {
let connection = self
.database
.connection
.clone()
.unwrap_or_else(|| String::from(DEFAULT_DATABASE_CONNECTION_ENV));
if let Some(connection_env) = connection.strip_prefix("$") {
2021-02-10 01:13:27 +03:00
env::var(connection_env)
.map_err(|e| Error::new(ErrorKind::MissedEnvVar(connection_env.to_string()), e))
} else {
2021-02-10 01:13:27 +03:00
Ok(connection)
}
}
pub fn migration_dir_path(&self) -> PathBuf {
PathBuilder::from(&self.directory_path())
.append("migrations")
.build()
}
pub fn migrations(&self) -> io::Result<Vec<Migration>> {
2021-02-10 01:13:27 +03:00
let mut entries = match self.migration_dir_path().read_dir() {
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
entries => entries?
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, io::Error>>()?,
};
if entries.is_empty() {
return Ok(vec![]);
}
entries.sort();
let migrations = entries
.iter()
.filter_map(Migration::new)
.collect::<Vec<_>>();
Ok(migrations)
}
}