linera_wallet_json/
paths.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Default file path resolution for wallet, keystore, and config directory.
5
6use std::{env, path::PathBuf};
7
8use anyhow::{anyhow, Error};
9use tracing::{debug, info};
10
11/// Resolves the default Linera config directory (`~/.config/linera`),
12/// creating it if necessary.
13pub fn config_dir() -> Result<PathBuf, Error> {
14    let mut config_dir = dirs::config_dir().ok_or_else(|| {
15        anyhow!(
16            "Default wallet directory is not supported in this platform: \
17             please specify storage and wallet paths"
18        )
19    })?;
20    config_dir.push("linera");
21    if !config_dir.exists() {
22        debug!("Creating default wallet directory {}", config_dir.display());
23        fs_err::create_dir_all(&config_dir)?;
24    }
25    info!("Using default wallet directory {}", config_dir.display());
26    Ok(config_dir)
27}
28
29/// Resolves the wallet file path from an explicit path, environment variable,
30/// or default location.
31pub fn wallet_path(explicit: Option<&PathBuf>, suffix: &str) -> Result<PathBuf, Error> {
32    if let Some(path) = explicit {
33        return Ok(path.clone());
34    }
35    let wallet_env_var = env::var(format!("LINERA_WALLET{suffix}")).ok();
36    if let Some(path) = wallet_env_var {
37        return Ok(path.parse()?);
38    }
39    Ok(config_dir()?.join("wallet.json"))
40}
41
42/// Resolves the keystore file path from an explicit path, environment variable,
43/// or default location.
44pub fn keystore_path(explicit: Option<&PathBuf>, suffix: &str) -> Result<PathBuf, Error> {
45    if let Some(path) = explicit {
46        return Ok(path.clone());
47    }
48    let keystore_env_var = env::var(format!("LINERA_KEYSTORE{suffix}")).ok();
49    if let Some(path) = keystore_env_var {
50        return Ok(path.parse()?);
51    }
52    Ok(config_dir()?.join("keystore.json"))
53}