handlers.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. use crate::config::{self, Config, ConfigurationError};
  2. use crate::github::{Event, GithubClient, IssueCommentAction, IssuesAction, IssuesEvent};
  3. use octocrab::Octocrab;
  4. use parser::command::{Command, Input};
  5. use std::fmt;
  6. use std::sync::Arc;
  7. use tokio_postgres::Client as DbClient;
  8. #[derive(Debug)]
  9. pub enum HandlerError {
  10. Message(String),
  11. Other(anyhow::Error),
  12. }
  13. impl std::error::Error for HandlerError {}
  14. impl fmt::Display for HandlerError {
  15. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  16. match self {
  17. HandlerError::Message(msg) => write!(f, "{}", msg),
  18. HandlerError::Other(_) => write!(f, "An internal error occurred."),
  19. }
  20. }
  21. }
  22. mod assign;
  23. mod autolabel;
  24. mod github_releases;
  25. mod glacier;
  26. mod major_change;
  27. mod milestone_prs;
  28. mod nominate;
  29. mod notification;
  30. mod notify_zulip;
  31. mod ping;
  32. mod prioritize;
  33. mod relabel;
  34. mod rustc_commits;
  35. pub async fn handle(ctx: &Context, event: &Event) -> Vec<HandlerError> {
  36. let config = config::get(&ctx.github, event.repo_name()).await;
  37. let mut errors = Vec::new();
  38. if let (Ok(config), Event::Issue(event)) = (config.as_ref(), event) {
  39. handle_issue(ctx, event, config, &mut errors).await;
  40. }
  41. if let Some(body) = event.comment_body() {
  42. handle_command(ctx, event, &config, body, &mut errors).await;
  43. }
  44. if let Err(e) = notification::handle(ctx, event).await {
  45. log::error!(
  46. "failed to process event {:?} with notification handler: {:?}",
  47. event,
  48. e
  49. );
  50. }
  51. if let Err(e) = rustc_commits::handle(ctx, event).await {
  52. log::error!(
  53. "failed to process event {:?} with rustc_commits handler: {:?}",
  54. event,
  55. e
  56. );
  57. }
  58. if let Err(e) = milestone_prs::handle(ctx, event).await {
  59. log::error!(
  60. "failed to process event {:?} with milestone_prs handler: {:?}",
  61. event,
  62. e
  63. );
  64. }
  65. if let Some(ghr_config) = config
  66. .as_ref()
  67. .ok()
  68. .and_then(|c| c.github_releases.as_ref())
  69. {
  70. if let Err(e) = github_releases::handle(ctx, event, ghr_config).await {
  71. log::error!(
  72. "failed to process event {:?} with github_releases handler: {:?}",
  73. event,
  74. e
  75. );
  76. }
  77. }
  78. errors
  79. }
  80. macro_rules! issue_handlers {
  81. ($($name:ident,)*) => {
  82. async fn handle_issue(
  83. ctx: &Context,
  84. event: &IssuesEvent,
  85. config: &Arc<Config>,
  86. errors: &mut Vec<HandlerError>,
  87. ) {
  88. $(
  89. match $name::parse_input(ctx, event, config.$name.as_ref()) {
  90. Err(err) => errors.push(HandlerError::Message(err)),
  91. Ok(Some(input)) => {
  92. if let Some(config) = &config.$name {
  93. $name::handle_input(ctx, config, event, input).await.unwrap_or_else(|err| errors.push(HandlerError::Other(err)));
  94. } else {
  95. errors.push(HandlerError::Message(format!(
  96. "The feature `{}` is not enabled in this repository.\n\
  97. To enable it add its section in the `triagebot.toml` \
  98. in the root of the repository.",
  99. stringify!($name)
  100. )));
  101. }
  102. }
  103. Ok(None) => {}
  104. })*
  105. }
  106. }
  107. }
  108. // Handle events that happend on issues
  109. //
  110. // This is for events that happends only on issues (e.g. label changes).
  111. // Each module in the list must contain the functions `parse_input` and `handle_input`.
  112. issue_handlers! {
  113. autolabel,
  114. major_change,
  115. notify_zulip,
  116. }
  117. macro_rules! command_handlers {
  118. ($($name:ident: $enum:ident,)*) => {
  119. async fn handle_command(
  120. ctx: &Context,
  121. event: &Event,
  122. config: &Result<Arc<Config>, ConfigurationError>,
  123. body: &str,
  124. errors: &mut Vec<HandlerError>,
  125. ) {
  126. match event {
  127. Event::Issue(e) => if !matches!(e.action, IssuesAction::Opened | IssuesAction::Edited) {
  128. // no change in issue's body for these events, so skip
  129. log::debug!("skipping event, issue was {:?}", e.action);
  130. return;
  131. }
  132. Event::IssueComment(e) => if e.action == IssueCommentAction::Deleted {
  133. // don't execute commands again when comment is deleted
  134. log::debug!("skipping event, comment was {:?}", e.action);
  135. return;
  136. }
  137. Event::Push(_) | Event::Create(_) => {
  138. log::debug!("skipping unsupported event");
  139. return;
  140. }
  141. }
  142. let input = Input::new(&body, &ctx.username);
  143. let commands = if let Some(previous) = event.comment_from() {
  144. let prev_commands = Input::new(&previous, &ctx.username).collect::<Vec<_>>();
  145. input.filter(|cmd| !prev_commands.contains(cmd)).collect::<Vec<_>>()
  146. } else {
  147. input.collect()
  148. };
  149. if commands.is_empty() {
  150. return;
  151. }
  152. let config = match config {
  153. Ok(config) => config,
  154. Err(e @ ConfigurationError::Missing) => {
  155. return errors.push(HandlerError::Message(e.to_string()));
  156. }
  157. Err(e @ ConfigurationError::Toml(_)) => {
  158. return errors.push(HandlerError::Message(e.to_string()));
  159. }
  160. Err(e @ ConfigurationError::Http(_)) => {
  161. return errors.push(HandlerError::Other(e.clone().into()));
  162. }
  163. };
  164. for command in commands {
  165. match command {
  166. $(
  167. Command::$enum(Ok(command)) => {
  168. if let Some(config) = &config.$name {
  169. $name::handle_command(ctx, config, event, command)
  170. .await
  171. .unwrap_or_else(|err| errors.push(HandlerError::Other(err)));
  172. } else {
  173. errors.push(HandlerError::Message(format!(
  174. "The feature `{}` is not enabled in this repository.\n\
  175. To enable it add its section in the `triagebot.toml` \
  176. in the root of the repository.",
  177. stringify!($name)
  178. )));
  179. }
  180. }
  181. Command::$enum(Err(err)) => {
  182. errors.push(HandlerError::Message(format!(
  183. "Parsing {} command in [comment]({}) failed: {}",
  184. stringify!($name),
  185. event.html_url().expect("has html url"),
  186. err
  187. )));
  188. })*
  189. }
  190. }
  191. }
  192. }
  193. }
  194. // Handle commands in comments/issues body
  195. //
  196. // This is for handlers for commands parsed by the `parser` crate.
  197. // Each variant of `parser::command::Command` must be in this list,
  198. // preceded by the module containing the coresponding `handle_command` function
  199. command_handlers! {
  200. assign: Assign,
  201. glacier: Glacier,
  202. nominate: Nominate,
  203. ping: Ping,
  204. prioritize: Prioritize,
  205. relabel: Relabel,
  206. major_change: Second,
  207. }
  208. pub struct Context {
  209. pub github: GithubClient,
  210. pub db: DbClient,
  211. pub username: String,
  212. pub octocrab: Octocrab,
  213. }