summaryrefslogtreecommitdiff
path: root/dichroism/src/config.rs
blob: 225ee4c8cb21460a69e9d1e1a80dfd3219500316 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use crate::result::Result;
use anyhow::{anyhow, Context};
use std::{env::var, net::SocketAddr, path::PathBuf};

#[derive(Debug, Clone)]
pub struct Config {
    pub bind_addr: SocketAddr,
    pub db_path: PathBuf,
    pub img_path: PathBuf,
}

impl Config {
    pub fn from_env() -> Result<Self> {
        let config = Self {
            bind_addr: var("GL_BIND_ADDR")
                .with_context(|| "Bind address missing.")?
                .parse()
                .with_context(|| "Failed to parse bind address.")?,
            db_path: var("GL_DB_PATH")
                .with_context(|| "Database path missing.")?
                .parse()
                .with_context(|| "Failed to parse database path.")?,
            img_path: var("GL_IMG_PATH")
                .with_context(|| "Image store path missing.")?
                .parse()
                .with_context(|| "Failed to parse image store path.")?,
        };

        if config.db_path.is_dir() {
            Err(anyhow!(format!(
                "Database path {:?} is not a regular file",
                config.db_path
            )))
        } else if !config.img_path.is_dir() {
            Err(anyhow!(format!(
                "Image store path {:?} is not a directory.",
                config.img_path
            )))
        } else if config.img_path.read_dir().is_err() {
            Err(anyhow!(format!(
                "Image store path {:?} is not readable.",
                config.img_path
            )))
        } else {
            Ok(config)
        }
    }
}