From e1708f5e68250dac3496ec91ced3e47ff4553ba1 Mon Sep 17 00:00:00 2001 From: Falko Zurell Date: Mon, 18 Nov 2024 23:54:33 +0100 Subject: [PATCH] the dotenv file is now also search in the users HOME --- Cargo.toml | 3 ++- README.md | 4 ++-- src/main.rs | 23 ++++++++++++++++++++++- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 37c4fb9..62dddc1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,12 +1,13 @@ [package] name = "image-helper-wordpress" -version = "0.1.1" +version = "0.1.2" edition = "2021" license = "GPLv3" authors = ["Falko Zurell "] description = "A tool to upload images to WordPress with AI-generated descriptions" [dependencies] +dirs = "5.0" # or whatever the latest version is tokio = { version = "1.0", features = ["full"] } reqwest = { version = "0.11", features = ["json", "multipart"] } dotenv = "0.15" diff --git a/README.md b/README.md index 9f2dc7b..59fb9f3 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ The script will take the URL of the Wordpress site, the username and application Install Rust on your machine. Copy the `.env.example` to `.env` +The `.env` file is either expected in the current working directory OR in `$HOME/.image-helper-wordpress/.env` + # testing @@ -25,5 +27,3 @@ Generated description: Aerial view of a circular lake surrounded by dense forest Successfully uploaded image to WordPress with description Image URL: https://example.wordpress.com/wp-content/uploads/2024/11/DJI_0247-scaled.jpg ``` - -Hint: make sure that the `.env` file is located in $PWD when calling the program diff --git a/src/main.rs b/src/main.rs index d45cf4c..c043738 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,8 +19,29 @@ struct Config { impl Config { fn from_env() -> Result> { - dotenv()?; + // Try to load .env from current directory first + match dotenv() { + Ok(_) => return Config::load_env_vars(), + Err(_) => { + // If that fails, try the home directory + if let Some(home_dir) = dirs::home_dir() { + let config_dir = home_dir.join(".image-helper-wordpress"); + let env_path = config_dir.join(".env"); + + if env_path.exists() { + match dotenv::from_path(&env_path) { + Ok(_) => return Config::load_env_vars(), + Err(e) => println!("Failed to load .env from home directory: {}", e), + } + } + } + } + } + // If we get here, neither location worked + Err("Could not find .env file in current directory or ~/.image-helper-wordpress/.env".into()) + } + fn load_env_vars() -> Result> { Ok(Config { wp_url: env::var("WP_URL")?, wp_username: env::var("WP_USERNAME")?,