handlers.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. use crate::config::{self, Config, ConfigurationError};
  2. use crate::github::{Event, GithubClient, IssueCommentAction, IssuesAction, IssuesEvent};
  3. use octocrab::Octocrab;
  4. use parser::command::{assign::AssignCommand, Command, Input};
  5. use std::fmt;
  6. use std::sync::Arc;
  7. use tracing as log;
  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. pub mod docs_update;
  26. mod github_releases;
  27. mod glacier;
  28. mod major_change;
  29. mod mentions;
  30. mod milestone_prs;
  31. mod no_merges;
  32. mod nominate;
  33. mod note;
  34. mod notification;
  35. mod notify_zulip;
  36. mod ping;
  37. mod prioritize;
  38. pub mod pull_requests_assignment_update;
  39. mod relabel;
  40. mod review_requested;
  41. mod review_submitted;
  42. mod rfc_helper;
  43. pub mod rustc_commits;
  44. mod shortcut;
  45. pub mod types_planning_updates;
  46. mod validate_config;
  47. pub async fn handle(ctx: &Context, event: &Event) -> Vec<HandlerError> {
  48. let config = config::get(&ctx.github, event.repo()).await;
  49. if let Err(e) = &config {
  50. log::warn!("configuration error {}: {e}", event.repo().full_name);
  51. }
  52. let mut errors = Vec::new();
  53. if let (Ok(config), Event::Issue(event)) = (config.as_ref(), event) {
  54. handle_issue(ctx, event, config, &mut errors).await;
  55. }
  56. if let Some(body) = event.comment_body() {
  57. handle_command(ctx, event, &config, body, &mut errors).await;
  58. }
  59. if let Err(e) = notification::handle(ctx, event).await {
  60. log::error!(
  61. "failed to process event {:?} with notification handler: {:?}",
  62. event,
  63. e
  64. );
  65. }
  66. if let Err(e) = rustc_commits::handle(ctx, event).await {
  67. log::error!(
  68. "failed to process event {:?} with rustc_commits handler: {:?}",
  69. event,
  70. e
  71. );
  72. }
  73. if let Err(e) = milestone_prs::handle(ctx, event).await {
  74. log::error!(
  75. "failed to process event {:?} with milestone_prs handler: {:?}",
  76. event,
  77. e
  78. );
  79. }
  80. if let Err(e) = rfc_helper::handle(ctx, event).await {
  81. log::error!(
  82. "failed to process event {:?} with rfc_helper handler: {:?}",
  83. event,
  84. e
  85. );
  86. }
  87. if let Some(config) = config
  88. .as_ref()
  89. .ok()
  90. .and_then(|c| c.review_submitted.as_ref())
  91. {
  92. if let Err(e) = review_submitted::handle(ctx, event, config).await {
  93. log::error!(
  94. "failed to process event {:?} with review_submitted handler: {:?}",
  95. event,
  96. e
  97. )
  98. }
  99. }
  100. if let Some(ghr_config) = config
  101. .as_ref()
  102. .ok()
  103. .and_then(|c| c.github_releases.as_ref())
  104. {
  105. if let Err(e) = github_releases::handle(ctx, event, ghr_config).await {
  106. log::error!(
  107. "failed to process event {:?} with github_releases handler: {:?}",
  108. event,
  109. e
  110. );
  111. }
  112. }
  113. errors
  114. }
  115. macro_rules! issue_handlers {
  116. ($($name:ident,)*) => {
  117. async fn handle_issue(
  118. ctx: &Context,
  119. event: &IssuesEvent,
  120. config: &Arc<Config>,
  121. errors: &mut Vec<HandlerError>,
  122. ) {
  123. $(
  124. match $name::parse_input(ctx, event, config.$name.as_ref()).await {
  125. Err(err) => errors.push(HandlerError::Message(err)),
  126. Ok(Some(input)) => {
  127. if let Some(config) = &config.$name {
  128. $name::handle_input(ctx, config, event, input).await.unwrap_or_else(|err| errors.push(HandlerError::Other(err)));
  129. } else {
  130. errors.push(HandlerError::Message(format!(
  131. "The feature `{}` is not enabled in this repository.\n\
  132. To enable it add its section in the `triagebot.toml` \
  133. in the root of the repository.",
  134. stringify!($name)
  135. )));
  136. }
  137. }
  138. Ok(None) => {}
  139. })*
  140. }
  141. }
  142. }
  143. // Handle events that happened on issues
  144. //
  145. // This is for events that happen only on issues (e.g. label changes).
  146. // Each module in the list must contain the functions `parse_input` and `handle_input`.
  147. issue_handlers! {
  148. assign,
  149. autolabel,
  150. major_change,
  151. mentions,
  152. no_merges,
  153. notify_zulip,
  154. review_requested,
  155. validate_config,
  156. }
  157. macro_rules! command_handlers {
  158. ($($name:ident: $enum:ident,)*) => {
  159. async fn handle_command(
  160. ctx: &Context,
  161. event: &Event,
  162. config: &Result<Arc<Config>, ConfigurationError>,
  163. body: &str,
  164. errors: &mut Vec<HandlerError>,
  165. ) {
  166. match event {
  167. // always handle new PRs / issues
  168. Event::Issue(IssuesEvent { action: IssuesAction::Opened, .. }) => {},
  169. Event::Issue(IssuesEvent { action: IssuesAction::Edited, .. }) => {
  170. // if the issue was edited, but we don't get a `changes[body]` diff, it means only the title was edited, not the body.
  171. // don't process the same commands twice.
  172. if event.comment_from().is_none() {
  173. log::debug!("skipping title-only edit event");
  174. return;
  175. }
  176. },
  177. Event::Issue(e) => {
  178. // no change in issue's body for these events, so skip
  179. log::debug!("skipping event, issue was {:?}", e.action);
  180. return;
  181. }
  182. Event::IssueComment(e) => if e.action == IssueCommentAction::Deleted {
  183. // don't execute commands again when comment is deleted
  184. log::debug!("skipping event, comment was {:?}", e.action);
  185. return;
  186. }
  187. Event::Push(_) | Event::Create(_) => {
  188. log::debug!("skipping unsupported event");
  189. return;
  190. }
  191. }
  192. let input = Input::new(&body, vec![&ctx.username, "triagebot"]);
  193. let commands = if let Some(previous) = event.comment_from() {
  194. let prev_commands = Input::new(&previous, vec![&ctx.username, "triagebot"]).collect::<Vec<_>>();
  195. input.filter(|cmd| !prev_commands.contains(cmd)).collect::<Vec<_>>()
  196. } else {
  197. input.collect()
  198. };
  199. log::info!("Comment parsed to {:?}", commands);
  200. if commands.is_empty() {
  201. return;
  202. }
  203. let config = match config {
  204. Ok(config) => config,
  205. Err(e @ ConfigurationError::Missing) => {
  206. // r? is conventionally used to mean "hey, can you review"
  207. // even if the repo doesn't have a triagebot.toml. In that
  208. // case, just ignore it.
  209. if commands
  210. .iter()
  211. .all(|cmd| matches!(cmd, Command::Assign(Ok(AssignCommand::ReviewName { .. }))))
  212. {
  213. return;
  214. }
  215. return errors.push(HandlerError::Message(e.to_string()));
  216. }
  217. Err(e @ ConfigurationError::Toml(_)) => {
  218. return errors.push(HandlerError::Message(e.to_string()));
  219. }
  220. Err(e @ ConfigurationError::Http(_)) => {
  221. return errors.push(HandlerError::Other(e.clone().into()));
  222. }
  223. };
  224. for command in commands {
  225. match command {
  226. $(
  227. Command::$enum(Ok(command)) => {
  228. if let Some(config) = &config.$name {
  229. $name::handle_command(ctx, config, event, command)
  230. .await
  231. .unwrap_or_else(|err| errors.push(HandlerError::Other(err)));
  232. } else {
  233. errors.push(HandlerError::Message(format!(
  234. "The feature `{}` is not enabled in this repository.\n\
  235. To enable it add its section in the `triagebot.toml` \
  236. in the root of the repository.",
  237. stringify!($name)
  238. )));
  239. }
  240. }
  241. Command::$enum(Err(err)) => {
  242. errors.push(HandlerError::Message(format!(
  243. "Parsing {} command in [comment]({}) failed: {}",
  244. stringify!($name),
  245. event.html_url().expect("has html url"),
  246. err
  247. )));
  248. })*
  249. }
  250. }
  251. }
  252. }
  253. }
  254. // Handle commands in comments/issues body
  255. //
  256. // This is for handlers for commands parsed by the `parser` crate.
  257. // Each variant of `parser::command::Command` must be in this list,
  258. // preceded by the module containing the coresponding `handle_command` function
  259. command_handlers! {
  260. assign: Assign,
  261. glacier: Glacier,
  262. nominate: Nominate,
  263. ping: Ping,
  264. prioritize: Prioritize,
  265. relabel: Relabel,
  266. major_change: Second,
  267. shortcut: Shortcut,
  268. close: Close,
  269. note: Note,
  270. }
  271. pub struct Context {
  272. pub github: GithubClient,
  273. pub db: crate::db::ClientPool,
  274. pub username: String,
  275. pub octocrab: Octocrab,
  276. }