Skip to main content

discord_proxy/
config.rs

1use anyhow::{Context, Result};
2use serde::Deserialize;
3use std::{
4    fs,
5    path::{Path, PathBuf},
6};
7
8const DEFAULT_CONFIG: &str = "discord-proxy.toml";
9
10#[derive(Debug, Default, Deserialize)]
11pub struct FileConfig {
12    pub proxy: Option<String>,
13    pub channel: Option<String>,
14    pub discord_dir: Option<PathBuf>,
15}
16
17pub fn load(path: Option<&Path>) -> Result<FileConfig> {
18    let path = match path {
19        Some(path) => path.to_path_buf(),
20        None => PathBuf::from(DEFAULT_CONFIG),
21    };
22
23    if !path.exists() {
24        if path.file_name().and_then(|name| name.to_str()) == Some(DEFAULT_CONFIG) {
25            return Ok(FileConfig::default());
26        }
27        anyhow::bail!("config file does not exist: {}", path.display());
28    }
29
30    let content = fs::read_to_string(&path)
31        .with_context(|| format!("failed to read config file {}", path.display()))?;
32    toml::from_str(&content)
33        .with_context(|| format!("failed to parse config file {}", path.display()))
34}