DennisOSRM / hms-mqtt-publisher

HMS-XXXXW-2T MQTT publisher and Home Assistant addon
BSD 2-Clause "Simplified" License
111 stars 16 forks source link

Config.toml file cannot be read, if executed from other directories #75

Closed wscheff42 closed 8 months ago

wscheff42 commented 8 months ago

The config.toml file can only be read, if it's in the executed directory. if you try to call the program from other directory in e.g. /usr/bin, the program stops with an error. Following code for main.rs establish program to read config.toml in the same directory as the executable file is:

use std::path::PathBuf;

fn main() {
    let mut path = std::env::current_exe().expect("Unable to get current executable path");
    path.pop(); // Remove executable name
    path.push("config.toml");

    let contents = fs::read_to_string(&path).expect("Could not read config.toml");
    // Rest of your code using 'contents' variable
} 
DennisOSRM commented 8 months ago

Does this work when the tool is started using cargo, ie cargo r?

wscheff42 commented 8 months ago

Yes, it works. But you have to copy the config.toml file to the /target/debug dir. (tested with Raspbian 10 (buster))

DennisOSRM commented 8 months ago

K, thanks for the update. I'll think of a backwards compatible way, too.

wscheff42 commented 8 months ago

Hi,

Here you can find a proposal, checking first in calling dir, and if not available, checking in path of execution (currently not tested)

use std::fs;
use std::path::{Path, PathBuf};

fn main() {
    // Check in the current directory
    let current_dir_path = Path::new("config.toml");
    if current_dir_path.exists() {
        let contents = fs::read_to_string(current_dir_path).expect("Could not read config.toml from current directory");
        // Rest of your code using 'contents' variable
    } else {
        // Check in the path of the main program
        let mut path = std::env::current_exe().expect("Unable to get current executable path");
        path.pop(); // Remove executable name
        path.push("config.toml");

        if path.exists() {
            let contents = fs::read_to_string(&path).expect("Could not read config.toml from main program path");
            // Rest of your code using 'contents' variable
        } else {
            eprintln!("Error: config.toml not found in current directory or main program path");
        }
    }
}