dialtone_bots 0.1.0

Dialtone Client-side Bots
use std::fs;

use dialtone_ccli_util::config::dirs::config_path;
use serde::{Deserialize, Serialize};

pub(crate) const BOTS_CONFIG_FILE: &str = "bots.toml";

#[derive(Serialize, Deserialize, Debug)]
pub struct BotsConfig {
    #[serde(rename="example_bot")]
    pub example_bots: Option<Vec<ExampleBot>>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ExampleBot{
    pub actor_id: String,
    pub owning_acct: String
}

impl BotsConfig {
    pub fn from_config_dir() -> Self {
        let path = config_path(BOTS_CONFIG_FILE);
        let contents = fs::read_to_string(path).unwrap();
        toml::from_str(&contents).unwrap()
    }

    #[allow(dead_code)]
    pub fn from_str(str: &str) -> Self {
        toml::from_str(str).unwrap()
    }

    pub fn to_toml_string(&self) -> String {
        toml::to_string_pretty(self).unwrap()
    }
}

impl Default for BotsConfig {
    fn default() -> Self {
        Self { example_bots: Default::default() }
    }
}

#[cfg(test)]
#[allow(non_snake_case)]
mod bots_config_tests {
    use super::{BotsConfig};

    #[test]
    fn GIVEN_a_toml_string_WHEN_from_str_THEN_values_are_correct() {
        // GIVEN
        let str = r#"
        [[example_bot]]
        actor_id = "https://example.com/foo"
        owning_acct = "foo@example.com"

        [[example_bot]]
        actor_id = "https://example.com/bar"
        owning_acct = "bar@example.com"
        "#;

        // WHEN
        let config = BotsConfig::from_str(str);

        // THEN
        let bots = config.example_bots.unwrap();
        assert_eq!(bots.len(), 2);
        assert_eq!(bots.first().unwrap().actor_id, "https://example.com/foo");
        assert_eq!(bots.last().unwrap().actor_id, "https://example.com/bar");
    }
}