command.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. use crate::code_block::ColorCodeBlocks;
  2. use crate::error::Error;
  3. use crate::token::{Token, Tokenizer};
  4. pub mod assign;
  5. pub mod nominate;
  6. pub mod ping;
  7. pub mod prioritize;
  8. pub mod relabel;
  9. pub mod second;
  10. pub fn find_commmand_start(input: &str, bot: &str) -> Option<usize> {
  11. input.find(&format!("@{}", bot))
  12. }
  13. #[derive(Debug)]
  14. pub enum Command<'a> {
  15. Relabel(Result<relabel::RelabelCommand, Error<'a>>),
  16. Assign(Result<assign::AssignCommand, Error<'a>>),
  17. Ping(Result<ping::PingCommand, Error<'a>>),
  18. Nominate(Result<nominate::NominateCommand, Error<'a>>),
  19. Prioritize(Result<prioritize::PrioritizeCommand, Error<'a>>),
  20. Second(Result<second::SecondCommand, Error<'a>>),
  21. None,
  22. }
  23. #[derive(Debug)]
  24. pub struct Input<'a> {
  25. all: &'a str,
  26. parsed: usize,
  27. code: ColorCodeBlocks,
  28. bot: &'a str,
  29. }
  30. fn parse_single_command<'a, T, F, M>(
  31. parse: F,
  32. mapper: M,
  33. tokenizer: &Tokenizer<'a>,
  34. ) -> Option<(Tokenizer<'a>, Command<'a>)>
  35. where
  36. F: FnOnce(&mut Tokenizer<'a>) -> Result<Option<T>, Error<'a>>,
  37. M: FnOnce(Result<T, Error<'a>>) -> Command<'a>,
  38. T: std::fmt::Debug,
  39. {
  40. let mut tok = tokenizer.clone();
  41. let res = parse(&mut tok);
  42. log::info!("parsed {:?} command: {:?}", std::any::type_name::<T>(), res);
  43. match res {
  44. Ok(None) => None,
  45. Ok(Some(v)) => Some((tok, mapper(Ok(v)))),
  46. Err(err) => Some((tok, mapper(Err(err)))),
  47. }
  48. }
  49. impl<'a> Input<'a> {
  50. pub fn new(input: &'a str, bot: &'a str) -> Input<'a> {
  51. Input {
  52. all: input,
  53. parsed: 0,
  54. code: ColorCodeBlocks::new(input),
  55. bot,
  56. }
  57. }
  58. pub fn parse_command(&mut self) -> Command<'a> {
  59. let start = match find_commmand_start(&self.all[self.parsed..], self.bot) {
  60. Some(pos) => pos,
  61. None => return Command::None,
  62. };
  63. self.parsed += start;
  64. let mut tok = Tokenizer::new(&self.all[self.parsed..]);
  65. assert_eq!(
  66. tok.next_token().unwrap(),
  67. Some(Token::Word(&format!("@{}", self.bot)))
  68. );
  69. log::info!("identified potential command");
  70. let mut success = vec![];
  71. let original_tokenizer = tok.clone();
  72. success.extend(parse_single_command(
  73. relabel::RelabelCommand::parse,
  74. Command::Relabel,
  75. &original_tokenizer,
  76. ));
  77. success.extend(parse_single_command(
  78. assign::AssignCommand::parse,
  79. Command::Assign,
  80. &original_tokenizer,
  81. ));
  82. success.extend(parse_single_command(
  83. ping::PingCommand::parse,
  84. Command::Ping,
  85. &original_tokenizer,
  86. ));
  87. success.extend(parse_single_command(
  88. nominate::NominateCommand::parse,
  89. Command::Nominate,
  90. &original_tokenizer,
  91. ));
  92. success.extend(parse_single_command(
  93. prioritize::PrioritizeCommand::parse,
  94. Command::Prioritize,
  95. &original_tokenizer,
  96. ));
  97. success.extend(parse_single_command(
  98. second::SecondCommand::parse,
  99. Command::Second,
  100. &original_tokenizer,
  101. ));
  102. if success.len() > 1 {
  103. panic!(
  104. "succeeded parsing {:?} to multiple commands: {:?}",
  105. &self.all[self.parsed..],
  106. success
  107. );
  108. }
  109. if self
  110. .code
  111. .overlaps_code((self.parsed)..(self.parsed + tok.position()))
  112. .is_some()
  113. {
  114. log::info!("command overlaps code; code: {:?}", self.code);
  115. return Command::None;
  116. }
  117. match success.pop() {
  118. Some((mut tok, c)) => {
  119. // if we errored out while parsing the command do not move the input forwards
  120. if c.is_ok() {
  121. self.parsed += tok.position();
  122. }
  123. c
  124. }
  125. None => Command::None,
  126. }
  127. }
  128. }
  129. impl<'a> Command<'a> {
  130. pub fn is_ok(&self) -> bool {
  131. match self {
  132. Command::Relabel(r) => r.is_ok(),
  133. Command::Assign(r) => r.is_ok(),
  134. Command::Ping(r) => r.is_ok(),
  135. Command::Nominate(r) => r.is_ok(),
  136. Command::Prioritize(r) => r.is_ok(),
  137. Command::Second(r) => r.is_ok(),
  138. Command::None => true,
  139. }
  140. }
  141. pub fn is_err(&self) -> bool {
  142. !self.is_ok()
  143. }
  144. pub fn is_none(&self) -> bool {
  145. match self {
  146. Command::None => true,
  147. _ => false,
  148. }
  149. }
  150. }
  151. #[test]
  152. fn errors_outside_command_are_fine() {
  153. let input =
  154. "haha\" unterminated quotes @bot modify labels: +bug. Terminating after the command";
  155. let mut input = Input::new(input, "bot");
  156. assert!(input.parse_command().is_ok());
  157. }
  158. #[test]
  159. fn code_1() {
  160. let input = "`@bot modify labels: +bug.`";
  161. let mut input = Input::new(input, "bot");
  162. assert!(input.parse_command().is_none());
  163. }
  164. #[test]
  165. fn code_2() {
  166. let input = "```
  167. @bot modify labels: +bug.
  168. ```";
  169. let mut input = Input::new(input, "bot");
  170. assert!(input.parse_command().is_none());
  171. }
  172. #[test]
  173. fn move_input_along() {
  174. let input = "@bot modify labels: +bug. Afterwards, delete the world.";
  175. let mut input = Input::new(input, "bot");
  176. let parsed = input.parse_command();
  177. assert!(parsed.is_ok());
  178. assert_eq!(&input.all[input.parsed..], " Afterwards, delete the world.");
  179. }
  180. #[test]
  181. fn move_input_along_1() {
  182. let input = "@bot modify labels\": +bug. Afterwards, delete the world.";
  183. let mut input = Input::new(input, "bot");
  184. assert!(input.parse_command().is_err());
  185. // don't move input along if parsing the command fails
  186. assert_eq!(input.parsed, 0);
  187. }