Commit 3969a986f5

3969a986f55b8abe6d0226186a868f552466facd

parent: 14f04e7e5c

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2020-06-25 18:44 UTC

config: Add macros to declaratively define a config.

Layout: unified · split

Cargo.lock +20
@@ -1160,6 +1160,25 @@ version = "1.0.1"
11601160source = "registry+https://github.com/rust-lang/crates.io-index"
11611161checksum = "9a7fad362df89617628a7508b3e9d588ade1b0ac31aa25de168193ad999c2dd4"
11621162
1163[[package]]
1164name = "paste"
1165version = "0.1.18"
1166source = "registry+https://github.com/rust-lang/crates.io-index"
1167checksum = "45ca20c77d80be666aef2b45486da86238fabe33e38306bd3118fe4af33fa880"
1168dependencies = [
1169 "paste-impl",
1170 "proc-macro-hack",
1171]
1172
1173[[package]]
1174name = "paste-impl"
1175version = "0.1.18"
1176source = "registry+https://github.com/rust-lang/crates.io-index"
1177checksum = "d95a7db200b97ef370c8e6de0088252f7e0dfff7d047a28528e47456c0fc98b6"
1178dependencies = [
1179 "proc-macro-hack",
1180]
1181
11631182[[package]]
11641183name = "peeking_take_while"
11651184version = "0.1.2"
@@ -2306,6 +2325,7 @@ dependencies = [
23062325 "clap",
23072326 "libc",
23082327 "matrix-sdk",
2328 "paste",
23092329 "tokio",
23102330 "tracing",
23112331 "tracing-subscriber",
Cargo.toml +1
@@ -18,6 +18,7 @@ tracing-subscriber = "0.2.6"
1818async-std = { version = "1.6.2", features = [ "unstable" ] }
1919clap = "2.33.1"
2020async-trait = "0.1.36"
21paste = "0.1"
2122uuid = { version = "0.8.1", features = ["v4"] }
2223
2324weechat = { git = "https://github.com/poljar/rust-weechat", features = ["async-executor"] }
src/commands.rs +3 −3
@@ -3,7 +3,7 @@ use clap::AppSettings as ArgParseSettings;
33use clap::{Arg, ArgMatches, SubCommand};
44use url::Url;
55
6use crate::config::Config;
6use crate::config::ConfigHandle;
77use crate::PLUGIN_NAME;
88use crate::{MatrixServer, Servers};
99use weechat::buffer::Buffer;
@@ -16,7 +16,7 @@ pub struct Commands {
1616
1717struct MatrixCommand {
1818 servers: Servers,
19 config: Config,
19 config: ConfigHandle,
2020}
2121
2222impl MatrixCommand {
@@ -269,7 +269,7 @@ impl Commands {
269269 pub fn hook_all(
270270 weechat: &Weechat,
271271 servers: &Servers,
272 config: &Config,
272 config: &ConfigHandle,
273273 ) -> Commands {
274274 let matrix_settings = CommandSettings::new("matrix")
275275 .description("Matrix chat protocol command.")
src/config.rs +200 −37
@@ -16,69 +16,188 @@
1616//! the section will do so.
1717use crate::{MatrixServer, Servers};
1818use weechat::config::{
19 Conf, ConfigSection, ConfigSectionSettings, OptionChanged,
20 SectionReadCallback,
19 Conf, ConfigOption, ConfigSection, ConfigSectionSettings, OptionChanged,
20 SectionHandle, SectionHandleMut, SectionReadCallback, StringOptionSettings,
2121};
2222use weechat::Weechat;
2323
2424use std::cell::{Ref, RefCell, RefMut};
25use std::ops::{Deref, DerefMut};
2526use std::rc::Rc;
2627
2728#[derive(Clone)]
28pub struct Config {
29 inner: Rc<RefCell<weechat::config::Config>>,
29pub struct ConfigHandle {
30 inner: Rc<RefCell<Config>>,
3031 servers: Servers,
3132}
3233
33impl SectionReadCallback for Config {
34 fn callback(
35 &mut self,
36 _: &Weechat,
37 _: &Conf,
38 section: &mut ConfigSection,
39 option_name: &str,
40 option_value: &str,
41 ) -> OptionChanged {
42 if option_name.is_empty() {
43 return OptionChanged::Error;
34macro_rules! option {
35 (StringOption, $option_name:ident, $description:literal, $default:literal) => {
36 paste::item! {
37 fn [<create_option_ $option_name>](section: &mut SectionHandleMut) {
38 let option_name = stringify!($option_name);
39 let option_settings = StringOptionSettings::new(option_name)
40 .description($description)
41 .default_value($default);
42
43 section.new_string_option(option_settings)
44 .expect(&format!("Can't create option {}", option_name));
45 }
4446 }
4547
46 let option_args: Vec<&str> = option_name.splitn(2, '.').collect();
48 paste::item! {
49 pub fn [<$option_name>](&self) -> String {
50 let option_name = stringify!($option_name);
4751
48 if option_args.len() != 2 {
49 return OptionChanged::Error;
52 let option = self.0.search_option(option_name)
53 .expect(&format!("Couldn't find option {} in section {}",
54 option_name, self.0.name()));
55
56 if let ConfigOption::String(o) = option {
57 o.value().to_string()
58 } else {
59 panic!("Incorect option type for option {} in section {}",
60 option_name, self.0.name());
61 }
62 }
5063 }
64 };
5165
52 let server_name = option_args[0];
66 (EvaluatedStringOption, $option_name:ident, $description:literal, $default:literal) => {
67 paste::item! {
68 fn [<create_option_ $option_name>](section: &mut SectionHandleMut) {
69 let option_name = stringify!($option_name);
70 let option_settings = StringOptionSettings::new(option_name)
71 .description(&format!("{} (note: the content is evaluated, see /help eval)", $description))
72 .default_value($default);
5373
54 {
55 let mut servers_borrow = self.servers.borrow_mut();
74 section.new_string_option(option_settings)
75 .expect(&format!("Can't create option {}", option_name));
76 }
77 }
5678
57 // We are reading the config, if the server doesn't yet exists
58 // we need to create it before setting the option and running
59 // the option change callback.
60 if !servers_borrow.contains_key(server_name) {
61 let server = MatrixServer::new(server_name, &self, section);
62 servers_borrow.insert(server_name.to_owned(), server);
79 paste::item! {
80 pub fn [<$option_name>](&self) -> String {
81 let option_name = stringify!($option_name);
82
83 let option = self.0.search_option(option_name)
84 .expect(&format!("Couldn't find option {} in section {}",
85 option_name, self.0.name()));
86
87 if let ConfigOption::String(o) = option {
88 Weechat::eval_string_expression(&o.value())
89 .expect(&format!(
90 "Can't evaluate string expression for option {} in section {}",
91 option_name,
92 self.0.name())
93 )
94 } else {
95 panic!("Incorect option type for option {} in section {}",
96 option_name, self.0.name());
97 }
6398 }
6499 }
100 };
101}
65102
66 let option = section.search_option(option_name);
103macro_rules! section {
104 ($section:ident { $({$option_type:ident, $option_name:ident, $($option:tt)*}), * }) => {
105 paste::item! {
106 pub struct [<$section:camel Section>]<'a>(SectionHandle<'a>);
67107
68 if let Some(o) = option {
69 o.set(option_value, true)
70 } else {
71 OptionChanged::NotFound
108 impl<'a> [<$section:camel Section>]<'a> {
109 pub fn create(config: &mut Config) {
110 let section_settings = ConfigSectionSettings::new(stringify!($section));
111
112 let mut $section = config.new_section(section_settings)
113 .expect(&format!("Can't create config section {}", stringify!($section)));
114
115 [<$section:camel Section>]::create_options(&mut $section);
116 }
117
118 pub fn create_options(section: &mut SectionHandleMut) {
119 $(
120 [<$section:camel Section>]::[<create_option_ $option_name>](section);
121 )*
122 }
123
124 $(
125 option!($option_type, $option_name, $($option)*);
126 )*
127 }
128 }
129 }
130}
131
132macro_rules! config {
133 ($(Section $section:ident { $({$($option:tt)*}), * }), *) => {
134 pub struct Config(weechat::config::Config);
135
136 impl Deref for Config {
137 type Target = weechat::config::Config;
138
139 fn deref(&self) -> &Self::Target {
140 &self.0
141 }
142 }
143
144 impl DerefMut for Config {
145 fn deref_mut(&mut self) -> &mut Self::Target {
146 &mut self.0
147 }
148 }
149
150 impl Config {
151 fn new(config: weechat::config::Config) -> Self {
152 let mut config = Config(config);
153 config.create_sections();
154
155 config
156 }
157
158 paste::item! {
159 fn create_sections(&mut self) {
160 $(
161 paste::expr! { [<$section:camel Section>]::create(self) };
162 )*
163 }
164 }
165
166 paste::item! {
167 $(
168 pub fn $section(&self) -> [<$section:camel Section>] {
169 let section_name = stringify!($section);
170 let section = self.0.search_section(section_name)
171 .expect(&format!("Couldn't find section {}", section_name));
172
173 paste::item! { [<$section:camel Section>](section) }
174 }
175 )*
176 }
72177 }
178
179 $(
180 section!($section { $({$($option)*}), * });
181 )*
73182 }
74183}
75184
76impl Config {
77 pub fn new(_weechat: &Weechat, servers: &Servers) -> Config {
185config!(
186 Section look {
187 {StringOption, encrypted_room_sign,
188 "A sign that is used to show that the current room is encrypted",
189 "🔒"}
190 }
191);
192
193impl ConfigHandle {
194 pub fn new(_weechat: &Weechat, servers: &Servers) -> ConfigHandle {
78195 let config = Weechat::config_new("matrix-rust")
79196 .expect("Can't create new config");
80197
81 let config = Config {
198 let config = Config::new(config);
199
200 let config = ConfigHandle {
82201 inner: Rc::new(RefCell::new(config)),
83202 servers: servers.clone(),
84203 };
@@ -95,6 +214,7 @@ impl Config {
95214 },
96215 )
97216 .set_read_callback(config.clone());
217
98218 {
99219 let mut config_borrow = config.borrow_mut();
100220
@@ -106,11 +226,54 @@ impl Config {
106226 config
107227 }
108228
109 pub fn borrow(&self) -> Ref<'_, weechat::config::Config> {
229 pub fn borrow(&self) -> Ref<'_, Config> {
110230 self.inner.borrow()
111231 }
112232
113 pub fn borrow_mut(&self) -> RefMut<'_, weechat::config::Config> {
233 pub fn borrow_mut(&self) -> RefMut<'_, Config> {
114234 self.inner.borrow_mut()
115235 }
116236}
237
238impl SectionReadCallback for ConfigHandle {
239 fn callback(
240 &mut self,
241 _: &Weechat,
242 _: &Conf,
243 section: &mut ConfigSection,
244 option_name: &str,
245 option_value: &str,
246 ) -> OptionChanged {
247 if option_name.is_empty() {
248 return OptionChanged::Error;
249 }
250
251 let option_args: Vec<&str> = option_name.splitn(2, '.').collect();
252
253 if option_args.len() != 2 {
254 return OptionChanged::Error;
255 }
256
257 let server_name = option_args[0];
258
259 {
260 let mut servers_borrow = self.servers.borrow_mut();
261
262 // We are reading the config, if the server doesn't yet exists
263 // we need to create it before setting the option and running
264 // the option change callback.
265 if !servers_borrow.contains_key(server_name) {
266 let server = MatrixServer::new(server_name, &self, section);
267 servers_borrow.insert(server_name.to_owned(), server);
268 }
269 }
270
271 let option = section.search_option(option_name);
272
273 if let Some(o) = option {
274 o.set(option_value, true)
275 } else {
276 OptionChanged::NotFound
277 }
278 }
279}
src/lib.rs +34 −5
@@ -11,10 +11,14 @@ use std::collections::HashMap;
1111use std::rc::Rc;
1212use tracing_subscriber;
1313
14use weechat::{weechat_plugin, ArgsWeechat, Weechat, WeechatPlugin};
14use weechat::{
15 buffer::Buffer,
16 hooks::{BarItemCallback, BarItemHandle},
17 weechat_plugin, ArgsWeechat, Weechat, WeechatPlugin,
18};
1519
1620use crate::commands::Commands;
17use crate::config::Config;
21use crate::config::ConfigHandle;
1822use crate::server::MatrixServer;
1923
2024const PLUGIN_NAME: &str = "matrix";
@@ -41,7 +45,9 @@ struct Matrix {
4145 #[used]
4246 commands: Commands,
4347 #[used]
44 config: Config,
48 config: ConfigHandle,
49 #[used]
50 status_bar: BarItemHandle,
4551}
4652
4753impl Matrix {
@@ -58,7 +64,7 @@ impl Matrix {
5864
5965 fn create_default_server(
6066 servers: &mut HashMap<String, MatrixServer>,
61 config: &Config,
67 config: &ConfigHandle,
6268 ) {
6369 let server_name = "localhost";
6470 let mut config_borrow = config.borrow_mut();
@@ -70,11 +76,33 @@ impl Matrix {
7076 }
7177}
7278
79impl BarItemCallback for Servers {
80 fn callback(&mut self, _: &Weechat, buffer: &Buffer) -> String {
81 let servers = self.borrow();
82
83 for server in servers.values() {
84 let server = server.inner();
85 for room in server.room_buffers().values() {
86 let room_buffer = room.weechat_buffer();
87 if &room_buffer == buffer {
88 if room.room().is_encrypted() {
89 return server.config().look().encrypted_room_sign();
90 }
91 }
92 }
93 }
94
95 "".to_owned()
96 }
97}
98
7399impl WeechatPlugin for Matrix {
74100 fn init(weechat: &Weechat, _args: ArgsWeechat) -> Result<Self, ()> {
75101 let servers = Servers::new();
76 let config = Config::new(weechat, &servers);
102 let config = ConfigHandle::new(weechat, &servers);
77103 let commands = Commands::hook_all(weechat, &servers, &config);
104 let status_bar =
105 Weechat::new_bar_item("matrix_modes", servers.clone())?;
78106
79107 tracing_subscriber::fmt().with_writer(debug::Debug).init();
80108
@@ -82,6 +110,7 @@ impl WeechatPlugin for Matrix {
82110 servers: servers.clone(),
83111 commands,
84112 config: config.clone(),
113 status_bar,
85114 };
86115
87116 {
src/room_buffer.rs +1 −1
@@ -162,7 +162,7 @@ impl RoomBuffer {
162162 self.inner.room.borrow()
163163 }
164164
165 pub fn weechat_buffer(&mut self) -> Buffer {
165 pub fn weechat_buffer(&self) -> Buffer {
166166 self.buffer_handle
167167 .upgrade()
168168 .expect("Buffer got closed but Room is still lingering around")
src/server.rs +16 −4
@@ -52,7 +52,7 @@
5252//! that processing events will not block the Weechat mainloop for too long.
5353use async_std::sync::channel as async_channel;
5454use async_std::sync::{Receiver, Sender};
55use std::cell::RefCell;
55use std::cell::{Ref, RefCell};
5656use std::collections::HashMap;
5757use std::path::PathBuf;
5858use std::rc::{Rc, Weak};
@@ -80,8 +80,8 @@ use weechat::JoinHandle;
8080use weechat::Weechat;
8181
8282use crate::room_buffer::RoomBuffer;
83use crate::Config;
8483use crate::PLUGIN_NAME;
84use crate::{config::Config, ConfigHandle};
8585
8686const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
8787
@@ -151,7 +151,7 @@ pub(crate) struct InnerServer {
151151 server_name: Rc<String>,
152152 room_buffers: HashMap<RoomId, RoomBuffer>,
153153 settings: ServerSettings,
154 config: Config,
154 config: ConfigHandle,
155155 client: Option<Client>,
156156 login_state: Option<LoginState>,
157157 connected_state: Rc<RefCell<Option<Connection>>>,
@@ -160,7 +160,7 @@ pub(crate) struct InnerServer {
160160impl MatrixServer {
161161 pub fn new(
162162 name: &str,
163 config: &Config,
163 config: &ConfigHandle,
164164 server_section: &mut ConfigSection,
165165 ) -> Self {
166166 let server_name = Rc::new(name.to_owned());
@@ -188,6 +188,10 @@ impl MatrixServer {
188188 &self.server_name
189189 }
190190
191 pub fn inner(&self) -> Ref<'_, InnerServer> {
192 self.inner.borrow()
193 }
194
191195 pub fn parse_homeserver_url(value: String) -> Result<(), String> {
192196 let url = Url::parse(&value);
193197
@@ -421,6 +425,14 @@ impl InnerServer {
421425 self.room_buffers.get_mut(room_id).unwrap()
422426 }
423427
428 pub fn room_buffers(&self) -> &HashMap<RoomId, RoomBuffer> {
429 &self.room_buffers
430 }
431
432 pub fn config(&self) -> Ref<Config> {
433 self.config.borrow()
434 }
435
424436 fn restore_room(&mut self, room: Room) {
425437 let homeserver = self
426438 .settings