Skip to main content

second_brain_core/
machine.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::path::Path;
4use uuid::Uuid;
5
6pub fn data_dir() -> Result<std::path::PathBuf> {
7    let home = dirs::home_dir().context("cannot determine home directory")?;
8    Ok(home.join(".second-brain"))
9}
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct MachineIdentity {
13    pub id: String,
14    pub name: String,
15}
16
17impl MachineIdentity {
18    pub fn load_or_create(config_dir: &Path) -> Result<Self> {
19        let path = config_dir.join("machine.toml");
20        if path.exists() {
21            let content = std::fs::read_to_string(&path).context("reading machine.toml")?;
22            let identity: MachineIdentity =
23                toml::from_str(&content).context("parsing machine.toml")?;
24            return Ok(identity);
25        }
26        let name = hostname::get()
27            .map(|h| h.to_string_lossy().to_string())
28            .unwrap_or_else(|_| "unknown".to_string());
29        let identity = MachineIdentity {
30            id: Uuid::new_v4().to_string(),
31            name,
32        };
33        std::fs::create_dir_all(config_dir).context("creating config directory")?;
34        std::fs::write(&path, toml::to_string_pretty(&identity)?)
35            .context("writing machine.toml")?;
36        Ok(identity)
37    }
38
39    pub fn config_dir() -> Result<std::path::PathBuf> {
40        let home = dirs::home_dir().context("cannot determine home directory")?;
41        Ok(home.join(".second-brain"))
42    }
43}