src/commands/topic.rs
158 lines · 4653 bytes
1use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg};
2use weechat::{
3 buffer::Buffer,
4 hooks::{Command, CommandCallback, CommandSettings},
5 Args, Prefix, 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 let room = room.room().clone();
91
92 Weechat::spawn(async move {
93 if let Err(error) = room.set_room_topic(&topic).await {
94 Weechat::print(&format!(
95 "{}Failed to set room topic: {}",
96 Weechat::prefix(Prefix::Error),
97 error
98 ));
99 }
100 })
101 .detach();
102 } else {
103 Weechat::print(
104 "The /topic command needs to be run in a Matrix room buffer.",
105 );
106 }
107 }
108}
109
110impl CommandCallback for TopicCommand {
111 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
112 parse_and_run(Self::parser(), arguments, |matches| match Self::action(
113 matches,
114 ) {
115 TopicAction::Show => self.show_topic(buffer),
116 TopicAction::Clear => self.set_topic(buffer, String::new()),
117 TopicAction::Set(topic) => self.set_topic(buffer, topic),
118 });
119 }
120}
121
122#[cfg(test)]
123mod tests {
124 use super::{TopicAction, TopicCommand};
125
126 fn parse(args: &[&str]) -> TopicAction {
127 let matches = TopicCommand::parser()
128 .get_matches_from_safe(args)
129 .expect("topic arguments should parse");
130
131 TopicCommand::action(&matches)
132 }
133
134 #[test]
135 fn omitted_topic_shows_current_topic() {
136 assert_eq!(TopicAction::Show, parse(&["topic"]));
137 }
138
139 #[test]
140 fn clear_flag_explicitly_clears_topic() {
141 assert_eq!(TopicAction::Clear, parse(&["topic", "--clear"]));
142 }
143
144 #[test]
145 fn clear_flag_rejects_topic_text() {
146 assert!(TopicCommand::parser()
147 .get_matches_from_safe(&["topic", "--clear", "not empty"])
148 .is_err());
149 }
150
151 #[test]
152 fn non_empty_topic_selects_set_action() {
153 assert_eq!(
154 TopicAction::Set("new room topic".to_owned()),
155 parse(&["topic", "new", "room", "topic"])
156 );
157 }
158}