1use crate::{error::Result, utils::get_project_root};
4use serde::Deserialize;
5use std::{fs, path::PathBuf};
6
7const CONFIG_NAMES: &[&str] = &["prdoc.toml", ".prdoc.toml"];
8
9pub mod env {
11 pub const PRDOC_CONFIG: &str = "PRDOC_CONFIG";
14
15 pub const PRDOC_FOLDERS: &str = "PRDOC_FOLDERS";
18}
19
20#[derive(Debug, Deserialize)]
22pub struct PRDocConfig {
23 pub(crate) schema: PathBuf,
27
28 pub prdoc_folders: Vec<PathBuf>,
30
31 pub(crate) output_dir: PathBuf,
33
34 pub(crate) template: PathBuf,
36}
37
38pub struct Config;
40
41impl Config {
42 pub fn get_config_file(config_file: Option<PathBuf>) -> Result<PathBuf> {
47 let root = get_project_root().expect("prdoc should run in a repo");
48
49 if let Some(config) = config_file {
50 if PathBuf::from(&config).exists() {
51 log::debug!("Found config in {config:?}");
52 return Ok(config);
53 }
54 }
55
56 for name in CONFIG_NAMES {
57 let candidate = root.join(name);
58 if candidate.exists() {
59 log::debug!("Found config in {}", candidate.display());
60 return Ok(candidate);
61 }
62 }
63
64 log::warn!("Config not found");
65 Err(crate::error::PRdocLibError::MissingConfig)
66 }
67
68 pub fn get_default_config() -> PRDocConfig {
70 PRDocConfig::default()
71 }
72
73 pub fn load(config_opts: Option<PathBuf>) -> Result<PRDocConfig> {
75 let config_file = Self::get_config_file(config_opts)?;
76 log::debug!("Loading config from {config_file:?}");
77 let str = match fs::read_to_string(config_file.clone()) {
78 Ok(s) => s,
79 Err(_) => Err(crate::error::PRdocLibError::InvalidConfig(config_file.clone()))?,
80 };
81
82 match toml::from_str(str.as_str()) {
83 Ok(c) => Ok(c),
84 Err(_e) => Err(crate::error::PRdocLibError::InvalidConfig(config_file))?,
85 }
86 }
87}
88
89impl Default for PRDocConfig {
90 fn default() -> Self {
91 Self {
92 schema: "prdoc/schema_user.json".into(),
94 prdoc_folders: vec!["prdoc".into()],
95 output_dir: "prdoc".into(),
96 template: "template.prdoc".into(),
97 }
98 }
99}
100
101impl PRDocConfig {
102 pub fn schema_path(&self) -> PathBuf {
104 self.schema.clone()
105 }
106}