rust_ai_generator/utils/
config.rs

1//!
2//! # Configuration
3//!
4//! Provide configuration related types and functions/methods.
5//!
6//! Note: `config.yml` must locate in your current working directory.
7//! 
8//! ## Example
9//! 
10//! ```yaml
11//! azure:
12//!   speech:
13//!     key: 4c7eXXXXXXXXXXXXXXXXXXXXXXX54c32
14//!     region: westus
15//! ```
16
17////////////////////////////////////////////////////////////////////////////////
18
19use std::{fs::read_to_string, path::PathBuf};
20use serde::{Deserialize, Serialize};
21use serde_yaml;
22
23/// Configurations from `config.yml`
24///
25/// Example contents:
26/// ```yaml
27/// azure:
28///   speech:
29///     key: 4c7eXXXXXXXXXXXXXXXXXXXXXXX54c32
30///     region: westus
31/// ```
32///
33/// # Examples
34///
35/// ```rust
36/// use rust_ai_generator::utils::config::Config;
37///
38/// let config = Config::load();
39/// ```
40#[derive(Debug, Serialize, Deserialize)]
41pub struct Config {
42    /// Azure config mapping
43    pub azure: Azure,
44}
45
46impl Config {
47    /// Load contents from local config file.
48    pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
49        let config_path = PathBuf::from("config.yml");
50        if !config_path.exists() {
51            return Err("`config.yml` doesn't exist!".into());
52        }
53
54        return if let Ok(config_contents) = read_to_string(config_path) {
55            match serde_yaml::from_str(&config_contents) {
56                Ok(config) => Ok(config),
57                Err(e) => {
58                    Err(e.into())
59                }
60            }
61        } else {
62            Err("Unable to read `config.yml`".into())
63        };
64    }
65}
66
67
68/// A mapping for Azure (Global) configuration contents
69#[derive(Debug, Serialize, Deserialize)]
70pub struct Azure {
71    /// Configuration content for cognitive/speech.
72    pub speech: AzureSpeech,
73}
74
75/// Service key for use in multiple Azure services.
76#[derive(Debug, Serialize, Deserialize)]
77pub struct AzureSpeech {
78    /// Key content from <https://portal.azure.com/>
79    pub key: String,
80
81    /// Region name from <https://portal.azure.com/>
82    pub region: String,
83}