Skip to main content

interstice_cli/
data_directory.rs

1use directories::ProjectDirs;
2use interstice_core::IntersticeError;
3use serde::{Deserialize, Serialize};
4use std::{fs, path::PathBuf};
5use uuid::Uuid;
6
7pub fn data_file() -> PathBuf {
8    let proj_dirs = ProjectDirs::from(
9        "com",        // qualifier (reverse domain)
10        "naloween",   // organization
11        "interstice", // application name
12    )
13    .expect("Could not determine data directory");
14
15    let dir = proj_dirs.data_dir(); // persistent app data
16    fs::create_dir_all(dir).expect("Failed to create data directory");
17
18    dir.to_path_buf()
19}
20
21pub fn nodes_dir() -> PathBuf {
22    let dir = data_file().join("nodes");
23    fs::create_dir_all(&dir).expect("Failed to create nodes directory");
24    dir
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct CliIdentity {
29    pub cli_id: String,
30    pub cli_token: String,
31}
32
33pub fn load_cli_identity() -> Result<CliIdentity, IntersticeError> {
34    let path = data_file().join("cli_identity.toml");
35    if path.exists() {
36        let contents = fs::read_to_string(&path).map_err(|err| {
37            IntersticeError::Internal(format!(
38                "Failed to read CLI identity {}: {err}",
39                path.display()
40            ))
41        })?;
42        if contents.trim().is_empty() {
43            return create_and_save_identity(&path);
44        }
45        let identity: CliIdentity = toml::from_str(&contents).map_err(|err| {
46            IntersticeError::Internal(format!(
47                "Failed to parse CLI identity {}: {err}",
48                path.display()
49            ))
50        })?;
51        if identity.cli_id.trim().is_empty() || identity.cli_token.trim().is_empty() {
52            return create_and_save_identity(&path);
53        }
54        Ok(identity)
55    } else {
56        create_and_save_identity(&path)
57    }
58}
59
60fn create_and_save_identity(path: &PathBuf) -> Result<CliIdentity, IntersticeError> {
61    let identity = CliIdentity {
62        cli_id: Uuid::new_v4().to_string(),
63        cli_token: Uuid::new_v4().to_string(),
64    };
65    let contents = toml::to_string_pretty(&identity).map_err(|err| {
66        IntersticeError::Internal(format!("Failed to serialize CLI identity: {err}"))
67    })?;
68    fs::write(path, contents).map_err(|err| {
69        IntersticeError::Internal(format!(
70            "Failed to write CLI identity {}: {err}",
71            path.display()
72        ))
73    })?;
74    Ok(identity)
75}