massa_models/config/
massa_settings.rs

1//! Build a settings for an object that implement `massa_settings`
2//!
3//! ---
4//! The massa node configuration is composed from 2 parts, one part is the
5//! file configuration often named `config.toml` located in the project
6//! directory.
7//!
8//! The First thing that the node will try is to read the configuration located
9//! in the `path` described in the environment variable `MASSA_CONFIG_PATH`.
10//! If no path found in the environment variable, the relative path
11//! `base_config/config.toml` is used as default. The default path should exist
12//! because it's a configuration file pushed in the repository.
13//!
14//! The next step will try to read the file at the given path. It will `panic`
15//! if no file found.
16//!
17//! Whatever configuration you used (the one from the environment variable or the
18//! default one) You always have a next possibility. Using the default path of
19//! configuration for the massa-project. The default configuration directories
20//! is set on Setting creation. All the configuration in this file will be merged
21//! with the previous step (override if duplicated)
22//!
23//! The last step is to merge the environment variable prefixed with
24//! `MASSA_CLIENT`, override if duplicated
25//!
26use directories::ProjectDirs;
27use serde::Deserialize;
28use std::path::Path;
29
30/// Merge the settings
31/// 1. default
32/// 2. in path specified in `MASSA_CONFIG_PATH` environment variable (`base_config/config.toml` by default)
33/// 3. in path specified in `MASSA_CONFIG_OVERRIDE_PATH` environment variable (`config/config.toml` by default)
34#[inline]
35pub fn build_massa_settings<T: Deserialize<'static>>(app_name: &str, env_prefix: &str) -> T {
36    let mut builder = config::Config::builder();
37    let config_path = std::env::var("MASSA_CONFIG_PATH")
38        .unwrap_or_else(|_| "base_config/config.toml".to_string());
39
40    builder = builder.add_source(config::File::with_name(&config_path));
41
42    let config_override_path = std::env::var("MASSA_CONFIG_OVERRIDE_PATH")
43        .unwrap_or_else(|_| "config/config.toml".to_string());
44
45    if Path::new(&config_override_path).is_file() {
46        builder = builder.add_source(config::File::with_name(&config_override_path));
47    }
48
49    if let Some(proj_dirs) = ProjectDirs::from("com", "MassaLabs", app_name) {
50        // Portable user config loading
51        let user_config_path = proj_dirs.config_dir();
52        if user_config_path.exists() {
53            let path_str = user_config_path.to_str().unwrap();
54            builder = builder.add_source(config::File::with_name(path_str));
55        }
56    }
57
58    let s = builder
59        .add_source(config::Environment::with_prefix(env_prefix))
60        .build()
61        .unwrap();
62
63    s.try_deserialize().unwrap()
64}