Skip to main content

pastebin_ai/
config.rs

1use anyhow::Result;
2use dirs::config_dir;
3use serde::{Deserialize, Serialize};
4use std::fs;
5use std::path::PathBuf;
6
7/// Application configuration stored in `~/.config/pastebin-ai/config.toml`.
8#[derive(Debug, Serialize, Deserialize)]
9pub struct Config {
10    /// Authentication configuration (optional)
11    #[serde(skip_serializing_if = "Option::is_none")]
12    pub auth: Option<AuthConfig>,
13}
14
15/// Authentication credentials for the pastebin.ai API.
16#[derive(Debug, Serialize, Deserialize)]
17pub struct AuthConfig {
18    /// Bearer token from pastebin.ai (starts with `pba_`)
19    pub token: String,
20}
21
22impl Config {
23    /// Load configuration from disk.
24    ///
25    /// Returns an empty config if the file doesn't exist.
26    pub fn load() -> Result<Self> {
27        let path = config_path()?;
28        if path.exists() {
29            let content = fs::read_to_string(path)?;
30            Ok(toml::from_str(&content)?)
31        } else {
32            Ok(Config { auth: None })
33        }
34    }
35
36    /// Save configuration to disk.
37    ///
38    /// Creates the config directory if it doesn't exist.
39    pub fn save(&self) -> Result<()> {
40        let path = config_path()?;
41        if let Some(parent) = path.parent() {
42            fs::create_dir_all(parent)?;
43        }
44        let content = toml::to_string_pretty(self)?;
45        fs::write(path, content)?;
46        Ok(())
47    }
48}
49
50/// Get the path to the config file.
51///
52/// Returns `~/.config/pastebin-ai/config.toml` on Linux,
53/// `~/Library/Application Support/pastebin-ai/config.toml` on macOS,
54/// or the equivalent on Windows.
55fn config_path() -> Result<PathBuf> {
56    let config_dir = config_dir()
57        .ok_or_else(|| anyhow::anyhow!("Could not find config directory"))?;
58    Ok(config_dir.join("pastebin-ai").join("config.toml"))
59}