moksha_wallet/
config_path.rs

1use dirs::home_dir;
2use std::{fs::create_dir, path::PathBuf};
3
4pub const ENV_DB_PATH: &str = "WALLET_DB_PATH";
5
6/// Returns the path to the wallet database file.
7///
8/// The path is determined by the value of the `WALLET_DB_PATH` environment variable. If the
9/// variable is not set, the function creates a `.moksha` directory in the user's home directory
10/// and returns a path to a `wallet.db` file in that directory.
11///
12/// # Examples
13///
14/// ```
15/// let db_path = moksha_wallet::config_path::db_path();
16/// println!("Database path: {}", db_path);
17/// ```
18pub fn db_path() -> String {
19    std::env::var(ENV_DB_PATH).map_or_else(
20        |_| {
21            let home = home_dir()
22                .expect("home dir not found")
23                .to_str()
24                .expect("home dir is invalid")
25                .to_owned();
26            // in a sandboxed environment on mac the path looks like
27            // /Users/$USER_NAME/Library/Containers/..... so we have are just ising the first 2 parts
28            let home = home
29                .split('/')
30                .take(3)
31                .collect::<Vec<&str>>()
32                .join(std::path::MAIN_SEPARATOR_STR);
33            let moksha_dir = format!("{}{}.moksha", home, std::path::MAIN_SEPARATOR);
34
35            if !std::path::Path::new(&moksha_dir).exists() {
36                create_dir(std::path::Path::new(&moksha_dir))
37                    .expect("failed to create .moksha dir");
38            }
39
40            format!("{moksha_dir}/wallet.db")
41        },
42        |val| val,
43    )
44}
45
46pub fn config_dir() -> PathBuf {
47    let home = home_dir()
48        .expect("home dir not found")
49        .to_str()
50        .expect("home dir is invalid")
51        .to_owned();
52    // in a sandboxed environment on mac the path looks like
53    // /Users/$USER_NAME/Library/Containers/..... so we have are just ising the first 2 parts
54    let home = home
55        .split('/')
56        .take(3)
57        .collect::<Vec<&str>>()
58        .join(std::path::MAIN_SEPARATOR_STR);
59    let moksha_dir = format!("{}{}.moksha", home, std::path::MAIN_SEPARATOR);
60
61    if !std::path::Path::new(&moksha_dir).exists() {
62        create_dir(std::path::Path::new(&moksha_dir)).expect("failed to create .moksha dir");
63    }
64    PathBuf::from(moksha_dir)
65}