the dotenv file is now also search in the users HOME

This commit is contained in:
Falko Zurell 2024-11-18 23:54:33 +01:00
parent da52a321b7
commit e1708f5e68
3 changed files with 26 additions and 4 deletions

View file

@ -1,12 +1,13 @@
[package]
name = "image-helper-wordpress"
version = "0.1.1"
version = "0.1.2"
edition = "2021"
license = "GPLv3"
authors = ["Falko Zurell <falko@zurell.de>"]
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"

View file

@ -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

View file

@ -19,8 +19,29 @@ struct Config {
impl Config {
fn from_env() -> Result<Self, Box<dyn Error>> {
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<Self, Box<dyn Error>> {
Ok(Config {
wp_url: env::var("WP_URL")?,
wp_username: env::var("WP_USERNAME")?,