use camino::Utf8PathBuf;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::path::Path;
use crate::config::{ApplyLayer, ApplyOptExt};
use crate::data::funding::FundingType;
use crate::errors::*;
#[derive(Debug, Clone)]
pub struct FundingConfig {
pub preferred_funding: Option<FundingType>,
pub yml_path: Option<String>,
pub md_path: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct FundingLayer {
pub preferred_funding: Option<FundingType>,
pub yml_path: Option<String>,
pub md_path: Option<String>,
}
impl Default for FundingConfig {
fn default() -> Self {
FundingConfig {
preferred_funding: None,
yml_path: None,
md_path: None,
}
}
}
impl ApplyLayer for FundingConfig {
type Layer = FundingLayer;
fn apply_layer(&mut self, layer: Self::Layer) {
let FundingLayer {
preferred_funding,
yml_path,
md_path,
} = layer;
self.preferred_funding.apply_opt(preferred_funding);
self.yml_path.apply_opt(yml_path);
self.md_path.apply_opt(md_path);
}
}
impl FundingConfig {
pub fn find_paths(config: &mut Option<Self>, start_dir: &Path) -> Result<()> {
let Some(this) = config else { return Ok(()) };
if this.yml_path.is_none() {
let default_yml_path =
Utf8PathBuf::from(format!("{}/.github/FUNDING.yml", start_dir.display()));
if default_yml_path.exists() {
this.yml_path = Some(default_yml_path.to_string());
}
}
if this.md_path.is_none() {
let default_md_path = Utf8PathBuf::from(format!("{}/funding.md", start_dir.display()));
if default_md_path.exists() {
this.md_path = Some(default_md_path.to_string());
}
}
let FundingConfig {
preferred_funding,
yml_path,
md_path,
} = this;
let cant_find_files = yml_path.is_none() && md_path.is_none();
let has_user_config = preferred_funding.is_some();
if cant_find_files {
if has_user_config {
return Err(OrandaError::FundingConfigInvalid);
} else {
*config = None;
}
}
Ok(())
}
}