src/commands/topic.rs
147 lines · 4300 bytes
14 symbols in this file
1use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg};
2use weechat::{
3 buffer::Buffer,
4 hooks::{Command, CommandCallback, CommandSettings},
5 Args, Weechat,
6};
7
8use super::parse_and_run;
9use crate::Servers;
10
11#[derive(Debug, Eq, PartialEq)]
12enum TopicAction {
13 Show,
14 Clear,
15 Set(String),
16}
17
18pub struct TopicCommand {
19 servers: Servers,
20}
21
22impl TopicCommand {
23 pub fn create(servers: &Servers) -> Result<Command, ()> {
24 let settings = CommandSettings::new("topic")
25 .description("Show, set, or clear the current Matrix room topic.")
26 .add_argument("[--clear] [topic]")
27 .arguments_description(
28 "topic: The new topic for the current room. Omit it to show the current topic.\n\
29 --clear: Clear the topic.",
30 );
31
32 Command::new(
33 settings,
34 TopicCommand {
35 servers: servers.clone(),
36 },
37 )
38 }
39
40 fn parser() -> Argparse<'static, 'static> {
41 Argparse::new("topic")
42 .about("Show, set, or clear the current Matrix room topic.")
43 .settings(&[
44 ArgParseSettings::DisableHelpFlags,
45 ArgParseSettings::DisableVersion,
46 ])
47 .arg(
48 Arg::with_name("clear")
49 .long("clear")
50 .help("Clear the current room topic.")
51 .conflicts_with("topic"),
52 )
53 .arg(
54 Arg::with_name("topic")
55 .multiple(true)
56 .allow_hyphen_values(true),
57 )
58 }
59
60 fn action(matches: &clap::ArgMatches) -> TopicAction {
61 if matches.is_present("clear") {
62 TopicAction::Clear
63 } else {
64 matches
65 .values_of("topic")
66 .map(|t| TopicAction::Set(t.collect::<Vec<_>>().join(" ")))
67 .unwrap_or(TopicAction::Show)
68 }
69 }
70
71 fn show_topic(&self, buffer: &Buffer) {
72 if let Some(room) = self.servers.find_room(buffer) {
73 match room.room().topic() {
74 Some(topic) if !topic.is_empty() => {
75 buffer.print(&format!("Topic: {}", topic));
76 }
77 _ => {
78 buffer.print("No topic is set.");
79 }
80 }
81 } else {
82 Weechat::print(
83 "The /topic command needs to be run in a Matrix room buffer.",
84 );
85 }
86 }
87
88 fn set_topic(&self, buffer: &Buffer, topic: String) {
89 if let Some(room) = self.servers.find_room(buffer) {
90 Weechat::spawn(async move { room.set_topic(topic).await }).detach();
91 } else {
92 Weechat::print(
93 "The /topic command needs to be run in a Matrix room buffer.",
94 );
95 }
96 }
97}
98
99impl CommandCallback for TopicCommand {
100 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
101 parse_and_run(Self::parser(), arguments, |matches| match Self::action(
102 matches,
103 ) {
104 TopicAction::Show => self.show_topic(buffer),
105 TopicAction::Clear => self.set_topic(buffer, String::new()),
106 TopicAction::Set(topic) => self.set_topic(buffer, topic),
107 });
108 }
109}
110
111#[cfg(test)]
112mod tests {
113 use super::{TopicAction, TopicCommand};
114
115 fn parse(args: &[&str]) -> TopicAction {
116 let matches = TopicCommand::parser()
117 .get_matches_from_safe(args)
118 .expect("topic arguments should parse");
119
120 TopicCommand::action(&matches)
121 }
122
123 #[test]
124 fn omitted_topic_shows_current_topic() {
125 assert_eq!(TopicAction::Show, parse(&["topic"]));
126 }
127
128 #[test]
129 fn clear_flag_explicitly_clears_topic() {
130 assert_eq!(TopicAction::Clear, parse(&["topic", "--clear"]));
131 }
132
133 #[test]
134 fn clear_flag_rejects_topic_text() {
135 assert!(TopicCommand::parser()
136 .get_matches_from_safe(&["topic", "--clear", "not empty"])
137 .is_err());
138 }
139
140 #[test]
141 fn non_empty_topic_selects_set_action() {
142 assert_eq!(
143 TopicAction::Set("new room topic".to_owned()),
144 parse(&["topic", "new", "room", "topic"])
145 );
146 }
147}