config.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. use crate::changelogs::ChangelogFormat;
  2. use crate::github::GithubClient;
  3. use std::collections::{HashMap, HashSet};
  4. use std::fmt;
  5. use std::sync::{Arc, RwLock};
  6. use std::time::{Duration, Instant};
  7. static CONFIG_FILE_NAME: &str = "triagebot.toml";
  8. const REFRESH_EVERY: Duration = Duration::from_secs(2 * 60); // Every two minutes
  9. lazy_static::lazy_static! {
  10. static ref CONFIG_CACHE:
  11. RwLock<HashMap<String, (Result<Arc<Config>, ConfigurationError>, Instant)>> =
  12. RwLock::new(HashMap::new());
  13. }
  14. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  15. #[serde(rename_all = "kebab-case")]
  16. pub(crate) struct Config {
  17. pub(crate) relabel: Option<RelabelConfig>,
  18. pub(crate) assign: Option<AssignConfig>,
  19. pub(crate) ping: Option<PingConfig>,
  20. pub(crate) nominate: Option<NominateConfig>,
  21. pub(crate) prioritize: Option<PrioritizeConfig>,
  22. pub(crate) major_change: Option<MajorChangeConfig>,
  23. pub(crate) glacier: Option<GlacierConfig>,
  24. pub(crate) close: Option<CloseConfig>,
  25. pub(crate) autolabel: Option<AutolabelConfig>,
  26. pub(crate) notify_zulip: Option<NotifyZulipConfig>,
  27. pub(crate) github_releases: Option<GitHubReleasesConfig>,
  28. pub(crate) review_submitted: Option<ReviewSubmittedConfig>,
  29. pub(crate) shortcut: Option<ShortcutConfig>,
  30. }
  31. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  32. pub(crate) struct NominateConfig {
  33. // team name -> label
  34. pub(crate) teams: HashMap<String, String>,
  35. }
  36. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  37. pub(crate) struct PingConfig {
  38. // team name -> message
  39. // message will have the cc string appended
  40. #[serde(flatten)]
  41. teams: HashMap<String, PingTeamConfig>,
  42. }
  43. impl PingConfig {
  44. pub(crate) fn get_by_name(&self, team: &str) -> Option<(&str, &PingTeamConfig)> {
  45. if let Some((team, cfg)) = self.teams.get_key_value(team) {
  46. return Some((team, cfg));
  47. }
  48. for (name, cfg) in self.teams.iter() {
  49. if cfg.alias.contains(team) {
  50. return Some((name, cfg));
  51. }
  52. }
  53. None
  54. }
  55. }
  56. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  57. pub(crate) struct PingTeamConfig {
  58. pub(crate) message: String,
  59. #[serde(default)]
  60. pub(crate) alias: HashSet<String>,
  61. pub(crate) label: Option<String>,
  62. }
  63. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  64. pub(crate) struct AssignConfig {
  65. #[serde(default)]
  66. _empty: (),
  67. }
  68. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  69. #[serde(rename_all = "kebab-case")]
  70. pub(crate) struct RelabelConfig {
  71. #[serde(default)]
  72. pub(crate) allow_unauthenticated: Vec<String>,
  73. }
  74. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  75. pub(crate) struct ShortcutConfig {
  76. #[serde(default)]
  77. _empty: (),
  78. }
  79. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  80. pub(crate) struct PrioritizeConfig {
  81. pub(crate) label: String,
  82. }
  83. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  84. pub(crate) struct AutolabelConfig {
  85. #[serde(flatten)]
  86. pub(crate) labels: HashMap<String, AutolabelLabelConfig>,
  87. }
  88. impl AutolabelConfig {
  89. pub(crate) fn get_by_trigger(&self, trigger: &str) -> Vec<(&str, &AutolabelLabelConfig)> {
  90. let mut results = Vec::new();
  91. for (label, cfg) in self.labels.iter() {
  92. if cfg.trigger_labels.iter().any(|l| l == trigger) {
  93. results.push((label.as_str(), cfg));
  94. }
  95. }
  96. results
  97. }
  98. }
  99. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  100. pub(crate) struct AutolabelLabelConfig {
  101. #[serde(default)]
  102. pub(crate) trigger_labels: Vec<String>,
  103. #[serde(default)]
  104. pub(crate) exclude_labels: Vec<String>,
  105. #[serde(default)]
  106. pub(crate) trigger_files: Vec<String>,
  107. }
  108. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  109. pub(crate) struct NotifyZulipConfig {
  110. #[serde(flatten)]
  111. pub(crate) labels: HashMap<String, NotifyZulipLabelConfig>,
  112. }
  113. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  114. pub(crate) struct NotifyZulipLabelConfig {
  115. pub(crate) zulip_stream: u64,
  116. pub(crate) topic: String,
  117. pub(crate) message_on_add: Option<String>,
  118. pub(crate) message_on_remove: Option<String>,
  119. pub(crate) message_on_close: Option<String>,
  120. pub(crate) message_on_reopen: Option<String>,
  121. #[serde(default)]
  122. pub(crate) required_labels: Vec<String>,
  123. }
  124. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  125. pub(crate) struct MajorChangeConfig {
  126. pub(crate) zulip_ping: String,
  127. pub(crate) second_label: String,
  128. pub(crate) meeting_label: String,
  129. pub(crate) zulip_stream: u64,
  130. pub(crate) open_extra_text: Option<String>,
  131. }
  132. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  133. pub(crate) struct GlacierConfig {}
  134. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  135. pub(crate) struct CloseConfig {}
  136. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  137. pub(crate) struct ReviewSubmittedConfig {
  138. pub(crate) review_labels: Vec<String>,
  139. pub(crate) reviewed_label: String,
  140. }
  141. pub(crate) async fn get(gh: &GithubClient, repo: &str) -> Result<Arc<Config>, ConfigurationError> {
  142. if let Some(config) = get_cached_config(repo) {
  143. log::trace!("returning config for {} from cache", repo);
  144. config
  145. } else {
  146. log::trace!("fetching fresh config for {}", repo);
  147. let res = get_fresh_config(gh, repo).await;
  148. CONFIG_CACHE
  149. .write()
  150. .unwrap()
  151. .insert(repo.to_string(), (res.clone(), Instant::now()));
  152. res
  153. }
  154. }
  155. #[derive(PartialEq, Eq, Debug, serde::Deserialize)]
  156. #[serde(rename_all = "kebab-case")]
  157. pub(crate) struct GitHubReleasesConfig {
  158. pub(crate) format: ChangelogFormat,
  159. pub(crate) project_name: String,
  160. pub(crate) changelog_path: String,
  161. pub(crate) changelog_branch: String,
  162. }
  163. fn get_cached_config(repo: &str) -> Option<Result<Arc<Config>, ConfigurationError>> {
  164. let cache = CONFIG_CACHE.read().unwrap();
  165. cache.get(repo).and_then(|(config, fetch_time)| {
  166. if fetch_time.elapsed() < REFRESH_EVERY {
  167. Some(config.clone())
  168. } else {
  169. None
  170. }
  171. })
  172. }
  173. async fn get_fresh_config(
  174. gh: &GithubClient,
  175. repo: &str,
  176. ) -> Result<Arc<Config>, ConfigurationError> {
  177. let contents = gh
  178. .raw_file(repo, "master", CONFIG_FILE_NAME)
  179. .await
  180. .map_err(|e| ConfigurationError::Http(Arc::new(e)))?
  181. .ok_or(ConfigurationError::Missing)?;
  182. let config = Arc::new(toml::from_slice::<Config>(&contents).map_err(ConfigurationError::Toml)?);
  183. log::debug!("fresh configuration for {}: {:?}", repo, config);
  184. Ok(config)
  185. }
  186. #[derive(Clone, Debug)]
  187. pub enum ConfigurationError {
  188. Missing,
  189. Toml(toml::de::Error),
  190. Http(Arc<anyhow::Error>),
  191. }
  192. impl std::error::Error for ConfigurationError {}
  193. impl fmt::Display for ConfigurationError {
  194. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  195. match self {
  196. ConfigurationError::Missing => write!(
  197. f,
  198. "This repository is not enabled to use triagebot.\n\
  199. Add a `triagebot.toml` in the root of the master branch to enable it."
  200. ),
  201. ConfigurationError::Toml(e) => {
  202. write!(f, "Malformed `triagebot.toml` in master branch.\n{}", e)
  203. }
  204. ConfigurationError::Http(_) => {
  205. write!(f, "Failed to query configuration for this repository.")
  206. }
  207. }
  208. }
  209. }
  210. #[cfg(test)]
  211. mod tests {
  212. use super::*;
  213. #[test]
  214. fn sample() {
  215. let config = r#"
  216. [relabel]
  217. allow-unauthenticated = [
  218. "C-*"
  219. ]
  220. [assign]
  221. [ping.compiler]
  222. message = """\
  223. So many people!\
  224. """
  225. label = "T-compiler"
  226. [ping.wg-meta]
  227. message = """\
  228. Testing\
  229. """
  230. [nominate.teams]
  231. compiler = "T-compiler"
  232. release = "T-release"
  233. core = "T-core"
  234. infra = "T-infra"
  235. [shortcut]
  236. "#;
  237. let config = toml::from_str::<Config>(&config).unwrap();
  238. let mut ping_teams = HashMap::new();
  239. ping_teams.insert(
  240. "compiler".to_owned(),
  241. PingTeamConfig {
  242. message: "So many people!".to_owned(),
  243. label: Some("T-compiler".to_owned()),
  244. alias: HashSet::new(),
  245. },
  246. );
  247. ping_teams.insert(
  248. "wg-meta".to_owned(),
  249. PingTeamConfig {
  250. message: "Testing".to_owned(),
  251. label: None,
  252. alias: HashSet::new(),
  253. },
  254. );
  255. let mut nominate_teams = HashMap::new();
  256. nominate_teams.insert("compiler".to_owned(), "T-compiler".to_owned());
  257. nominate_teams.insert("release".to_owned(), "T-release".to_owned());
  258. nominate_teams.insert("core".to_owned(), "T-core".to_owned());
  259. nominate_teams.insert("infra".to_owned(), "T-infra".to_owned());
  260. assert_eq!(
  261. config,
  262. Config {
  263. relabel: Some(RelabelConfig {
  264. allow_unauthenticated: vec!["C-*".into()],
  265. }),
  266. assign: Some(AssignConfig { _empty: () }),
  267. ping: Some(PingConfig { teams: ping_teams }),
  268. nominate: Some(NominateConfig {
  269. teams: nominate_teams
  270. }),
  271. shortcut: Some(ShortcutConfig { _empty: () }),
  272. prioritize: None,
  273. major_change: None,
  274. glacier: None,
  275. close: None,
  276. autolabel: None,
  277. notify_zulip: None,
  278. github_releases: None,
  279. review_submitted: None,
  280. }
  281. );
  282. }
  283. }