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#[derive(Debug, Serialize, Deserialize)]
8pub struct Config {
9    #[serde(skip_serializing_if = "Option::is_none")]
10    pub auth: Option<AuthConfig>,
11}
12
13#[derive(Debug, Serialize, Deserialize)]
14pub struct AuthConfig {
15    pub token: String,
16}
17
18impl Config {
19    pub fn load() -> Result<Self> {
20        let path = config_path()?;
21        if path.exists() {
22            let content = fs::read_to_string(path)?;
23            Ok(toml::from_str(&content)?)
24        } else {
25            Ok(Config { auth: None })
26        }
27    }
28
29    pub fn save(&self) -> Result<()> {
30        let path = config_path()?;
31        if let Some(parent) = path.parent() {
32            fs::create_dir_all(parent)?;
33        }
34        let content = toml::to_string_pretty(self)?;
35        fs::write(path, content)?;
36        Ok(())
37    }
38}
39
40fn config_path() -> Result<PathBuf> {
41    let config_dir = config_dir()
42        .ok_or_else(|| anyhow::anyhow!("Could not find config directory"))?;
43    Ok(config_dir.join("pastebin-ai").join("config.toml"))
44}