handlers.rs 8.1 KB

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