Skip to content

Commit

Permalink
consolidating the instance config
Browse files Browse the repository at this point in the history
  • Loading branch information
thesandybridge committed Mar 18, 2024
1 parent fe434dc commit d95a7b6
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 44 deletions.
62 changes: 43 additions & 19 deletions wpdev_core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,56 @@ use crate::AppConfig;

pub async fn read_or_create_config() -> Result<crate::AppConfig> {
info!("Reading or creating config file");
let config_dir =
dirs::config_dir().ok_or_else(|| anyhow::anyhow!("Failed to find config directory"))?;
let config_dir = config_dir.join("wpdev");
let config_dir = get_config_dir().await?;
fs::create_dir_all(&config_dir)
.await
.context("Failed to create config directory")?;

let config_path = config_dir.join("config.toml");
let default_config_dir = config_dir.join("instances");

match fs::read_to_string(&config_path).await {
Ok(contents) => {
info!("Reading config file from {:?}", config_path);
let config: AppConfig = toml::from_str(&contents)
let mut config: AppConfig = toml::from_str(&contents)
.with_context(|| format!("Failed to parse config file at {:?}", config_path))?;
info!("Checking if custom root is set");
if config.custom_root.is_none() {
info!("Custom root not found in config, setting to default value");
config.custom_root = Some(default_config_dir);
}
info!("Config file read successfully");
Ok(config)
}
Err(_) => {
info!("Creating new config file at {:?}", config_path);
Ok(AppConfig::default())
let config = AppConfig {
custom_root: Some(config_dir.join("instances")),
..AppConfig::default()
};
info!("Writing default config to {:?}", config_path);
Ok(config)
}
}
}

pub(crate) async fn get_config_dir() -> Result<PathBuf> {
info!("Getting root directory");
let config_dir = dirs::config_dir().context("Failed to find home directory")?;
let config_dir = config_dir.join("wpdev");
Ok(config_dir)
}

pub(crate) async fn get_instance_dir() -> Result<PathBuf> {
info!("Getting instance directory");
let config = read_or_create_config().await?;
let instance_dir = config
.custom_root
.ok_or_else(|| AnyhowError::msg("Custom root not found"))?;
info!("Instance directory: {:?}", instance_dir);
Ok(instance_dir)
}

pub async fn image_exists(image_name: &str) -> Result<bool> {
info!("Checking if image {} exists locally", image_name);
let docker = Docker::connect_with_defaults()?;
Expand Down Expand Up @@ -272,14 +299,16 @@ server {{
}

pub(crate) async fn generate_wpcli_config(
config: &crate::AppConfig,
config: &PathBuf,
instance_label: &str,
home_dir: &PathBuf,
) -> Result<(), AnyhowError> {
info!("Generating wp-cli config");
let instance_dir = home_dir.join(format!(
"{}/{}-{}/",
&config.custom_root,
&config
.to_str()
.ok_or_else(|| AnyhowError::msg("Config directory not found"))?,
crate::NETWORK_NAME,
instance_label
));
Expand Down Expand Up @@ -330,13 +359,9 @@ define('WP_DEBUG', false);

pub async fn read_instance_data_from_toml(instance_label: &str) -> Result<InstanceData> {
info!("Reading instance data from toml");
let config = read_or_create_config()
.await
.context("Failed to read config")?;
let home_dir = dirs::home_dir().context("Failed to find home directory")?;
let instance_dir = home_dir
.join(&config.custom_root)
.join(format!("{}/instance.toml", instance_label));
let instance_config_dir = get_instance_dir().await?;
let instance_dir = instance_config_dir.join(format!("{}/instance.toml", instance_label));
info!("Reading instance data from {:?}", instance_dir);

if !instance_dir.exists() {
error!("Instance file not found at {:?}", instance_dir);
Expand All @@ -363,14 +388,13 @@ pub(crate) async fn parse_instance_data(
env_vars: &EnvVars,
nginx_port: &u32,
adminer_port: &u32,
config: &crate::AppConfig,
home_dir: &PathBuf,
instance_label: &str,
) -> Result<InstanceData> {
info!("Parsing instance data");
let instance_dir = home_dir.join(format!(
"{}/{}-{}/instance.toml",
&config.custom_root,
let instance_config_dir = get_instance_dir().await?;
let config = read_or_create_config().await?;
let instance_dir = instance_config_dir.join(format!(
"{}-{}/instance.toml",
crate::NETWORK_NAME,
instance_label
));
Expand Down
35 changes: 12 additions & 23 deletions wpdev_core/src/docker/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::collections::HashMap;
use std::path::PathBuf;
use tokio::fs;

use crate::config::{self, read_or_create_config};
use crate::config::{self};
use crate::docker::config::{
configure_adminer_container, configure_mysql_container, configure_nginx_container,
configure_wordpress_container,
Expand Down Expand Up @@ -103,7 +103,7 @@ impl Instance {
instance_label: &str,
user_env_vars: ContainerEnvVars,
) -> Result<Self> {
let config = config::read_or_create_config().await?;
let instance_dir = config::get_instance_dir().await?;
let home_dir =
dirs::home_dir().ok_or_else(|| AnyhowError::msg("Home directory not found"))?;

Expand All @@ -125,9 +125,8 @@ impl Instance {
labels.insert("nginx_port".to_string(), nginx_port_str);
labels.insert("adminer_port".to_string(), adminer_port_str);

let instance_path = home_dir.join(PathBuf::from(format!(
"{}/{}-{}",
&config.custom_root,
let instance_path = instance_dir.join(PathBuf::from(format!(
"{}-{}",
crate::NETWORK_NAME,
instance_label
)));
Expand All @@ -151,15 +150,9 @@ impl Instance {
)
.await?;

let wordpress_data = config::parse_instance_data(
&env_vars,
&nginx_port,
&adminer_port,
&config,
&home_dir,
&instance_label,
)
.await?;
let wordpress_data =
config::parse_instance_data(&env_vars, &nginx_port, &adminer_port, &instance_label)
.await?;

let mut instance = Instance {
uuid: format!("{}-{}", crate::NETWORK_NAME, instance_label.to_string()),
Expand All @@ -172,7 +165,7 @@ impl Instance {
wordpress_data: Some(wordpress_data),
};

config::generate_wpcli_config(&config, instance_label, &home_dir).await?;
config::generate_wpcli_config(&instance_dir, instance_label, &home_dir).await?;

let containers = vec![
(mysql_options, "mysql"),
Expand Down Expand Up @@ -529,22 +522,18 @@ impl Instance {

async fn purge_instances(instance: InstanceSelection) -> Result<()> {
info!("Starting to purge instances");
let config = read_or_create_config()
.await
.context("Failed to read config")?;
let home_dir = dirs::home_dir().context("Failed to find home directory")?;
let config_dir = home_dir.join(&config.custom_root);
let instance_dir = config::get_instance_dir().await?;
let docker = Docker::connect_with_defaults().context("Failed to connect to Docker")?;

if !config_dir.exists() {
if !instance_dir.exists() {
info!("Instance directory not found");
return Ok(());
}

match instance {
InstanceSelection::All => {
info!("Pruning all instances");
let p = &config_dir;
let p = &instance_dir;
let path = p.to_str().context("Instance directory not found")?;
let networks = docker
.list_networks::<String>(None)
Expand Down Expand Up @@ -578,7 +567,7 @@ async fn purge_instances(instance: InstanceSelection) -> Result<()> {
}
InstanceSelection::One(instance_uuid) => {
info!("Removing instance: {}", instance_uuid);
let p = &config_dir;
let p = &instance_dir;
let path = p.to_str().context("Instance directory not found")?;
let instance_path = format!("{}/{}", path, instance_uuid);
if !PathBuf::from(&instance_path).exists() {
Expand Down
5 changes: 3 additions & 2 deletions wpdev_core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use serde::{Deserialize, Serialize};
use std::net::{IpAddr, Ipv4Addr};
use std::path::PathBuf;

pub mod config;
pub mod docker;
Expand All @@ -15,7 +16,7 @@ pub const WORDPRESS_CLI_IMAGE: &str = "wordpress:cli";
#[derive(Serialize, Deserialize)]
#[serde(default)]
pub struct AppConfig {
pub custom_root: String,
pub custom_root: Option<PathBuf>,
pub docker_images: Vec<String>,
pub log_level: String,
pub enable_frontend: bool,
Expand All @@ -32,7 +33,7 @@ pub struct AppConfig {
impl Default for AppConfig {
fn default() -> Self {
AppConfig {
custom_root: String::from(".config/wpdev/instances"),
custom_root: None,
docker_images: vec![
WORDPRESS_IMAGE.to_string(),
NGINX_IMAGE.to_string(),
Expand Down

0 comments on commit d95a7b6

Please sign in to comment.