use crate::{config, error};
use serde::Deserialize;
use std::path::Path;
use tokio::fs;
#[derive(Clone, Deserialize)]
pub struct Keyfile {
keys: KeysTable,
}
#[derive(Clone, Deserialize)]
struct KeysTable {
#[cfg(feature = "github")]
#[serde(default)]
#[serde(skip_serializing_if = "config::is_empty_string")]
github: String,
#[cfg(feature = "gitlab")]
#[serde(default)]
#[serde(skip_serializing_if = "config::is_empty_string")]
gitlab: String,
}
impl Keyfile {
pub async fn get_key(&self, api_name: &str) -> String {
let keys = self.keys.to_owned();
match api_name {
#[cfg(feature = "github")]
"github" => keys.github,
#[cfg(feature = "gitlab")]
"gitlab" => keys.gitlab,
_ => String::new(),
}
}
}
pub async fn load(config_content: &Option<config::ConfigTable>) -> error::Result<Option<Keyfile>> {
if let Some(config_table) = config_content {
if let Some(keyfile) = config_table.to_owned().keyfile {
let keyfile = config::expand_tilde(keyfile)?;
let keyfile_path = Path::new(&keyfile);
let keyfile_content = if keyfile_path.exists() && keyfile_path.is_file() {
fs::read_to_string(keyfile_path).await?
} else {
String::new()
};
if keyfile_content.is_empty() {
return Err(error::Error::NoKeyfile);
}
Ok(Some(toml::from_str(&keyfile_content)?))
} else {
Ok(None)
}
} else {
Ok(None)
}
}