komichi 2.2.0

Application tools for working with file-system paths
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
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
use camino::Utf8Path;
use std::collections::VecDeque;
use unicode_segmentation::UnicodeSegmentation;

use crate::error::{
    ExpandIdentifierError, ExpandTextError, IdentifierKeyError,
};

#[doc(hidden)]
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
    Identifier(String),
    Text(String),
    NewLine,
}

impl Token {
    fn new_text(text: &str) -> Self {
        let text = text.to_string();
        Self::Text(text)
    }
}

enum CapturingState {
    Pre,
    Enabled,
    Post,
}
// | 000 | 001 | 002 | 003 | 004 | 005 | 006 | 007 | 008 | 009 | 010 | 011 | 012 | 013 | 014 | 015
// |  a  |     |  b  |  o  |  t  |     |  $  |  {  |  _  |  a  |  }  |
// |  a  |     |  b  |  o  |  t  |     |  $  |  $  |  {  |  _  |  a  |  }  |

#[doc(hidden)]
pub struct WideChars<'a> {
    wide_chars: Vec<&'a str>,
    started: bool,
    index: usize,
}

impl<'a> WideChars<'a> {
    pub fn new(data: &'a str) -> Self {
        let wide_chars = UnicodeSegmentation::graphemes(data, true)
            .collect::<Vec<&str>>();

        Self {
            wide_chars,
            started: false,
            index: 0_usize,
        }
    }

    pub fn get(
        &self,
        index: usize,
    ) -> Option<&'a str> {
        match self.wide_chars.get(index) {
            Some(out) => Some(*out),
            None => None,
        }
    }

    pub fn bump_index(&mut self) {
        self.index += 1;
    }

    pub fn get_index(&self) -> usize {
        self.index
    }

    pub fn set_index(
        &mut self,
        index: usize,
    ) {
        self.index = index;
    }
}

impl<'a> Iterator for WideChars<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        if self.started {
            self.index += 1;
        } else {
            self.started = true;
        }
        let out = self.get(self.index);
        if out.is_none() && self.index > 0 {
            self.index -= 1;
        }
        out
    }
}

pub struct TokenIterator<'a> {
    wide_chars: WideChars<'a>,
    token_cache: VecDeque<Token>,
    line_number: usize,
}

impl<'a> TokenIterator<'a> {
    pub fn new(text: &'a str) -> Self {
        let wide_chars = WideChars::new(text);
        let token_cache: VecDeque<Token> =
            VecDeque::with_capacity(2);
        Self {
            wide_chars,
            token_cache,
            line_number: 0_usize,
        }
    }
    fn get_identifier(
        &mut self,
        wide_char: &str,
    ) -> Result<Option<String>, IdentifierKeyError> {
        if wide_char != "$" {
            return Ok(None);
        }
        let mut index = self.wide_chars.get_index();
        let next_wide_char = match self.wide_chars.get(index + 1) {
            Some(nwc) => nwc,
            None => return Ok(None),
        };
        if next_wide_char == "$" {
            self.wide_chars.bump_index();
            return Ok(None);
        }

        if next_wide_char != "{" {
            return Err(IdentifierKeyError::missing_starting_curly(
                index + 1,
            ));
        }
        index += 2;
        let starting_curly_index = index;
        let mut state = CapturingState::Pre;
        let mut out = String::new();
        let mut has_closing_curly = false;
        let mut first_identifier_character_index = 0_usize;
        while let Some(wchar) = self.wide_chars.get(index) {
            if !wchar.is_ascii() {
                return Err(IdentifierKeyError::non_ascii(index));
            }
            if wchar == "}" {
                has_closing_curly = true;
                break;
            }
            match state {
                CapturingState::Pre => {
                    if wchar == " " {
                        index += 1;
                        continue;
                    }
                    if wchar
                        .chars()
                        .all(|x| x.is_alphanumeric() || x == '_')
                    {
                        state = CapturingState::Enabled;
                        out.push_str(wchar);
                        first_identifier_character_index = index;
                        index += 1;
                        continue;
                    } else {
                        return Err(IdentifierKeyError::non_alpha_numeric_underscore(index));
                    }
                },
                CapturingState::Enabled => {
                    if wchar == " " {
                        state = CapturingState::Post;
                        index += 1;
                        continue;
                    }
                    if !wchar
                        .chars()
                        .all(|x| x.is_alphanumeric() || x == '_')
                    {
                        return Err(IdentifierKeyError::non_alpha_numeric_underscore(index));
                    }
                    index += 1;
                    out.push_str(wchar);
                    continue;
                },
                CapturingState::Post => {
                    if wchar == " " {
                        index += 1;
                        continue;
                    } else {
                        return Err(
                            IdentifierKeyError::invalid_name(index),
                        );
                    }
                },
            }
        }

        if !has_closing_curly {
            return Err(IdentifierKeyError::missing_closing_curly(
                starting_curly_index,
            ));
        }
        if out.is_empty() {
            return Err(IdentifierKeyError::empty_identifier_name(
                index - 1,
            ));
        }

        let first_char = out
            .chars()
            .next()
            .expect("Should have at lest one character");
        if first_char.is_numeric() {
            return Err(IdentifierKeyError::starts_with_number(
                first_identifier_character_index,
            ));
        }
        self.wide_chars.set_index(index);
        Ok(Some(out))
    }
}

impl Iterator for TokenIterator<'_> {
    type Item = Result<Token, ExpandIdentifierError>;

    fn next(&mut self) -> Option<Self::Item> {
        #[allow(clippy::never_loop)]
        while let Some(out) = self.token_cache.pop_front() {
            return Some(Ok(out));
        }
        let mut text = String::new();
        while let Some(wide_char) = self.wide_chars.next() {
            let identifier = match self.get_identifier(wide_char) {
                Ok(identifier) => identifier,
                Err(e) => {
                    return Some(Err(
                        ExpandIdentifierError::key_error(
                            self.line_number,
                            e,
                        ),
                    ));
                },
            };

            if let Some(identifier_name) = identifier {
                if !text.is_empty() {
                    self.token_cache
                        .push_back(Token::new_text(&text));
                    text.clear();
                }
                self.token_cache
                    .push_back(Token::Identifier(identifier_name));
                break;
            }
            if wide_char == "\n" {
                if !text.is_empty() {
                    self.token_cache
                        .push_back(Token::new_text(&text));
                    text.clear();
                }
                self.token_cache.push_back(Token::NewLine);
                self.line_number += 1;
                break;
            }
            text.push_str(wide_char);
        }
        if !text.is_empty() {
            self.token_cache.push_back(Token::new_text(&text));
            text.clear();
        }
        #[allow(clippy::never_loop)]
        while let Some(out) = self.token_cache.pop_front() {
            return Some(Ok(out));
        }
        None
    }
}

/// Provide the ability to expand BASH-like-curly-variables in text or in a
/// file.
///
/// This struct will only expand BASH-like-curly-variables (e.g. `${VAR}`).
/// This struct will not expand any non-curly-BASH-variables (e.g. `$VAR`).
///
/// The `$` character can be escaped by using two `$` characters e.g. `$$`.
///
/// # Example
///
/// ```
/// use komichi::ExpandText;
///
/// fn fetcher(key: &str) -> Option<String> {
///     match key {
///         "COLOR" => Some(String::from("brown")),
///         "animal" => Some(String::from("dog")),
///         _ => None
///     }
/// }
///
/// // Expand a simple string
/// let expect = "The quick brown fox jumps over the lazy dog";
/// let arg = "The quick ${COLOR} fox jumps over the lazy ${animal}";
/// let expand = ExpandText::new(fetcher);
///
/// let result = expand.text(arg).unwrap();
///
/// assert_eq!(result, expect);
///
/// // Expand the contents of a file (in this case a temp file)
/// use tempfile::NamedTempFile;
/// use camino::Utf8Path;
/// use std::io::Write;
///
/// let expect = "The playful brown fox runs into the sleeping dog";
/// let text = "The playful ${COLOR} fox runs into the sleeping ${animal}";
///
/// let mut file = NamedTempFile::new().expect("unable to create temp file");
/// file.write_all(text.as_bytes()).unwrap();
/// let path = Utf8Path::from_path(file.path()).unwrap();
///
/// let result = expand.file(&path).unwrap();
/// drop(file);
///
/// assert_eq!(result, expect);
/// ```
pub struct ExpandText {
    fetch_function: fn(&str) -> Option<String>,
}

impl ExpandText {
    pub fn new(fetch_function: fn(&str) -> Option<String>) -> Self {
        Self { fetch_function }
    }

    #[inline]
    fn _text(
        &self,
        text: &str,
    ) -> Result<String, ExpandIdentifierError> {
        let tokens = TokenIterator::new(text);
        let mut out = String::new();
        for token in tokens {
            let token = token?;
            match token {
                Token::Text(text) => out.push_str(&text),
                Token::Identifier(key) => {
                    if let Some(value) = (self.fetch_function)(&key)
                    {
                        out.push_str(&value);
                    } else {
                        out.push_str(format!("${{{key}}}").as_str());
                    }
                },
                Token::NewLine => out.push('\n'),
            }
        }
        Ok(out)
    }
    /// Return the given text, containing bash-like-curly variables that are
    /// expanded with values from this struct's callback function.
    ///
    /// The text can contain BASH-like variables with each variable using
    /// the curly syntax (e.g. `A dog named ${DOG_NAME}`). BASH-like variables
    /// that do not contain curly brackets (e.g. `$DOG_NAME`) will become
    /// identifier errors.
    ///
    /// The `$` character can be escaped by using two `$` characters e.g. `$$`.
    ///
    /// Any identifier that does not have a value, as given by the callback
    /// function will be skipped. Meaning that the BASH-like variable will be
    /// put back into the output.
    ///
    /// # Arguments
    /// * `text` - A string-slice containing the text-to-be-expanded
    ///
    /// # Errors
    /// A [`ExpandTextError`] - will be returned if:
    ///   * there are any syntactical errors with any BASH-like variables:
    ///     * Non-ASCII characters between the curly-brackets,
    ///     * Non-alpha-numeric-underscore characters between the curly-brackets,
    ///     * No characters/empty between the curly-brackets,
    ///     * Missing an opening curly-bracket, after the `$`,
    ///     * Missing a closing curly-bracket, after the identifier,
    ///     * Identifier starts with a number. Can only start with an underscore
    ///       or an ASCII-letter,
    ///     * Invalid identifier name when the identifier name contains spaces
    ///       between parts of the identifier name (e.g. `${dog name}`).
    pub fn text(
        &self,
        text: &str,
    ) -> Result<String, ExpandTextError> {
        Ok(self._text(text)?)
    }

    #[inline]
    fn _text_strict(
        &self,
        text: &str,
    ) -> Result<String, ExpandIdentifierError> {
        let tokens = TokenIterator::new(text);
        let mut out = String::new();
        for token in tokens {
            let token = token?;
            match token {
                Token::Text(text) => out.push_str(&text),
                Token::Identifier(key) => {
                    if let Some(value) = (self.fetch_function)(&key)
                    {
                        out.push_str(&value);
                    } else {
                        return Err(
                            ExpandIdentifierError::ValueError(key),
                        );
                    }
                },
                Token::NewLine => out.push('\n'),
            }
        }
        Ok(out)
    }

    /// Return the given text, containing bash-like-curly variables that are
    /// expanded with values from the given callback-function. And return
    /// an [`ExpandTextError`] when a value cannot be found by the given
    /// callback-function
    ///
    /// The text can contain BASH-like variables with each variable using
    /// the curly syntax (e.g. `A dog named ${DOG_NAME}`). BASH-like variables
    /// that do not contain curly brackets (e.g. `$DOG_NAME`) will become
    /// identifier errors.
    ///
    /// The `$` character can be escaped by using two `$` characters e.g. `$$`.
    ///
    /// # Arguments
    /// * `text` - A string-slice containing the text-to-be-expanded
    ///
    /// # Errors
    /// A [`ExpandTextError`] - will be returned if:
    ///   * there are any syntactical errors with any BASH-like variables:
    ///     * Non-ASCII characters between the curly-brackets,
    ///     * Non-alpha-numeric-underscore characters between the curly-brackets,
    ///     * No characters/empty between the curly-brackets,
    ///     * Missing an opening curly-bracket, after the `$`,
    ///     * Missing a closing curly-bracket, after the identifier,
    ///     * Identifier starts with a number. Can only start with an underscore
    ///       or an ASCII-letter,
    ///     * Invalid identifier name when the identifier name contains spaces
    ///       between parts of the identifier name (e.g. `${dog name}`),
    ///   * if the value for any identifier cannot be returned by the given
    ///     callback-function.
    pub fn text_strict(
        &self,
        text: &str,
    ) -> Result<String, ExpandTextError> {
        Ok(self._text_strict(text)?)
    }

    /// Return the given file's text, containing bash-like-curly variables
    /// that are expanded with values from this struct's callback function.
    ///
    /// The file-contents can contain BASH-like variables with each variable
    /// using the curly syntax (e.g. `A dog named ${DOG_NAME}`). BASH-like
    /// variables that do not contain curly brackets (e.g. `$DOG_NAME`) will
    /// become identifier errors.
    ///
    /// The `$` character can be escaped by using two `$` characters e.g. `$$`.
    ///
    /// # Arguments
    /// * path - a string-like reference to a [`str`] containing the path
    ///   that will be expanded.
    ///
    /// # Errors
    /// A [`ExpandTextError`] - will be returned if:
    ///   * there are any problems opening the given file path
    ///   * there are any syntactical errors with any BASH-like variables:
    ///     * Non-ASCII characters between the curly-brackets,
    ///     * Non-alpha-numeric-underscore characters between the
    ///       curly-brackets,
    ///     * No characters/empty between the curly-brackets,
    ///     * Missing an opening curly-bracket, after the `$`,
    ///     * Missing a closing curly-bracket, after the identifier,
    ///     * Identifier starts with a number. Can only start with an
    ///       underscore or an ASCII-letter,
    ///     * Invalid identifier name when the identifier name contains spaces
    ///       between parts of the identifier name (e.g. `${dog name}`).
    pub fn file<T>(
        &self,
        path: &T,
    ) -> Result<String, ExpandTextError>
    where
        T: AsRef<Utf8Path> + ?Sized,
    {
        let path = path.as_ref();
        let text = std::fs::read_to_string(path).map_err(|e| {
            ExpandTextError::read_file_error(path, e)
        })?;
        self._text(&text).map_err(|e| {
            ExpandTextError::identifier_error_in_file(path, e)
        })
    }

    /// Return the given file's text, containing bash-like-curly variables that
    /// are expanded with values from this struct's callback function and
    /// return an [`ExpandTextError`] if the value cannot be retrieved.
    ///
    /// The file-contents can contain BASH-like variables with each variable
    /// using the curly syntax (e.g. `A dog named ${DOG_NAME}`). BASH-like
    /// variables that do not contain curly brackets (e.g. `$DOG_NAME`) will
    /// become identifier errors.
    ///
    /// The `$` character can be escaped by using two `$` characters e.g. `$$`.
    ///
    /// # Arguments
    /// * path - a string-like reference to a [`str`] containing the path
    ///   that will be expanded.
    ///
    /// # Errors
    /// A [`ExpandTextError`] - will be returned if:
    ///   * there are any problems opening the given file path
    ///   * there are any syntactical errors with any BASH-like variables:
    ///     * Non-ASCII characters between the curly-brackets,
    ///     * Non-alpha-numeric-underscore characters between the curly-brackets,
    ///     * No characters/empty between the curly-brackets,
    ///     * Missing an opening curly-bracket, after the `$`,
    ///     * Missing a closing curly-bracket, after the identifier,
    ///     * Identifier starts with a number. Can only start with an underscore
    ///       or an ASCII-letter,
    ///     * Invalid identifier name when the identifier name contains spaces
    ///       between parts of the identifier name (e.g. `${dog name}`),
    ///   * if the value for any identifier cannot be returned by the given
    ///     callback-function.
    ///
    pub fn file_strict<T>(
        &self,
        path: &T,
    ) -> Result<String, ExpandTextError>
    where
        T: AsRef<Utf8Path> + ?Sized,
    {
        let path = path.as_ref();
        let text = std::fs::read_to_string(path).map_err(|e| {
            ExpandTextError::read_file_error(path, e)
        })?;
        self._text(&text).map_err(|e| {
            ExpandTextError::identifier_error_in_file(path, e)
        })
    }
}

/// A trait for types that can retrieve string-based data by a given key.
///
/// Implementors of `Fetcher` provide a mechanism to look up and return
/// a `String` value based on a `&str` key. This trait is suitable for
/// abstracting over various data sources, such as caches, configuration stores,
/// environment variables, or simple in-memory key-value maps.
///
/// # Examples
///
/// ## Implementing `Fetcher` on a struct holding values:
/// ```
/// use komichi::{Fetcher, ExpandTextWith};
///
/// struct Data {
///     a: String,
///     b: u16,
/// }
///
/// impl Data {
///     fn new(a: &str, b: u16) -> Self {
///         let a = a.to_string();
///         Self { a, b }
///     }
/// }
///
/// impl Fetcher for Data {
///     fn fetch(&self, key: &str) -> Option<String> {
///         match key {
///             "a" => Some(self.a.to_string()),
///             "b" => Some(self.b.to_string()),
///             _ => None
///         }
///     }
/// }
///
/// // Now interpolate a string using Data::fetch
/// let arg = "Hello ${a} for the ${b}th time";
/// let expect = "Hello World for the 12th time".to_string();
/// let data = Data::new("World", 12u16);
/// let expand = ExpandTextWith::new(&data);
/// let got = expand.text(&arg).unwrap();
/// assert_eq!(expect, got);
/// ```
/// ## Implementing `Fetcher` on a more complicated struct:
/// ```
/// use komichi::{Fetcher, ExpandTextWith};
///
/// struct Data<'a> {
///     a: &'a str,
///     b: u16,
/// }
///
/// impl<'a> Data<'a> {
///     fn new(a: &'a str, b: u16) -> Self {
///         Self { a, b }
///     }
/// }
///
/// impl<'a> Fetcher for Data<'a> {
///     fn fetch(&self, key: &str) -> Option<String> {
///         match key {
///             "a" => Some(self.a.to_string()),
///             "b" => Some(self.b.to_string()),
///             _ => None
///         }
///     }
/// }
///
/// // Now interpolate a string using Data::fetch
/// let arg = "Hello ${a} for the ${b}th time";
/// let expect = "Hello World for the 12th time".to_string();
/// let a = "World";
/// let data = Data::new(a, 12u16);
/// let expand = ExpandTextWith::new(&data);
/// let got = expand.text(&arg).unwrap();
/// assert_eq!(expect, got);
/// ```
/// ## Implementing `Fetcher` for an in-memory map:
/// ```
/// use std::collections::HashMap;
/// use komichi::{Fetcher, ExpandTextWith};
///
/// struct InMemoryCache {
///     data: HashMap<String, String>
/// }
///
/// impl InMemoryCache {
///     fn new() -> Self {
///         let mut data = HashMap::new();
///         data.insert("a".to_string(), "World".to_string());
///         data.insert("b".to_string(), "12".to_string());
///         Self { data }
///     }
/// }
///
/// impl Fetcher for InMemoryCache {
///     fn fetch(&self, key: &str) -> Option<String> {
///         self.data.get(key).cloned()
///     }
/// }
///
/// // Now interpolate a string using InMemoryCache::fetch
/// let arg = "Hello ${a} for the ${b}th time";
/// let expect = "Hello World for the 12th time".to_string();
/// let in_memory_cache = InMemoryCache::new();
/// let expand = ExpandTextWith::new(&in_memory_cache);
/// let got = expand.text(&arg).unwrap();
/// assert_eq!(expect, got);
/// ```
pub trait Fetcher {
    fn fetch(
        &self,
        key: &str,
    ) -> Option<String>;
}

/// Expand any BASH-like-identifiers in text or a file by obtaining values
/// using the [`Fetcher`] trait.
///
/// # Example
///
/// ```
/// use komichi::{Fetcher, ExpandTextWith};
///
/// struct Data<'a> {
///     a: &'a str,
///     b: u16,
/// }
///
/// impl<'a> Data<'a> {
///     fn new(a: &'a str, b: u16) -> Self {
///         Self { a, b }
///     }
/// }
///
/// impl<'a> Fetcher for Data<'a> {
///     fn fetch(&self, key: &str) -> Option<String> {
///         match key {
///             "a" => Some(self.a.to_string()),
///             "b" => Some(self.b.to_string()),
///             _ => None
///         }
///     }
/// }
///
/// // Now interpolate a string using Data::fetch
/// let arg = "Hello ${a} for the ${b}th time";
/// let expect = "Hello World for the 12th time".to_string();
/// let a = "World";
/// let data = Data::new(a, 12u16);
/// let expand = ExpandTextWith::new(&data);
/// let got = expand.text(&arg).unwrap();
/// assert_eq!(expect, got);
/// ```
pub struct ExpandTextWith<'a> {
    pub obj: &'a dyn Fetcher,
}

impl<'a> ExpandTextWith<'a> {
    pub fn new(obj: &'a dyn Fetcher) -> Self {
        Self { obj }
    }

    fn _text(
        &self,
        text: &str,
    ) -> Result<String, ExpandIdentifierError> {
        let tokens = TokenIterator::new(text);
        let mut out = String::new();
        for token in tokens {
            let token = token?;
            match token {
                Token::Text(text) => out.push_str(&text),
                Token::Identifier(key) => {
                    if let Some(value) = self.obj.fetch(&key) {
                        out.push_str(&value);
                    } else {
                        out.push_str(format!("${{{key}}}").as_str());
                    }
                },
                Token::NewLine => out.push('\n'),
            }
        }
        Ok(out)
    }

    /// Return the given text, containing bash-like-curly variables that are
    /// expanded with values from this struct's callback function.
    ///
    /// The text can contain BASH-like variables with each variable using
    /// the curly syntax (e.g. `A dog named ${DOG_NAME}`). BASH-like variables
    /// that do not contain curly brackets (e.g. `$DOG_NAME`) will become
    /// identifier errors.
    ///
    /// Any identifier that does not have a value, as given by the callback
    /// function will be skipped. Meaning that the BASH-like variable will be
    /// put back into the output.
    ///
    /// # Arguments
    /// * `text` - A string-slice containing the text-to-be-expanded
    ///
    /// # Errors
    /// A [`ExpandTextError`] - will be returned if:
    ///   * there are any syntactical errors with any BASH-like variables:
    ///     * Non-ASCII characters between the curly-brackets,
    ///     * Non-alpha-numeric-underscore characters between the curly-brackets,
    ///     * No characters/empty between the curly-brackets,
    ///     * Missing an opening curly-bracket, after the `$`,
    ///     * Missing a closing curly-bracket, after the identifier,
    ///     * Identifier starts with a number. Can only start with an underscore
    ///       or an ASCII-letter,
    ///     * Invalid identifier name when the identifier name contains spaces
    ///       between parts of the identifier name (e.g. `${dog name}`).
    pub fn text(
        &self,
        text: &str,
    ) -> Result<String, ExpandTextError> {
        Ok(self._text(text)?)
    }

    fn _text_strict(
        &self,
        text: &str,
    ) -> Result<String, ExpandIdentifierError> {
        let tokens = TokenIterator::new(text);
        let mut out = String::new();
        for token in tokens {
            let token = token?;
            match token {
                Token::Text(text) => out.push_str(&text),
                Token::Identifier(key) => {
                    if let Some(value) = self.obj.fetch(&key) {
                        out.push_str(&value);
                    } else {
                        return Err(
                            ExpandIdentifierError::ValueError(key),
                        );
                    }
                },
                Token::NewLine => out.push('\n'),
            }
        }
        Ok(out)
    }

    /// Return the given text, containing bash-like-curly variables that are
    /// expanded with values from the given callback-function. And return
    /// an [`ExpandTextError`] when a value cannot be found by the given
    /// callback-function
    ///
    /// The text can contain BASH-like variables with each variable using
    /// the curly syntax (e.g. `A dog named ${DOG_NAME}`). BASH-like variables
    /// that do not contain curly brackets (e.g. `$DOG_NAME`) will become
    /// identifier errors.
    ///
    /// # Arguments
    /// * `text` - A string-slice containing the text-to-be-expanded
    ///
    /// # Errors
    /// A [`ExpandTextError`] - will be returned if:
    ///   * there are any syntactical errors with any BASH-like variables:
    ///     * Non-ASCII characters between the curly-brackets,
    ///     * Non-alpha-numeric-underscore characters between the curly-brackets,
    ///     * No characters/empty between the curly-brackets,
    ///     * Missing an opening curly-bracket, after the `$`,
    ///     * Missing a closing curly-bracket, after the identifier,
    ///     * Identifier starts with a number. Can only start with an underscore
    ///       or an ASCII-letter,
    ///     * Invalid identifier name when the identifier name contains spaces
    ///       between parts of the identifier name (e.g. `${dog name}`),
    ///   * if the value for any identifier cannot be returned by the given
    ///     callback-function.
    pub fn text_strict(
        &self,
        text: &str,
    ) -> Result<String, ExpandTextError> {
        Ok(self._text_strict(text)?)
    }

    /// Return the given file's text, containing bash-like-curly variables
    /// that are expanded with values from this struct's callback function.
    ///
    /// The file-contents can contain BASH-like variables with each variable
    /// using the curly syntax (e.g. `A dog named ${DOG_NAME}`). BASH-like
    /// variables that do not contain curly brackets (e.g. `$DOG_NAME`) will
    /// become identifier errors.
    ///
    /// The `$` character can be escaped by using two `$` characters e.g. `$$`.
    ///
    /// # Arguments
    /// * path - a string-like reference to a [`str`] containing the path
    ///   that will be expanded.
    ///
    /// # Errors
    /// A [`ExpandTextError`] - will be returned if:
    ///   * there are any problems opening the given file path
    ///   * there are any syntactical errors with any BASH-like variables:
    ///     * Non-ASCII characters between the curly-brackets,
    ///     * Non-alpha-numeric-underscore characters between the
    ///       curly-brackets,
    ///     * No characters/empty between the curly-brackets,
    ///     * Missing an opening curly-bracket, after the `$`,
    ///     * Missing a closing curly-bracket, after the identifier,
    ///     * Identifier starts with a number. Can only start with an
    ///       underscore or an ASCII-letter,
    ///     * Invalid identifier name when the identifier name contains spaces
    ///       between parts of the identifier name (e.g. `${dog name}`).
    pub fn file<T>(
        &self,
        path: &T,
    ) -> Result<String, ExpandTextError>
    where
        T: AsRef<Utf8Path> + ?Sized,
    {
        let path = path.as_ref();
        let text = std::fs::read_to_string(path).map_err(|e| {
            ExpandTextError::read_file_error(path, e)
        })?;
        self._text(&text).map_err(|e| {
            ExpandTextError::identifier_error_in_file(path, e)
        })
    }

    /// Return the given file's text, containing bash-like-curly variables that
    /// are expanded with values from this struct's callback function and
    /// return an [`ExpandTextError`] if the value cannot be retrieved.
    ///
    /// The file-contents can contain BASH-like variables with each variable
    /// using the curly syntax (e.g. `A dog named ${DOG_NAME}`). BASH-like
    /// variables that do not contain curly brackets (e.g. `$DOG_NAME`) will
    /// become identifier errors.
    ///
    /// The `$` character can be escaped by using two `$` characters e.g. `$$`.
    ///
    /// # Arguments
    /// * path - a string-like reference to a [`str`] containing the path
    ///   that will be expanded.
    ///
    /// # Errors
    /// A [`ExpandTextError`] - will be returned if:
    ///   * there are any problems opening the given file path
    ///   * there are any syntactical errors with any BASH-like variables:
    ///     * Non-ASCII characters between the curly-brackets,
    ///     * Non-alpha-numeric-underscore characters between the curly-brackets,
    ///     * No characters/empty between the curly-brackets,
    ///     * Missing an opening curly-bracket, after the `$`,
    ///     * Missing a closing curly-bracket, after the identifier,
    ///     * Identifier starts with a number. Can only start with an underscore
    ///       or an ASCII-letter,
    ///     * Invalid identifier name when the identifier name contains spaces
    ///       between parts of the identifier name (e.g. `${dog name}`),
    ///   * if the value for any identifier cannot be returned by the given
    ///     callback-function.
    ///
    pub fn file_strict<T>(
        &self,
        path: &T,
    ) -> Result<String, ExpandTextError>
    where
        T: AsRef<Utf8Path> + ?Sized,
    {
        let path = path.as_ref();
        let text = std::fs::read_to_string(path).map_err(|e| {
            ExpandTextError::read_file_error(path, e)
        })?;
        self._text(&text).map_err(|e| {
            ExpandTextError::identifier_error_in_file(path, e)
        })
    }
}