command.rs 6.5 KB

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