Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I save my config files in Rust

I need to persist information, such as the user's configuration for my program and their input. Where would the best place be to save this files on Linux and Windows?

This is for a rust-cargo program, which will be installed into ~/.cargo/bin for its usage. I have tried to save my files into ~/.cargo but I don't know if this is appropiate, as I am new into Rust.

like image 551
Mario Codes Avatar asked Oct 24 '19 12:10

Mario Codes


1 Answers

There's nothing special for applications written in Rust. Contrary to other solutions coming with a runtime, Rust builds normal applications relying on the standard env and practices. The normal rules of the system apply for configuration locations.

On linux you should first query the XDG paths then use $HOME as fallback when it's not available.

Here's how you can do it:

use std::env::var;

fn main() {
    let config_home = var("XDG_CONFIG_HOME")
        .or_else(|_| var("HOME").map(|home|format!("{}/.config", home)));
    println!("{:?}", config_home);
}

Note that several libraries do this job for you and take care of supporting alternate operating systems.

I won't link to them because they are many of them and they often change but your favourite search engine will direct you to the most popular ones if you search for "rust configuration directory".

like image 189
Denys Séguret Avatar answered Nov 22 '22 13:11

Denys Séguret