improved script

main
Mathias Rothenhaeusler 2024-05-21 07:48:52 +02:00
parent 5044f6a19c
commit 1dd669697e
6 changed files with 85 additions and 31 deletions

View File

@ -9,6 +9,8 @@ use clap::Parser;
pub struct Arguments {
#[arg(help = "Possible values are 'up' and 'down'")]
pub action: String,
#[arg(help = "Which project folder to use, defined in your env file. E.g. xxx_DIR.")]
pub project: String,
}
impl Arguments {

View File

@ -4,12 +4,20 @@ use std::{
};
use anyhow::Context;
use crate::env::config::DevToolsConf;
pub const GLOBAL_CONNECTION_PATH: &str = "conf/global/connections.env";
const LOCAL_CONNECTION_PATH: &str = "conf/local/.env";
pub fn set_local_db(start: bool) -> Result<(), Box<dyn std::error::Error>> {
let file: File = File::open(GLOBAL_CONNECTION_PATH)
.with_context(|| format!("could not read file `{}`", GLOBAL_CONNECTION_PATH))?;
/// writes global connections
pub fn set_local_db(start: bool, config: &DevToolsConf) -> Result<(), Box<dyn std::error::Error>> {
let global_connections_env = format!(
"{}{}",
config.project_dir_as_string(),
GLOBAL_CONNECTION_PATH
);
let file: File = File::open(&global_connections_env)
.with_context(|| format!("could not read file `{}`", global_connections_env))?;
let reader: BufReader<File> = BufReader::new(file);
let modified_lines: Vec<String> = reader
@ -27,13 +35,14 @@ pub fn set_local_db(start: bool) -> Result<(), Box<dyn std::error::Error>> {
})
.collect();
fs::write(GLOBAL_CONNECTION_PATH, modified_lines.join("\n")).expect("");
fs::write(global_connections_env, modified_lines.join("\n"))
.expect("Cannot write global connections env");
Ok(())
}
pub fn set_dot_env(start: bool) -> Result<(), Box<dyn std::error::Error>> {
toggle_after_line("#docker", 4, start)?;
toggle_after_line("#cidb", 2, !start)?;
pub fn set_dot_env(start: bool, config: &DevToolsConf) -> Result<(), Box<dyn std::error::Error>> {
toggle_after_line("#docker", 4, start, config)?;
toggle_after_line("#cidb", 2, !start, config)?;
Ok(())
}
@ -49,9 +58,15 @@ fn toggle_after_line(
target_line_prefix: &str,
num_lines: usize,
activate: bool,
config: &DevToolsConf,
) -> Result<(), Box<dyn std::error::Error>> {
let file: File = File::open(LOCAL_CONNECTION_PATH)
.with_context(|| format!("could not read file `{}`", LOCAL_CONNECTION_PATH))?;
let local_connection_env = format!(
"{}{}",
config.project_dir_as_string(),
LOCAL_CONNECTION_PATH
);
let file: File = File::open(&local_connection_env)
.with_context(|| format!("could not read file `{}`", local_connection_env))?;
let reader: BufReader<File> = BufReader::new(file);
let mut modified_lines: Vec<String> = Vec::new();
@ -74,12 +89,19 @@ fn toggle_after_line(
modified_lines.push(toggle(&line_content, activate));
counter += 1;
} else {
if !activate && line_content.trim_start().starts_with("connection=") {
modified_lines.push("connection='ci'".to_string());
continue;
} else if activate && line_content.trim_start().starts_with("connection=") {
modified_lines.push("connection='staging'".to_string());
continue;
}
modified_lines.push(line_content);
}
}
// Write the modified content back to the output file
fs::write(LOCAL_CONNECTION_PATH, modified_lines.join("\n")).expect("");
fs::write(local_connection_env, modified_lines.join("\n")).expect("");
Ok(())
}

View File

@ -28,6 +28,7 @@ pub fn start_docker_compose(
let base_dir: BaseDirs = BaseDirs::new().unwrap();
let absolute = base_dir.home_dir().join(container_path);
let compose_path = Path::new(&absolute);
println!("{}", compose_path.to_str().unwrap());
let running: bool = is_container_running(service_name)?;
@ -37,9 +38,9 @@ pub fn start_docker_compose(
}
if start && compose_path.exists() {
let status: ExitStatus = Command::new("docker-compose")
let status: ExitStatus = Command::new("docker")
.current_dir(compose_path)
.args(["up", "-d"])
.args(["compose", "up", "-d"])
.status()?;
if status.success() {
@ -55,9 +56,9 @@ pub fn start_docker_compose(
}
if !start && compose_path.exists() {
let status: ExitStatus = Command::new("docker-compose")
let status: ExitStatus = Command::new("docker")
.current_dir(compose_path)
.args(["down"])
.args(["compose", "down"])
.status()?;
if status.success() {

35
src/env/config.rs vendored
View File

@ -3,15 +3,28 @@ use std::path::PathBuf;
use directories::BaseDirs;
use crate::arguments::Arguments;
const DOCKER_SERVICE: &str = "DOCKER_SERVICE";
const DOCKER_DIR: &str = "DOCKER_DIR";
pub struct DevToolsConf {
pub container_service: String,
pub container_dir: String,
pub current_directory: PathBuf,
pub project_directory: PathBuf,
}
pub fn load_config() -> Result<DevToolsConf, Box<dyn std::error::Error>> {
impl DevToolsConf {
pub fn project_dir_as_string(&self) -> String {
self.project_directory
.as_os_str()
.to_str()
.unwrap()
.to_string()
}
}
pub fn load_config(arguments: &Arguments) -> Result<DevToolsConf, Box<dyn std::error::Error>> {
let base_dir: BaseDirs = match BaseDirs::new() {
Some(dirs) => dirs,
None => {
@ -31,15 +44,23 @@ pub fn load_config() -> Result<DevToolsConf, Box<dyn std::error::Error>> {
}
};
let container_service: String =
env::var(DOCKER_SERVICE).map_err(|_| format!("{} missing in env file.", DOCKER_SERVICE))?;
let container_service: String = env::var(DOCKER_SERVICE)
.map_err(|e| format!("{} missing in env file. {}", DOCKER_SERVICE, e))?;
let container_dir: String =
env::var(DOCKER_DIR).map_err(|_| format!("{} missing in env file.", DOCKER_DIR))?;
let current_directory: PathBuf = env::current_dir()?;
env::var(DOCKER_DIR).map_err(|e| format!("{} missing in env file. {}", DOCKER_DIR, e))?;
let mut project_directory: PathBuf = env::current_dir()?;
if !arguments.project.is_empty() {
let config_to_read = format!("{}_DIR", arguments.project.to_uppercase());
let dir: String = env::var(&config_to_read)
.map_err(|e| format!("{} missing in env file. {}", &config_to_read, e))?;
project_directory = PathBuf::from(dir);
}
Ok(DevToolsConf {
container_service,
container_dir,
current_directory,
project_directory,
})
}

View File

@ -1,19 +1,27 @@
use std::process::Command;
use crate::config::parse::GLOBAL_CONNECTION_PATH;
use crate::{config::parse::GLOBAL_CONNECTION_PATH, env::config::DevToolsConf};
pub fn toggle_index(start: bool) -> Result<(), Box<dyn std::error::Error>> {
pub fn toggle_index(start: bool, config: &DevToolsConf) -> Result<(), Box<dyn std::error::Error>> {
let change: &str = match start {
true => "--assume-unchanged",
false => "--no-assume-unchanged",
};
let project_path = format!(
"{}{}",
config.project_dir_as_string(),
GLOBAL_CONNECTION_PATH
);
Command::new("git")
.args(["update-index", change, "conf/global/connections.env"])
.current_dir(&config.project_dir_as_string())
.args(["update-index", change, &project_path])
.status()?;
if !start {
Command::new("git")
.args(["checkout", GLOBAL_CONNECTION_PATH])
.current_dir(&config.project_dir_as_string())
.args(["checkout", &project_path])
.status()?;
}

View File

@ -17,17 +17,17 @@ mod git;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Arguments = Arguments::parse();
args.validate()?;
let config: DevToolsConf = load_config()?;
let config: DevToolsConf = load_config(&args)?;
let start: bool = args.action == "up";
start_docker_compose(&config.container_service, &config.container_dir, start)?;
set_local_db(start)?;
set_dot_env(start)?;
toggle_index(start)?;
set_local_db(start, &config)?;
set_dot_env(start, &config)?;
toggle_index(start, &config)?;
println!(
"Don't forget your interpreter! Current directory: {}",
config.current_directory.as_path().to_str().unwrap()
"Don't forget your interpreter! Project directory: {}",
config.project_dir_as_string()
);
Ok(())
}