icann_rdap_cli/dirs/
project.rs

1use std::{
2    fs::{create_dir_all, remove_dir_all, write},
3    path::PathBuf,
4    sync::LazyLock,
5};
6
7use directories::ProjectDirs;
8
9pub const QUALIFIER: &str = "org";
10pub const ORGANIZATION: &str = "ICANN";
11pub const APPLICATION: &str = "rdap";
12
13pub const ENV_FILE_NAME: &str = "rdap.env";
14pub const RDAP_CACHE_NAME: &str = "rdap_cache";
15pub const BOOTSTRAP_CACHE_NAME: &str = "bootstrap_cache";
16
17pub(crate) static PROJECT_DIRS: LazyLock<ProjectDirs> = LazyLock::new(|| {
18    ProjectDirs::from(QUALIFIER, ORGANIZATION, APPLICATION)
19        .expect("unable to formulate project directories")
20});
21
22/// Initializes the directories to be used.
23pub fn init() -> Result<(), std::io::Error> {
24    create_dir_all(PROJECT_DIRS.config_dir())?;
25    create_dir_all(PROJECT_DIRS.cache_dir())?;
26    create_dir_all(rdap_cache_path())?;
27    create_dir_all(bootstrap_cache_path())?;
28
29    // create default config file
30    if !config_path().exists() {
31        let example_config = include_str!("rdap.env");
32        write(config_path(), example_config)?;
33    }
34    Ok(())
35}
36
37/// Reset the directories.
38pub fn reset() -> Result<(), std::io::Error> {
39    remove_dir_all(PROJECT_DIRS.config_dir())?;
40    remove_dir_all(PROJECT_DIRS.cache_dir())?;
41    init()
42}
43
44/// Returns a [PathBuf] to the configuration file.
45pub fn config_path() -> PathBuf {
46    if let Ok(xdg_config) = std::env::var("XDG_CONFIG_HOME") {
47        PathBuf::from(xdg_config).join(ENV_FILE_NAME)
48    } else {
49        PROJECT_DIRS.config_dir().join(ENV_FILE_NAME)
50    }
51}
52
53/// Returns a [PathBuf] to the cache directory for RDAP responses.
54pub fn rdap_cache_path() -> PathBuf {
55    PROJECT_DIRS.cache_dir().join(RDAP_CACHE_NAME)
56}
57
58/// Returns a [PathBuf] to the cache directory for bootstrap files.
59pub fn bootstrap_cache_path() -> PathBuf {
60    if let Ok(xdg_cache) = std::env::var("XDG_CACHE_HOME") {
61        PathBuf::from(xdg_cache).join(BOOTSTRAP_CACHE_NAME)
62    } else {
63        PROJECT_DIRS.cache_dir().join(BOOTSTRAP_CACHE_NAME)
64    }
65}