afrim-config 0.4.4

Handle the configuration of the afrim input method.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
#![deny(missing_docs)]
//! Library to manage the configuration of the afrim input method.
//!
//! It's based on the top of the [`toml`](toml) crate.
//!
//! # Example
//!
//! ```no_run
//! use afrim_config::Config;
//! use std::path::Path;
//!
//! let filepath = Path::new("./data/config_sample.toml");
//! let conf = Config::from_file(&filepath).unwrap();
//!
//! # assert_eq!(conf.extract_data().keys().len(), 23);
//! # #[cfg(feature = "rhai")]
//! # assert_eq!(conf.extract_translators().unwrap().keys().len(), 2);
//! # assert_eq!(conf.extract_translation().keys().len(), 4);
//! ```
//!
//! In case that you want control the filesystem (reading of file), you can use the
//! [`Config::from_filesystem`](crate::Config::from_filesystem) method.
//!
//! # Example
//!
//! ```
//! use afrim_config::{Config, FileSystem};
//! use std::{error, path::Path, string::String};
//!
//! // Implements a custom filesystem.
//! struct File {
//!     source: String,
//! }
//!
//! impl File {
//!     pub fn new(source: String) -> Self {
//!         Self { source }
//!     }
//! }
//!
//! impl FileSystem for File {
//!     fn read_to_string(&self, filepath: &Path) -> Result<String, Box<dyn error::Error>> {
//!         Ok(self.source.to_string())
//!     }
//! }
//!
//! // Sets the config file.
//! let config_file = File::new(r#"
//! [core]
//! auto_commit = false
//!
//! [data]
//! "n*" = "ŋ"
//! "#.to_owned());
//!
//! // Loads the config file.
//! let config = Config::from_filesystem(&Path::new("."), &config_file).unwrap();
//!
//! assert_eq!(config.core.clone().unwrap().auto_commit, Some(false));
//! // Note that the auto_capitalize is enabled by default.
//! assert_eq!(
//!     Vec::from_iter(config.extract_data().into_iter()),
//!     vec![("n*".to_owned(), "ŋ".to_owned()), ("N*".to_owned(), "Ŋ".to_owned())]
//! );
//! ```

use indexmap::IndexMap;
#[cfg(feature = "rhai")]
use rhai::{Engine, AST};
use serde::Deserialize;
use std::result::Result;
use std::{error, fs, path::Path};
use toml::{self};

/// Trait to customize the filesystem.
pub trait FileSystem {
    /// Alternative to the fs::read_to_string.
    fn read_to_string(&self, filepath: &Path) -> Result<String, Box<dyn error::Error>>;
}

// Representation of the std::fs.
struct StdFileSystem;

impl FileSystem for StdFileSystem {
    fn read_to_string(&self, filepath: &Path) -> Result<String, Box<dyn error::Error>> {
        Ok(fs::read_to_string(filepath)?)
    }
}

/// Holds information about a configuration.
///
/// # Example
///
/// ```no_run
/// # use afrim_config::{Config, FileSystem};
/// # use std::{error, path::Path, string::String};
/// #
/// # // Implements a custom filesystem.
/// # struct File {
/// #     source: String,
/// # }
/// #
/// # impl File {
/// #     pub fn new(source: String) -> Self {
/// #         Self { source }
/// #     }
/// # }
/// #
/// # impl FileSystem for File {
/// #     fn read_to_string(&self, filepath: &Path) -> Result<String, Box<dyn error::Error>> {
/// #         Ok(self.source.to_string())
/// #     }
/// # }
/// #
/// # // Sets the config file.
/// # let config_file = File::new(r#"
/// [info]
/// description = "Sample Config File"
/// version = "2023-10-02"
///
/// [data]
/// 2a_ = "á̠"
/// ".?" = { value = "ʔ", alias = ["?."] }
/// emoji = { path = "./emoji.toml" }
///
/// [translation]
/// hey = "hi"
/// hi = { value = "hello", alias = ["hey"] }
/// hola = { values = ["hello"], alias = [] }
/// dictionary = { path = "./dictionary.toml" }
///
/// [translator]
/// date = "./scripts/datetime/date.rhai"
/// # "#.to_owned());
///
/// # // Loads the config file.
/// # Config::from_filesystem(&Path::new("."), &config_file).unwrap();
/// ```
#[derive(Deserialize, Debug, Clone)]
pub struct Config {
    /// The core config.
    pub core: Option<CoreConfig>,
    data: Option<IndexMap<String, Data>>,
    #[cfg(feature = "rhai")]
    translators: Option<IndexMap<String, Data>>,
    translation: Option<IndexMap<String, Data>>,
}

/// Core information about a configuration.
///
/// # Example
///
/// ```
/// # use afrim_config::{Config, FileSystem};
/// # use std::{error, path::Path, string::String};
/// #
/// # // Implements a custom filesystem.
/// # struct File {
/// #     source: String,
/// # }
/// #
/// # impl File {
/// #     pub fn new(source: String) -> Self {
/// #         Self { source }
/// #     }
/// # }
/// #
/// # impl FileSystem for File {
/// #     fn read_to_string(&self, filepath: &Path) -> Result<String, Box<dyn error::Error>> {
/// #         Ok(self.source.to_string())
/// #     }
/// # }
/// #
/// # // Sets the config file.
/// # let config_file = File::new(r#"
/// [core]
/// buffer_size = 32
/// auto_capitalize = false
/// page_size = 10
/// auto_commit = true
/// # "#.to_owned());
/// #
/// # // Loads the config file.
/// # Config::from_filesystem(&Path::new("."), &config_file).unwrap();
/// ```
#[derive(Deserialize, Debug, Clone)]
pub struct CoreConfig {
    /// The size of the memory (history).
    /// The number of elements that should be tracked.
    pub buffer_size: Option<usize>,
    auto_capitalize: Option<bool>,
    /// The max numbers of predicates to display.
    pub page_size: Option<usize>,
    /// Whether the predicate should be automatically committed.
    pub auto_commit: Option<bool>,
}

#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
enum Data {
    Simple(String),
    Multi(Vec<String>),
    File(DataFile),
    Detailed(DetailedData),
    MoreDetailed(MoreDetailedData),
}

#[derive(Deserialize, Debug, Clone)]
struct DataFile {
    path: String,
}

#[derive(Deserialize, Debug, Clone)]
struct DetailedData {
    value: String,
    alias: Vec<String>,
}

#[derive(Deserialize, Debug, Clone)]
struct MoreDetailedData {
    values: Vec<String>,
    alias: Vec<String>,
}

macro_rules! insert_with_auto_capitalize {
    ( $data: expr, $auto_capitalize: expr, $key: expr, $value: expr ) => {
        $data.insert($key.to_owned(), Data::Simple($value.to_owned()));

        if $auto_capitalize && !$key.is_empty() && $key.chars().next().unwrap().is_lowercase() {
            $data
                .entry($key[0..1].to_uppercase() + &$key[1..])
                .or_insert(Data::Simple($value.to_uppercase()));
        }
    };
}

impl Config {
    /// Load the configuration from a file.
    pub fn from_file(filepath: &Path) -> Result<Self, Box<dyn error::Error>> {
        Self::from_filesystem(filepath, &StdFileSystem {})
    }

    /// Loads the configuration from a file in using a specified filesystem.
    pub fn from_filesystem(
        filepath: &Path,
        fs: &impl FileSystem,
    ) -> Result<Self, Box<dyn error::Error>> {
        let content = fs
            .read_to_string(filepath)
            .map_err(|err| format!("Couldn't open file `{filepath:?}`.\nCaused by:\n\t{err}."))?;
        let mut config: Self = toml::from_str(&content).map_err(|err| {
            format!("Failed to parse configuration file `{filepath:?}`.\nCaused by:\n\t{err}")
        })?;
        let config_path = filepath.parent().unwrap();
        let auto_capitalize = config
            .core
            .as_ref()
            .and_then(|c| c.auto_capitalize)
            .unwrap_or(true);

        // Data
        let mut data = IndexMap::new();

        config.data.unwrap_or_default().iter().try_for_each(
            |(key, value)| -> Result<(), Box<dyn error::Error>> {
                match value {
                    Data::File(DataFile { path }) => {
                        let filepath = config_path.join(path);
                        let conf = Config::from_filesystem(&filepath, fs)?;
                        data.extend(conf.data.unwrap_or_default());
                    }
                    Data::Simple(value) => {
                        insert_with_auto_capitalize!(data, auto_capitalize, key, value);
                    }
                    Data::Detailed(DetailedData { value, alias }) => {
                        alias.iter().chain([key.to_owned()].iter()).for_each(|key| {
                            insert_with_auto_capitalize!(data, auto_capitalize, key, value);
                        });
                    }
                    _ => Err(format!("Invalid script file `{filepath:?}`.\nCaused by:\n\t{value:?} not allowed in the data table."))?,
                };
                Ok(())
            },
        )?;
        config.data = Some(data);

        // Translators
        #[cfg(feature = "rhai")]
        {
            let mut translators = IndexMap::new();

            config.translators.unwrap_or_default().iter().try_for_each(
                |(key, value)| -> Result<(), Box<dyn error::Error>> {
                    match value {
                        Data::File(DataFile { path }) => {
                            let filepath = config_path.join(path);
                            let conf = Config::from_filesystem(&filepath, fs)?;
                            translators.extend(conf.translators.unwrap_or_default());
                        }
                        Data::Simple(value) => {
                            let filepath = config_path.join(value.clone()).to_str().unwrap().to_string();
                            translators.insert(key.to_owned(), Data::Simple(filepath));
                        }
                        _ => Err(format!("Invalid script file `{filepath:?}`.\nCaused by:\n\t{value:?} not allowed in the translator table."))?,
                    };
                    Ok(())
                },
            )?;
            config.translators = Some(translators);
        }

        // Translation
        let mut translation = IndexMap::new();

        config.translation.unwrap_or_default().iter().try_for_each(
            |(key, value)| -> Result<(), Box<dyn error::Error>> {
                match value {
                    Data::File(DataFile { path }) => {
                        let filepath = config_path.join(path);
                        let conf = Config::from_filesystem(&filepath, fs)?;
                        translation.extend(conf.translation.unwrap_or_default());
                    }
                    Data::Simple(_) | Data::Multi(_) => {
                        translation.insert(key.to_owned(), value.clone());
                    }
                    Data::Detailed(DetailedData { value, alias }) => {
                        alias.iter().chain([key.to_owned()].iter()).for_each(|e| {
                            translation.insert(e.to_owned(), Data::Simple(value.to_owned()));
                        });
                    }
                    Data::MoreDetailed(MoreDetailedData { values, alias }) => {
                        alias.iter().chain([key.to_owned()].iter()).for_each(|key| {
                            translation.insert(key.to_owned(), Data::Multi(values.clone()));
                        });
                    }
                };
                Ok(())
            },
        )?;

        config.translation = Some(translation);

        Ok(config)
    }

    /// Extracts the data from the configuration.
    pub fn extract_data(&self) -> IndexMap<String, String> {
        let empty = IndexMap::default();

        self.data
            .as_ref()
            .unwrap_or(&empty)
            .iter()
            .filter_map(|(key, value)| {
                let value = match value {
                    Data::Simple(value) => Some(value),
                    _ => None,
                };
                value.map(|value| (key.to_owned(), value.to_owned()))
            })
            .collect()
    }

    /// Extracts the translators from the configuration.
    #[cfg(feature = "rhai")]
    pub fn extract_translators(&self) -> Result<IndexMap<String, AST>, Box<dyn error::Error>> {
        self.extract_translators_using_filesystem(&StdFileSystem {})
    }

    /// Extracts the translators from the configuration using the specified filesystem..
    #[cfg(feature = "rhai")]
    pub fn extract_translators_using_filesystem(
        &self,
        fs: &impl FileSystem,
    ) -> Result<IndexMap<String, AST>, Box<dyn error::Error>> {
        let empty = IndexMap::default();
        let mut engine = Engine::new();

        // allow nesting up to 50 layers of expressions/statements
        // at global level, but only 10 inside function
        engine.set_max_expr_depths(25, 25);

        self.translators
            .as_ref()
            .unwrap_or(&empty)
            .iter()
            .filter_map(|(name, file_path)| {
                let file_path = match file_path {
                    Data::Simple(file_path) => Some(file_path),
                    _ => None,
                };

                file_path.map(|file_path| {
                    let file_path = Path::new(&file_path);
                    let parent = file_path.parent().unwrap().to_str().unwrap();
                    let header = format!(r#"const DIR = {parent:?};"#);
                    let body = fs.read_to_string(file_path)?;
                    let ast = engine.compile(body).map_err(|err| {
                        format!(
                            "Failed to parse script file `{file_path:?}`.\nCaused by:\n\t{err}."
                        )
                    })?;
                    let ast = engine.compile(header).unwrap().merge(&ast);

                    Ok((name.to_owned(), ast))
                })
            })
            .collect()
    }

    /// Extracts the translation from the configuration.
    pub fn extract_translation(&self) -> IndexMap<String, Vec<String>> {
        let empty = IndexMap::new();

        self.translation
            .as_ref()
            .unwrap_or(&empty)
            .iter()
            .filter_map(|(key, value)| {
                let value = match value {
                    Data::Simple(value) => Some(vec![value.to_owned()]),
                    Data::Multi(value) => Some(value.to_owned()),
                    _ => None,
                };

                value.map(|value| (key.to_owned(), value))
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use crate::Config;
    use std::path::Path;

    #[test]
    fn from_file() {
        let conf = Config::from_file(Path::new("./data/config_sample.toml")).unwrap();

        assert_eq!(
            conf.core.as_ref().map(|core| {
                assert_eq!(core.buffer_size.unwrap(), 64);
                assert!(!core.auto_capitalize.unwrap());
                assert!(!core.auto_commit.unwrap());
                assert_eq!(core.page_size.unwrap(), 10);
                true
            }),
            Some(true)
        );

        let data = conf.extract_data();
        assert_eq!(data.keys().len(), 23);

        // data and core not provided
        let conf = Config::from_file(Path::new("./data/blank_sample.toml")).unwrap();
        let data = conf.extract_data();
        assert_eq!(data.keys().len(), 0);

        // parsing error
        let conf = Config::from_file(Path::new("./data/invalid_file.toml"));
        assert!(conf.is_err());

        // config file not found
        let conf = Config::from_file(Path::new("./data/not_found"));
        assert!(conf.is_err());
    }

    #[test]
    fn from_invalid_file() {
        // invalid data
        let conf = Config::from_file(Path::new("./data/invalid_data.toml"));
        assert!(conf.is_err());
    }

    #[cfg(feature = "rhai")]
    #[test]
    fn from_file_with_translators() {
        // invalid translator
        let conf = Config::from_file(Path::new("./data/invalid_translator.toml"));
        assert!(conf.is_err());

        let conf = Config::from_file(Path::new("./data/config_sample.toml")).unwrap();
        let translators = conf.extract_translators().unwrap();
        assert_eq!(translators.keys().len(), 2);

        // translators not provided
        let conf = Config::from_file(Path::new("./data/blank_sample.toml")).unwrap();
        let translators = conf.extract_translators().unwrap();
        assert_eq!(translators.keys().len(), 0);

        // scripts parsing error
        let conf = Config::from_file(Path::new("./data/bad_script2.toml")).unwrap();
        assert!(conf.extract_translators().is_err());

        // script file not found
        let conf = Config::from_file(Path::new("./data/bad_script.toml")).unwrap();
        assert!(conf.extract_translators().is_err());
    }

    #[test]
    fn from_file_with_translation() {
        let conf = Config::from_file(Path::new("./data/config_sample.toml")).unwrap();
        let translation = conf.extract_translation();
        assert_eq!(translation.keys().len(), 4);

        let conf = Config::from_file(Path::new("./data/blank_sample.toml")).unwrap();
        let translation = conf.extract_translation();
        assert_eq!(translation.keys().len(), 0);
    }

    #[test]
    fn from_filesystem() {
        use crate::FileSystem;
        use std::{error::Error, fs};

        #[derive(Default)]
        struct FilterFileSystem;

        impl FileSystem for FilterFileSystem {
            fn read_to_string(&self, filepath: &Path) -> Result<String, Box<dyn Error>> {
                let file_stem = filepath.file_stem().unwrap();

                Ok(if file_stem == "data_sample" {
                    fs::read_to_string(filepath)?
                } else {
                    String::new()
                })
            }
        }

        let fs = FilterFileSystem {};
        let filepath = Path::new("./data/data_sample.toml");
        let conf = Config::from_filesystem(&filepath, &fs).unwrap();

        assert_eq!(conf.extract_data().keys().len(), 13);
        #[cfg(feature = "rhai")]
        assert_eq!(conf.extract_translators().unwrap().keys().len(), 0);
        assert_eq!(conf.extract_translation().keys().len(), 0);
    }
}