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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
//! ### config
//!
//! `config` is the module which handles pyc configuration parsing

/*
*
*   Copyright (C) 2020 Christian Visintin - christian.visintin1997@gmail.com
*
* 	This file is part of "Pyc"
*
*   Pyc is free software: you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation, either version 3 of the License, or
*   (at your option) any later version.
*
*   Pyc is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details.
*
*   You should have received a copy of the GNU General Public License
*   along with Pyc.  If not, see <http://www.gnu.org/licenses/>.
*
*/

extern crate yaml_rust;

mod configparser;

use configparser::ConfigParser;
use std::collections::HashMap;
use std::fmt;
use yaml_rust::{Yaml, YamlLoader};

use std::path::PathBuf;

//Types
#[derive(Clone)]
pub struct Config {
    pub language: String,
    pub shell_config: ShellConfig,
    pub alias: HashMap<String, String>,
    pub output_config: OutputConfig,
    pub prompt_config: PromptConfig,
}

#[derive(Clone)]
pub struct ShellConfig {
    pub exec: String,
    pub args: Vec<String>
}

#[derive(Clone)]
pub struct OutputConfig {
    pub translate_output: bool,
}

#[derive(Clone)]
pub struct PromptConfig {
    pub prompt_line: String,
    pub history_size: usize,
    pub translate: bool,
    pub break_enabled: bool,
    pub break_str: String,
    pub min_duration: usize,
    pub rc_ok: String,
    pub rc_err: String,
    pub git_branch: String,
    pub git_commit_ref: usize,
    pub git_commit_prepend: Option<String>,
    pub git_commit_append: Option<String>
}

#[derive(Copy, Clone, PartialEq, fmt::Debug)]
pub enum ConfigErrorCode {
    NoSuchFileOrDirectory,
    CouldNotReadFile,
    YamlSyntaxError,
}

pub struct ConfigError {
    pub code: ConfigErrorCode,
    pub message: String,
}

impl fmt::Display for ConfigErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let code_str: &str = match self {
            ConfigErrorCode::NoSuchFileOrDirectory => "NoSuchFileOrDirectory",
            ConfigErrorCode::CouldNotReadFile => "CouldNotReadFile",
            ConfigErrorCode::YamlSyntaxError => "YamlSyntaxError",
        };
        write!(f, "{}", code_str)
    }
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} ({})", self.message, self.code)
    }
}

impl Config {
    /// ### default
    ///
    /// Instantiates a default configuration struct
    pub fn default() -> Config {
        let alias_config: HashMap<String, String> = HashMap::new();
        Config {
            language: String::from("ru"),
            shell_config: ShellConfig::default(),
            alias: alias_config,
            output_config: OutputConfig::default(),
            prompt_config: PromptConfig::default(),
        }
    }

    /// ### parse_config
    ///
    /// `parse_config` parse a YAML configuration file and return a Config struct
    pub fn parse_config(config_file: PathBuf) -> Result<Config, ConfigError> {
        //Read configuration file
        let config_str: String = match std::fs::read_to_string(config_file.clone()) {
            Ok(config) => config,
            Err(err) => match err.kind() {
                std::io::ErrorKind::NotFound => {
                    return Err(ConfigError {
                        code: ConfigErrorCode::NoSuchFileOrDirectory,
                        message: format!("No such file or directory: {}", config_file.display()),
                    })
                }
                _ => {
                    return Err(ConfigError {
                        code: ConfigErrorCode::CouldNotReadFile,
                        message: format!("Could not read file {}", config_file.display())
                    })
                }
            },
        };
        Config::parse_config_str(config_str)
    }

    /// ### parse_config_str
    ///
    /// Parse configuration as string
    fn parse_config_str(config: String) -> Result<Config, ConfigError> {
        //Parse YAML file
        let yaml_docs: Vec<Yaml> = match YamlLoader::load_from_str(config.as_str()) {
            Ok(doc) => doc,
            Err(_) => {
                return Err(ConfigError {
                    code: ConfigErrorCode::YamlSyntaxError,
                    message: String::from("Configuration is not a valid YAML"),
                });
            }
        };
        //Check there is at least one document
        if yaml_docs.len() == 0 {
            return Err(ConfigError {
                code: ConfigErrorCode::YamlSyntaxError,
                message: String::from("File does not contain any YAML document"),
            });
        };
        let yaml_doc: &Yaml = &yaml_docs[0];
        //Look for keys and get configuration parts
        //Get language
        let language: String = match ConfigParser::get_child(&yaml_doc, String::from("language")) {
            Ok(node) => match Config::parse_language(&node) {
                Ok(l) => l,
                Err(err) => return Err(err),
            },
            Err(_) => String::from("ru"),
        };
        //Get alias
        let alias_config: HashMap<String, String> = match ConfigParser::get_child(&yaml_doc, String::from("alias")) {
                Ok(node) => match Config::parse_alias(&node) {
                    Ok(cfg) => cfg,
                    Err(err) => return Err(err),
                },
                Err(_) => HashMap::new(),
        };
        let shell_config: ShellConfig = match ConfigParser::get_child(&yaml_doc, String::from("shell")) {
            Ok(node) => match ShellConfig::parse_config(&node) {
                Ok(cfg) => cfg,
                Err(err) => return Err(err)
            },
            Err(_) => ShellConfig::default()
        };
        //Get output config
        let output_config: OutputConfig =
            match ConfigParser::get_child(&yaml_doc, String::from("output")) {
                Ok(node) => match OutputConfig::parse_config(&node) {
                    Ok(config) => config,
                    Err(err) => return Err(err),
                },
                Err(_) => OutputConfig::default(),
            };
        //Get prompt config
        let prompt_config: PromptConfig =
            match ConfigParser::get_child(&yaml_doc, String::from("prompt")) {
                Ok(node) => match PromptConfig::parse_config(&node) {
                    Ok(config) => config,
                    Err(err) => return Err(err),
                },
                Err(_) => PromptConfig::default(),
            };
        Ok(Config {
            language: language,
            shell_config: shell_config,
            alias: alias_config,
            output_config: output_config,
            prompt_config: prompt_config,
        })
    }

    /// ### get_alias
    ///
    ///  Get alias from configuration
    pub fn get_alias(&self, alias: &String) -> Option<String> {
        match self.alias.get(alias) {
            Some(cmd) => Some(cmd.clone()),
            None => None,
        }
    }

    /// ### parse_alias
    ///
    /// Parse alias in Pyc configuration file
    fn parse_alias(alias_yaml: &Yaml) -> Result<HashMap<String, String>, ConfigError> {
        if !alias_yaml.is_array() {
            return Err(ConfigError {
                code: ConfigErrorCode::YamlSyntaxError,
                message: String::from("'alias' key is not an array"),
            });
        }
        let mut alias_table: HashMap<String, String> = HashMap::new();
        //Iterate over alias
        for pair in alias_yaml.as_vec().unwrap() {
            for p in pair.as_hash().unwrap().iter() {
                let key: String = String::from(p.0.as_str().unwrap());
                let value: String = String::from(p.1.as_str().unwrap());
                alias_table.insert(key, value);
            }
        }
        Ok(alias_table)
    }

    /// ### parse_language
    ///
    /// Parse language YAML object
    fn parse_language(language_yaml: &Yaml) -> Result<String, ConfigError> {
        match language_yaml.as_str() {
            Some(s) => Ok(String::from(s)),
            None => Err(ConfigError {
                code: ConfigErrorCode::YamlSyntaxError,
                message: String::from("'language' is not a string"),
            }),
        }
    }
}

impl ShellConfig {
    pub fn default() -> ShellConfig {
        ShellConfig {
            exec: String::from("bash"),
            args: vec![]
        }
    }

    pub fn parse_config(shell_yaml: &Yaml) -> Result<ShellConfig, ConfigError> {
        let exec: String = match ConfigParser::get_string(&shell_yaml, String::from("exec")) {
            Ok(s) => s,
            Err(err) => return Err(err)
        };

        let args: Vec<String> = match ConfigParser::get_child(&shell_yaml, String::from("args")) {
            Ok(args_yaml) => {
                let mut args: Vec<String> = Vec::new();
                //Iterate over args
                for arg in args_yaml.as_vec().unwrap() {
                    args.push(match arg.as_str() {
                        Some(s) => String::from(s),
                        None => return Err(ConfigError {code: ConfigErrorCode::YamlSyntaxError, message: String::from("Shell arg is not a string")})
                    });
                }
                args
            },
            Err(_) => Vec::new()
        };
        Ok(ShellConfig {
            exec: exec,
            args: args
        })
    }
}

impl OutputConfig {
    pub fn default() -> OutputConfig {
        OutputConfig {
            translate_output: true,
        }
    }

    pub fn parse_config(output_yaml: &Yaml) -> Result<OutputConfig, ConfigError> {
        let translate_output: bool =
            match ConfigParser::get_bool(&output_yaml, String::from("translate")) {
                Ok(t) => t,
                Err(err) => return Err(err),
            };
        Ok(OutputConfig {
            translate_output: translate_output,
        })
    }
}

impl PromptConfig {
    /// ### default
    ///
    /// Instantiate a default PromptConfig struct
    pub fn default() -> PromptConfig {
        PromptConfig {
            prompt_line: String::from("${USER}@${HOSTNAME}:${WRKDIR}$"),
            history_size: 256,
            translate: false,
            break_enabled: false,
            break_str: String::from("❯"),
            min_duration: 2000,
            rc_ok: String::from("✔"),
            rc_err: String::from("✖"),
            git_branch: String::from("on "),
            git_commit_ref: 8,
            git_commit_append: None,
            git_commit_prepend: None
        }
    }

    /// ### parse_config
    ///
    /// Parse a PromptConfig from YAML configuration file
    pub fn parse_config(prompt_config_yaml: &Yaml) -> Result<PromptConfig, ConfigError> {
        //Prompt line
        let prompt_line: String =
            match ConfigParser::get_string(&prompt_config_yaml, String::from("prompt_line")) {
                Ok(ret) => ret,
                Err(err) => return Err(err),
            };
        //History size
        let history_size: usize =
            match ConfigParser::get_usize(&prompt_config_yaml, String::from("history_size")) {
                Ok(ret) => ret,
                Err(err) => return Err(err),
            };
        //History size
        let translate: bool =
            match ConfigParser::get_bool(&prompt_config_yaml, String::from("translate")) {
                Ok(ret) => ret,
                Err(err) => return Err(err),
            };
        //Break
        let brk: &Yaml = match ConfigParser::get_child(&prompt_config_yaml, String::from("break")) {
            Ok(ret) => ret,
            Err(err) => return Err(err),
        };
        //Break enabled
        let break_enabled: bool = match ConfigParser::get_bool(&brk, String::from("enabled")) {
            Ok(ret) => ret,
            Err(err) => return Err(err),
        };
        //Break with
        let break_str: String = match ConfigParser::get_string(&brk, String::from("with")) {
            Ok(ret) => ret,
            Err(err) => return Err(err),
        };
        //Duration
        let duration: &Yaml =
            match ConfigParser::get_child(&prompt_config_yaml, String::from("duration")) {
                Ok(ret) => ret,
                Err(err) => return Err(err),
            };
        //Minimum duration
        let min_duration: usize =
            match ConfigParser::get_usize(&duration, String::from("min_elapsed_time")) {
                Ok(ret) => ret,
                Err(err) => return Err(err),
            };
        //Rc
        let rc: &Yaml = match ConfigParser::get_child(&prompt_config_yaml, String::from("rc")) {
            Ok(ret) => ret,
            Err(err) => return Err(err),
        };
        //Rc_ok
        let rc_ok: String = match ConfigParser::get_string(&rc, String::from("ok")) {
            Ok(ret) => ret,
            Err(err) => return Err(err),
        };
        //Rc err
        let rc_err: String = match ConfigParser::get_string(&rc, String::from("error")) {
            Ok(ret) => ret,
            Err(err) => return Err(err),
        };
        //Git
        let git: &Yaml = match ConfigParser::get_child(&prompt_config_yaml, String::from("git")) {
            Ok(ret) => ret,
            Err(err) => return Err(err),
        };
        //Git branch
        let git_branch: String = match ConfigParser::get_string(&git, String::from("branch")) {
            Ok(ret) => ret,
            Err(err) => return Err(err),
        };
        //Git commit ref
        let git_commit_ref: usize =
            match ConfigParser::get_usize(&git, String::from("commit_ref_len")) {
                Ok(ret) => ret,
                Err(err) => return Err(err),
            };
        //Git commit prepend
        let git_commit_prepend: Option<String> =
            match ConfigParser::get_string(&git, String::from("commit_prepend")) {
                Ok(ret) => Some(ret),
                Err(_) => None,
            };
        //Git commit append
        let git_commit_append: Option<String> =
            match ConfigParser::get_string(&git, String::from("commit_append")) {
                Ok(ret) => Some(ret),
                Err(_) => None,
            };
        Ok(PromptConfig {
            prompt_line: prompt_line,
            history_size: history_size,
            translate: translate,
            break_enabled: break_enabled,
            break_str: break_str,
            min_duration: min_duration,
            rc_ok: rc_ok,
            rc_err: rc_err,
            git_branch: git_branch,
            git_commit_ref: git_commit_ref,
            git_commit_append: git_commit_append,
            git_commit_prepend: git_commit_prepend
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    #[test]
    fn test_config_default() {
        let config: Config = Config::default();
        assert!(config.get_alias(&String::from("чд")).is_none());
        assert_eq!(config.output_config.translate_output, true);
        assert_eq!(config.language, String::from("ru"));
        let prompt_config: PromptConfig = config.prompt_config;
        assert_eq!(prompt_config.prompt_line, String::from("${USER}@${HOSTNAME}:${WRKDIR}$"));
        assert_eq!(prompt_config.break_enabled, false);
        assert_eq!(prompt_config.break_str, String::from("❯"));
        assert_eq!(prompt_config.git_branch, String::from("on "));
        assert_eq!(prompt_config.git_commit_ref, 8);
        assert_eq!(prompt_config.git_commit_prepend, None);
        assert_eq!(prompt_config.git_commit_append, None);
        assert_eq!(prompt_config.history_size, 256);
        assert_eq!(prompt_config.min_duration, 2000);
        assert_eq!(prompt_config.rc_err, String::from("✖"));
        assert_eq!(prompt_config.rc_ok, String::from("✔"));
        assert_eq!(prompt_config.translate, false);
        assert_eq!(config.shell_config.exec, String::from("bash"));
        assert_eq!(config.shell_config.args.len(), 0);
    }

    #[test]
    fn test_config_file() {
        //Try to parse a configuration file
        let config_file: tempfile::NamedTempFile = write_config_file_en();
        let config_file_path: PathBuf = PathBuf::from(config_file.path().to_str().unwrap());
        println!("Generated config file: {}", config_file_path.display());
        let config: Result<Config, ConfigError> =Config::parse_config(config_file_path);
        assert!(config.is_ok());
        let config: Config = config.ok().unwrap();
        // Verify parameters
        assert!(config.get_alias(&String::from("чд")).is_some());
        assert_eq!(config.output_config.translate_output, true);
        assert_eq!(config.language, String::from("ru"));
        let prompt_config: PromptConfig = config.prompt_config;
        assert_eq!(prompt_config.prompt_line, String::from("${USER}@${HOSTNAME}:${WRKDIR}$"));
        assert_eq!(prompt_config.break_enabled, false);
        assert_eq!(prompt_config.break_str, String::from("❯"));
        assert_eq!(prompt_config.git_branch, String::from("on "));
        assert_eq!(prompt_config.git_commit_ref, 8);
        assert_eq!(prompt_config.git_commit_prepend, None);
        assert_eq!(prompt_config.git_commit_append, None);
        assert_eq!(prompt_config.history_size, 256);
        assert_eq!(prompt_config.min_duration, 2000);
        assert_eq!(prompt_config.rc_err, String::from("✖"));
        assert_eq!(prompt_config.rc_ok, String::from("✔"));
        assert_eq!(prompt_config.translate, false);
        assert_eq!(config.shell_config.exec, String::from("bash"));
        assert_eq!(config.shell_config.args.len(), 0);
        
    }

    #[test]
    fn test_config_no_file() {
        assert_eq!(
            Config::parse_config(PathBuf::from("config.does.not.exist.yml"))
                .err()
                .unwrap()
                .code,
            ConfigErrorCode::NoSuchFileOrDirectory
        );
    }

    #[cfg(not(target_os = "macos"))]
    #[test]
    fn test_config_not_accessible() {
        assert_eq!(
            Config::parse_config(PathBuf::from("/dev/ttyS0"))
                .err()
                .unwrap()
                .code,
            ConfigErrorCode::CouldNotReadFile
        );
    }

    #[test]
    fn test_config_en_alias() {
        //Try to parse a configuration file
        let config: String =
            String::from("alias:\n  - чд: \"cd\"\n  - пвд: \"pwd\"\n  - уич: \"which\"");
        match Config::parse_config_str(config) {
            Ok(config) => {
                //Verify alias parameters
                assert_eq!(
                    config.get_alias(&String::from("чд")).unwrap(),
                    String::from("cd")
                );
                assert_eq!(
                    config.get_alias(&String::from("пвд")).unwrap(),
                    String::from("pwd")
                );
                assert_eq!(
                    config.get_alias(&String::from("уич")).unwrap(),
                    String::from("which")
                );
                assert!(config
                    .get_alias(&String::from("thiskeydoesnotexist"))
                    .is_none());
            }
            Err(error) => panic!(
                "Parse_config should have returned OK, but returned {} ({:?})",
                error.message, error.code
            ),
        };
    }

    #[test]
    fn test_config_no_alias() {
        //Try to parse a configuration file
        let config: String = String::from("language: ru\n");
        let config: Config = Config::parse_config_str(config).ok().unwrap();
        assert!(config.get_alias(&String::from("чд")).is_none());
    }

    #[test]
    fn test_config_alias_not_array() {
        let config: String = String::from("alias: 5\n");
        assert_eq!(
            Config::parse_config_str(config).err().unwrap().code,
            ConfigErrorCode::YamlSyntaxError
        );
    }

    #[test]
    fn test_config_shell_config() {
        let config: String = String::from("shell:\n  exec: \"sh\"\n  args:\n    - \"-l\"\n    - \"-h\"\n");
        let config: Config = Config::parse_config_str(config).ok().unwrap();
        assert_eq!(config.shell_config.exec, String::from("sh"));
        assert_eq!(config.shell_config.args, vec![String::from("-l"), String::from("-h")]);
    }

    #[test]
    fn test_config_shell_config_bad() {
        let config: String = String::from("shell:\n  args:\n    - \"-l\"\n    - \"-h\"\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("shell:\n  args: 5\n");
        assert!(Config::parse_config_str(config).is_err());
    }

    #[test]
    fn test_config_output_config() {
        let config: String =
            String::from("alias:\n  - чд: \"cd\"\n  - пвд: \"pwd\"\n  - уич: \"which\"");
        let config: Config = Config::parse_config_str(config).ok().unwrap();
        assert!(config.output_config.translate_output);
        //Try to parse a configuration file
        let config: String = String::from("output:\n  translate: false\n");
        let config: Config = Config::parse_config_str(config).ok().unwrap();
        assert!(!config.output_config.translate_output);
    }

    #[test]
    fn test_config_bad_output_config() {
        let config: String = String::from("output: 5\n");
        assert_eq!(
            Config::parse_config_str(config).err().unwrap().code,
            ConfigErrorCode::YamlSyntaxError
        );
        let config: String = String::from("output:\n  translate: foobar\n");
        assert_eq!(
            Config::parse_config_str(config).err().unwrap().code,
            ConfigErrorCode::YamlSyntaxError
        );
        let config: String = String::from("output:\n  trsnlate: true\n");
        assert_eq!(
            Config::parse_config_str(config).err().unwrap().code,
            ConfigErrorCode::YamlSyntaxError
        );
    }

    #[test]
    fn test_config_language() {
        let config: String = String::from("language: bg\n");
        let config: Config = Config::parse_config_str(config).ok().unwrap();
        assert_eq!(config.language, String::from("bg"));
    }

    #[test]
    fn test_config_language_missing() {
        let config: String = String::from("output:\n  translate: false\n");
        let config: Config = Config::parse_config_str(config).ok().unwrap();
        assert_eq!(config.language, String::from("ru"));
    }

    #[test]
    #[should_panic]
    fn test_config_language_badvalue() {
        let config: String = String::from("language:\n  name: ru\n");
        assert!(Config::parse_config_str(config).is_ok());
    }

    #[test]
    fn test_config_prompt_default() {
        let config: String = String::from("language:\n  ru\n");
        let config: Config = Config::parse_config_str(config).ok().unwrap();
        let prompt_config: PromptConfig = config.prompt_config;
        assert_eq!(prompt_config.prompt_line, String::from("${USER}@${HOSTNAME}:${WRKDIR}$"));
        assert_eq!(prompt_config.break_enabled, false);
        assert_eq!(prompt_config.break_str, String::from("❯"));
        assert_eq!(prompt_config.git_branch, String::from("on "));
        assert_eq!(prompt_config.git_commit_ref, 8);
        assert_eq!(prompt_config.history_size, 256);
        assert_eq!(prompt_config.min_duration, 2000);
        assert_eq!(prompt_config.rc_err, String::from("✖"));
        assert_eq!(prompt_config.rc_ok, String::from("✔"));
        assert_eq!(prompt_config.translate, false);
    }

    #[test]
    fn test_config_prompt() {
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n    commit_prepend: \"(\"\n    commit_append: \")\"\n");
        let config: Config = Config::parse_config_str(config).ok().unwrap();
        //Verify config parameters
        let prompt_config: PromptConfig = config.prompt_config;
        assert_eq!(prompt_config.prompt_line, String::from("${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}"));
        assert_eq!(prompt_config.break_enabled, false);
        assert_eq!(prompt_config.break_str, String::from(">"));
        assert_eq!(prompt_config.git_branch, String::from("on "));
        assert_eq!(prompt_config.git_commit_ref, 4);
        assert_eq!(prompt_config.git_commit_prepend, Some(String::from("(")));
        assert_eq!(prompt_config.git_commit_append, Some(String::from(")")));
        assert_eq!(prompt_config.history_size, 1024);
        assert_eq!(prompt_config.min_duration, 5000);
        assert_eq!(prompt_config.rc_err, String::from("x_x"));
        assert_eq!(prompt_config.rc_ok, String::from("^_^"));
        assert_eq!(prompt_config.translate, true);
    }

    #[test]
    fn test_config_prompt_bad() {
        let config: String = String::from("prompt:\n  prompt_le: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  histosize: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  trslate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  bak:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    eled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    th: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  dution:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsime: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  r:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    o: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    err: \"x_x\"\n  git:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  gi:\n    branch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    brch: \"on \"\n    commit_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
        let config: String = String::from("prompt:\n  prompt_line: \"${USER} on ${HOSTNAME} in ${WRKDIR} ${GIT_BRANCH} (${GIT_COMMIT}) ${CMD_TIME}\"\n  history_size: 1024\n  translate: true\n  break:\n    enabled: false\n    with: \">\"\n  duration:\n    min_elapsed_time: 5000\n  rc:\n    ok: \"^_^\"\n    error: \"x_x\"\n  git:\n    branch: \"on \"\n    com_ref_len: 4\n");
        assert!(Config::parse_config_str(config).is_err());
    }

    #[test]
    fn test_config_bad_syntax() {
        let config: String = String::from("foobar: 5:\n");
        assert_eq!(
            Config::parse_config_str(config).err().unwrap().code,
            ConfigErrorCode::YamlSyntaxError
        );
    }

    #[test]
    fn test_config_empty_yaml() {
        let config: String = String::from("\n");
        assert_eq!(
            Config::parse_config_str(config).err().unwrap().code,
            ConfigErrorCode::YamlSyntaxError
        );
    }

    #[test]
    fn test_config_error_display() {
        println!(
            "{};{};{}",
            ConfigErrorCode::CouldNotReadFile,
            ConfigErrorCode::NoSuchFileOrDirectory,
            ConfigErrorCode::YamlSyntaxError
        );
        println!(
            "{}",
            ConfigError {
                code: ConfigErrorCode::NoSuchFileOrDirectory,
                message: String::from("No such file or directory ~/.config/pyc/pyc.yml")
            }
        );
    }

    /// ### write_config_file_en
    /// Write configuration file to a temporary directory and return the file path
    fn write_config_file_en() -> tempfile::NamedTempFile {
        // Write
        let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
        write!(
            tmpfile,
            "alias:\n  - чд: \"cd\"\n  - пвд: \"pwd\"\n  - уич: \"which\""
        )
        .unwrap();
        tmpfile
    }
}