Skip to main content

second_brain_core/
machine.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::io::ErrorKind;
4use std::path::Path;
5use uuid::Uuid;
6
7const MACHINE_FILE: &str = "machine.toml";
8
9pub fn data_dir() -> Result<std::path::PathBuf> {
10    let home = dirs::home_dir().context("cannot determine home directory")?;
11    Ok(home.join(".second-brain"))
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct MachineIdentity {
16    pub id: String,
17    pub name: String,
18}
19
20impl MachineIdentity {
21    pub fn load_or_create(config_dir: &Path) -> Result<Self> {
22        if let Some(identity) = Self::load(config_dir)? {
23            return Ok(identity);
24        }
25        let identity = Self::fresh();
26        std::fs::create_dir_all(config_dir).context("creating config directory")?;
27        std::fs::write(
28            config_dir.join(MACHINE_FILE),
29            toml::to_string_pretty(&identity)?,
30        )
31        .context("writing machine.toml")?;
32        Ok(identity)
33    }
34
35    /// None when `config_dir` holds no machine.toml.
36    pub fn load(config_dir: &Path) -> Result<Option<Self>> {
37        let content = match std::fs::read_to_string(config_dir.join(MACHINE_FILE)) {
38            Ok(content) => content,
39            Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
40            Err(e) => return Err(e).context("reading machine.toml"),
41        };
42        toml::from_str(&content)
43            .map(Some)
44            .context("parsing machine.toml")
45    }
46
47    /// Replaces `machine.toml` with a fresh machine id, atomically.
48    pub(crate) fn mint(config_dir: &Path) -> Result<Self> {
49        let identity = Self::fresh();
50        let temp = config_dir.join(format!(".{MACHINE_FILE}.{}.tmp", Uuid::new_v4().simple()));
51        std::fs::write(&temp, toml::to_string_pretty(&identity)?)
52            .and_then(|()| std::fs::File::open(&temp)?.sync_all())
53            .and_then(|()| std::fs::rename(&temp, config_dir.join(MACHINE_FILE)))
54            .with_context(|| format!("writing a new machine id into {}", config_dir.display()))
55            .inspect_err(|_| {
56                if let Err(e) = std::fs::remove_file(&temp)
57                    && e.kind() != ErrorKind::NotFound
58                {
59                    tracing::warn!("cannot remove {}: {e}", temp.display());
60                }
61            })?;
62        std::fs::File::open(config_dir)
63            .and_then(|d| d.sync_all())
64            .with_context(|| format!("syncing {}", config_dir.display()))?;
65        Ok(identity)
66    }
67
68    fn fresh() -> Self {
69        let name = hostname::get()
70            .map(|h| h.to_string_lossy().to_string())
71            .unwrap_or_else(|_| "unknown".to_string());
72        MachineIdentity {
73            id: Uuid::new_v4().to_string(),
74            name,
75        }
76    }
77
78    pub fn config_dir() -> Result<std::path::PathBuf> {
79        let home = dirs::home_dir().context("cannot determine home directory")?;
80        Ok(home.join(".second-brain"))
81    }
82}