use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use crate::error::CliResult;
pub const CONFIG_FILE_NAME: &str = "prax.toml";
pub const PRAX_DIR: &str = "prax";
pub const SCHEMA_FILE_NAME: &str = "schema.prax";
pub const SCHEMA_FILE_PATH: &str = "prax/schema.prax";
pub const MIGRATIONS_DIR: &str = "prax/migrations";
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
pub database: DatabaseConfig,
pub generator: GeneratorConfig,
pub migrations: MigrationConfig,
pub seed: SeedConfig,
}
impl Default for Config {
fn default() -> Self {
Self {
database: DatabaseConfig::default(),
generator: GeneratorConfig::default(),
migrations: MigrationConfig::default(),
seed: SeedConfig::default(),
}
}
}
impl Config {
pub fn load(path: &Path) -> CliResult<Self> {
let content = std::fs::read_to_string(path)?;
let config: Config = toml::from_str(&content)?;
Ok(config)
}
pub fn save(&self, path: &Path) -> CliResult<()> {
let content = toml::to_string_pretty(self)?;
std::fs::write(path, content)?;
Ok(())
}
pub fn default_for_provider(provider: &str) -> Self {
let mut config = Self::default();
config.database.provider = provider.to_string();
config
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DatabaseConfig {
pub provider: String,
pub url: Option<String>,
pub shadow_url: Option<String>,
pub direct_url: Option<String>,
pub seed_path: Option<PathBuf>,
}
impl Default for DatabaseConfig {
fn default() -> Self {
Self {
provider: "postgresql".to_string(),
url: None,
shadow_url: None,
direct_url: None,
seed_path: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GeneratorConfig {
pub output: String,
pub features: Option<Vec<String>>,
pub prelude: Option<Vec<String>>,
}
impl Default for GeneratorConfig {
fn default() -> Self {
Self {
output: "./src/generated".to_string(),
features: None,
prelude: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MigrationConfig {
pub directory: String,
pub table_name: String,
pub schema: Option<String>,
}
impl Default for MigrationConfig {
fn default() -> Self {
Self {
directory: MIGRATIONS_DIR.to_string(),
table_name: "_prax_migrations".to_string(),
schema: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SeedConfig {
pub script: Option<PathBuf>,
pub auto_seed: bool,
pub environments: std::collections::HashMap<String, bool>,
}
impl Default for SeedConfig {
fn default() -> Self {
let mut environments = std::collections::HashMap::new();
environments.insert("development".to_string(), true);
environments.insert("test".to_string(), true);
environments.insert("staging".to_string(), false);
environments.insert("production".to_string(), false);
Self {
script: None,
auto_seed: false,
environments,
}
}
}
impl SeedConfig {
pub fn should_seed(&self, environment: &str) -> bool {
self.environments.get(environment).copied().unwrap_or(false)
}
}