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
use crate::error::{ExpandPathError, ExpandPathLexerError};

use camino::{Utf8Path, Utf8PathBuf};
use std::marker::PhantomData;
use std::path::MAIN_SEPARATOR_STR;
use std::{collections::VecDeque, convert::AsRef, string::ToString};
use unicode_segmentation::UnicodeSegmentation;

#[derive(Debug, Clone, PartialEq)]
enum Token {
    /// Represents the tilde when used as the first (wide) character and
    /// may be expanded to the users home directory
    IdentifierTilde,

    /// Represents an identifier (variable) to be expanded
    ///
    /// # Attributes
    ///
    /// * `name`- The identifier's name (variable name)
    /// * `uses_curly` - A boolean representing if curly brackets were used
    ///
    Identifier { name: String, uses_curly: bool },

    /// Represents the operating system's path-separator
    Separator,

    /// Represents any component within the path that is not an identifier.
    ///
    /// # Attributes
    ///
    /// `1` - The text
    Text(String),
}

#[derive(Clone, Debug)]
struct Parts<'a> {
    index: usize,
    started: bool,
    wide_chars: Vec<&'a str>,
}

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

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

    #[inline]
    fn nth(
        &mut self,
        index: usize,
    ) -> Option<&'a str> {
        match self.wide_chars.get(index) {
            Some(s) => Some(*s),
            None => None,
        }
    }
}

impl<'a> Parts<'a> {
    fn new(text: &'a str) -> Self {
        let wide_chars = UnicodeSegmentation::graphemes(text, true)
            .collect::<Vec<&str>>();
        Self {
            index: 0usize,
            started: false,
            wide_chars,
        }
    }

    #[inline]
    fn peek(&mut self) -> Option<&'a str> {
        let mut index = self.index;
        if self.started {
            index += 1;
        }
        self.nth(index)
    }

    #[inline]
    fn bump_index(&mut self) {
        self.index += 1;
    }

    #[inline]
    fn possible_token_count(&self) -> usize {
        let mut count = 0usize;
        for item in self.wide_chars.iter() {
            if item == &MAIN_SEPARATOR_STR {
                count += 1
            }
        }
        count = count * 2 + 1;
        count
    }

    fn extract_text(&mut self) -> String {
        let mut out = String::new();
        let mut escape = false;
        while let Some(wide_char) = self.peek() {
            if !escape {
                match wide_char {
                    "\\" => {
                        escape = true;
                        // out.push_str(wide_char);
                        self.bump_index();
                        continue;
                    },
                    "$" => break,
                    MAIN_SEPARATOR_STR => break,
                    _ => {},
                }
            }
            out.push_str(wide_char);
            escape = false;
            self.bump_index();
        }
        out
    }

    fn extract_identifier(
        &mut self
    ) -> Result<(String, bool), ExpandPathLexerError> {
        let mut start_position = 0usize;
        let mut curly = false;
        let mut uses_curly = false;
        let mut curly_start_position = 0usize;
        let mut started = false;
        let mut out = String::new();
        let mut position = 0usize;
        while let Some(wide_char) = self.peek() {
            if position == 0 {
                if wide_char != "$" {
                    return Err(
                        ExpandPathLexerError::MissingIdentifierSymbol(
                            self.index + 1,
                        ),
                    );
                }
                position += 1;
                start_position = self.index + 1;
                self.bump_index();
                continue;
            }
            if position == 1 && wide_char == "{" {
                curly = true;
                uses_curly = true;
                curly_start_position = self.index + 1;
                position += 1;
                self.bump_index();
                continue;
            }
            if !wide_char.is_ascii() {
                break;
            }
            if !started {
                if is_identifier_start(wide_char) {
                    out.push_str(wide_char);
                    self.bump_index();
                    position += 1;
                    started = true;
                    continue;
                }
                self.bump_index();
                if uses_curly && wide_char == "}" {
                    return Err(
                        ExpandPathLexerError::MissingIdentifierName(
                            self.index - 1,
                        ),
                    );
                }
                return Err(
                    ExpandPathLexerError::invalid_identifier_start_character(
                        wide_char,
                        self.index - 1,
                    ),
                );
            }
            if is_identifier(wide_char) {
                out.push_str(wide_char);
                self.bump_index();
                position += 1;
                continue;
            }
            if curly && wide_char == "}" {
                self.bump_index();
                curly = false;
            }
            break;
        }
        if curly {
            return Err(ExpandPathLexerError::MissingClosingCurly(
                curly_start_position,
            ));
        }
        if out.is_empty() {
            return Err(
                ExpandPathLexerError::MissingIdentifierName(
                    start_position,
                ),
            );
        }
        Ok((out, uses_curly))
    }
}

#[inline(always)]
fn is_identifier_start(wide_char: &str) -> bool {
    if !wide_char.is_ascii() {
        return false;
    }
    let c = wide_char.chars().next().unwrap_or_default();
    if c.is_alphabetic() {
        return true;
    }
    if c == '_' {
        return true;
    }
    false
}

#[inline(always)]
fn is_identifier(wide_char: &str) -> bool {
    if !wide_char.is_ascii() {
        return false;
    }
    let c = wide_char.chars().next().unwrap_or_default();
    if c.is_alphanumeric() {
        return true;
    }
    if c == '_' {
        return true;
    }
    false
}

fn tokenize<T>(
    text: &T
) -> Result<VecDeque<Token>, ExpandPathLexerError>
where
    T: AsRef<Utf8Path> + ?Sized,
{
    let text = text.as_ref().to_string();
    let mut parts = Parts::new(text.as_ref());

    let mut out: VecDeque<Token> =
        VecDeque::with_capacity(parts.possible_token_count());

    let mut position = 0usize;
    let mut started = false;
    while let Some(wide_char) = parts.peek() {
        if started {
            position += 1;
        } else {
            started = true;
        }
        if position == 0 && wide_char == "~" {
            if let Some(s) = parts.nth(1usize) {
                if s != MAIN_SEPARATOR_STR {
                    return Err(
                        ExpandPathLexerError::InvalidTildeUse(
                            MAIN_SEPARATOR_STR.to_string(),
                        ),
                    );
                }
            }
            parts.bump_index();
            out.push_back(Token::IdentifierTilde);
            continue;
        }
        match wide_char {
            "\\" => {
                out.push_back(Token::Text(parts.extract_text()));
                continue;
            },
            MAIN_SEPARATOR_STR => {
                parts.bump_index();
                out.push_back(Token::Separator);
                position += 1;
                continue;
            },
            "$" => {
                let (name, uses_curly) =
                    parts.extract_identifier()?;
                out.push_back(Token::Identifier {
                    name,
                    uses_curly,
                });
            },
            _ => out.push_back(Token::Text(parts.extract_text())),
        }
    }
    Ok(out)
}

#[inline(always)]
fn tokens_to_string(tokens: &VecDeque<Token>) -> String {
    let mut out = String::new();
    for token in tokens.iter() {
        match token {
            Token::IdentifierTilde => out.push('~'),
            Token::Separator => out.push_str(MAIN_SEPARATOR_STR),
            Token::Text(val) => out.push_str(val),
            Token::Identifier { name, uses_curly } => {
                out.push('$');
                if *uses_curly {
                    out.push('{');
                }
                out.push_str(name);
                if *uses_curly {
                    out.push('}');
                }
            },
        }
    }
    out
}

/// Represents a locked [`ExpandPath`] struct.
pub struct Locked;
///
/// Represents an unlocked [`ExpandPath`] struct.
pub struct Unlocked;

/// [Expand](index.html#expansion) any
/// BASH-like-[identifiers](index.html#identifier) in a path using a callback
/// function.
///
/// # Example
/// ```
/// use komichi::ExpandPath;
/// use camino::Utf8PathBuf;
///
/// fn fetch(key: &str) -> Option<String> {
///     match key {
///         "ONE" => Some("1".to_string()),
///         "TWO" => Some("two".to_string()),
///         "THREE" => Some("三".to_string()),
///         "FOUR" => Some("四".to_string()),
///         "FIVE" => Some("五".to_string()),
///         "SIX" => Some("陸".to_string()),
///         _ => None
///     }
/// }
///
/// let expand = ExpandPath::new()
///     .set_home("/a/b/c")
///     .unwrap()
///     .set_cwd("/coruscant")
///     .unwrap()
///     .set_fetch(fetch);
///
/// let paths = vec![
///     "/$ONE/${TWO}/九十九",
///     "/${ONE}/$TWO/${THREE}/${SIX}",
///     "~/${ONE}/$TWO/${THREE}/${FIVE}",
///     "${FOUR}/$FIVE/七/${SIX}",
///     "/${ONE}${TWO}/${THREE}4/\\$FIVE",
///     "${HOME}/deez/ナッツ"
/// ];
///
/// let expects = vec![
///     Utf8PathBuf::from("/1/two/九十九"),
///     Utf8PathBuf::from("/1/two/三/陸"),
///     Utf8PathBuf::from("/a/b/c/1/two/三/五"),
///     Utf8PathBuf::from("/coruscant/四/五/七/陸"),
///     Utf8PathBuf::from("/1two/三4/$FIVE"),
///     Utf8PathBuf::from("/a/b/c/deez/ナッツ"),
/// ];
///
/// for (i, path) in paths.iter().enumerate() {
///     let result = expand.path(&path).unwrap();
///     let expect = expects.get(i).unwrap();
///     assert_eq!(expect, &result);
/// }
/// ```
pub struct ExpandPath<State = Locked> {
    home: Option<Vec<Token>>,
    cwd: Option<Vec<Token>>,
    fetch: Option<fn(&str) -> Option<String>>,
    state: PhantomData<State>,
}

impl Default for ExpandPath {
    fn default() -> Self {
        Self::new()
    }
}

impl ExpandPath {
    /// Return a new [`ExpandPath`] struct.
    pub fn new() -> ExpandPath<Locked> {
        ExpandPath {
            home: None,
            cwd: None,
            fetch: None,
            state: Default::default(),
        }
    }
}

impl ExpandPath<Unlocked> {
    fn path_as_tokens(
        &self,
        path: &str,
    ) -> Result<VecDeque<Token>, ExpandPathError> {
        tokenize(&path)
            .map_err(|e| ExpandPathError::lexer_error(&path, e))
    }
    fn expand_tilde(
        &self,
        tokens: &mut VecDeque<Token>,
    ) {
        let home = match &self.home {
            Some(path) => path,
            None => return,
        };
        if let Some(token) = tokens.front() {
            match token {
                Token::IdentifierTilde => {
                    let _ = tokens.pop_front();
                },
                _ => return,
            }
        }
        for token in home.iter().rev() {
            tokens.push_front(token.clone());
        }
    }
    fn expand_home(
        &self,
        tokens: &mut VecDeque<Token>,
    ) {
        let home = match &self.home {
            Some(path) => path,
            None => return,
        };
        for i in 0..tokens.len() {
            let token = tokens.get(i).unwrap();
            if let Token::Identifier { name, .. } = token {
                if name == "HOME" {
                    let mut started = false;
                    for home_token in home.iter().rev() {
                        if !started {
                            tokens[i] = home_token.clone();
                            started = true;
                        } else {
                            tokens.insert(i, home_token.clone());
                        }
                    }
                }
            }
        }
    }

    fn expand_cwd(
        &self,
        tokens: &mut VecDeque<Token>,
    ) {
        let cwd = match &self.cwd {
            Some(path) => path,
            None => return,
        };
        if let Some(token) = tokens.front() {
            match token {
                Token::Separator => return,
                Token::IdentifierTilde => return,
                _ => {},
            }
        }
        tokens.push_front(Token::Separator);
        for token in cwd.iter().rev() {
            tokens.push_front(token.clone());
        }
    }

    fn expand_with(
        &self,
        tokens: &mut VecDeque<Token>,
    ) {
        let fetch = match self.fetch {
            Some(func) => func,
            None => return,
        };
        for i in 0..tokens.len() {
            let token = tokens.get(i).unwrap();
            if let Token::Identifier { name, .. } = token {
                if let Some(val) = fetch(name) {
                    tokens[i] = Token::Text(val)
                }
            }
        }
    }

    fn expand_strict_with(
        &self,
        tokens: &mut VecDeque<Token>,
        path: &str,
    ) -> Result<(), ExpandPathError> {
        let fetch = match self.fetch {
            Some(func) => func,
            None => return Ok(()),
        };
        // for (i, token) in tokens.iter().enumerate() {
        for i in 0..tokens.len() {
            let token = tokens.get(i).unwrap();
            if let Token::Identifier { name, .. } = token {
                match fetch(name) {
                    Some(val) => tokens[i] = Token::Text(val),
                    None => {
                        return Err(
                            ExpandPathError::identifier_expand_error(
                                &path, name,
                            ),
                        );
                    },
                }
            }
        }
        Ok(())
    }
    /// Expand the given path and return a [`Utf8PathBuf`](module@camino).
    ///
    /// # Notes
    /// * Any identifiers contained in the given path which cannot be expanded
    ///   will remain in the returned value.
    /// * If [`set_home`](struct@ExpandPath) was called, with a value, this
    ///   function will expand a beginning tilde, in the given `path` with
    ///   the value given in [`set_home`](struct@ExpandPath).
    /// * If [`set_cwd`](struct@ExpandPath) was called, with a value, this
    ///   function will prepend the CWD value to the given `path` if the
    ///   given path is not absolute or starts with a tilde.
    /// * If [`set_fetch`](struct@ExpandPath) was called, with a function/callback,
    ///   the function/callback will be used to expand any identifiers
    ///   contained in the given `path`.
    ///
    /// # Arguments
    /// * `path` - a string-like reference to a [`str`] containing the
    ///   path that will be expanded.
    ///
    /// # Errors
    /// * [`ExpandPathError`] will be returned if:
    ///   * if the given `path` is empty; or,
    ///   * if the given `path` contains an identifier which cannot be
    ///     expanded by the function given to [`set_fetch`](struct@ExpandPath); or,
    ///   * the given `path` contains an open curly bracket `{` with no preceding
    ///     dollar sign `$`; or,
    ///   * the given `path` contains an identifier that has an invalid start
    ///     character; or,
    ///   * the given `path` contains an identifier that is missing a closing
    ///     curly bracket `}`; or,
    ///   * the given `path` contains an invalid character after a starting
    ///     tilde `~`; or,
    ///
    pub fn path<T>(
        &self,
        path: &T,
    ) -> Result<Utf8PathBuf, ExpandPathError>
    where
        T: AsRef<str> + ?Sized,
    {
        let path = path.as_ref().to_string();
        if path.is_empty() {
            return Err(ExpandPathError::EmptyPathError);
        }
        let mut tokens = self.path_as_tokens(&path)?;

        self.expand_tilde(&mut tokens);
        self.expand_home(&mut tokens);
        self.expand_cwd(&mut tokens);
        self.expand_with(&mut tokens);

        let path = tokens_to_string(&tokens);
        Ok(Utf8PathBuf::from(path))
    }

    /// Expand the given path and return a [`Utf8PathBuf`](module@camino).
    ///
    /// # Notes
    /// * This differs from [`path`](struct@ExpandPath) in that an
    ///   [`ExpandPathError`] will be returned on any identifiers that cannot
    ///   be expanded by the function/callback given in
    ///   [`set_fetch`](struct@ExpandPath).
    /// * If [`set_home`](struct@ExpandPath) was called, with a value, this
    ///   function will expand a beginning tilde, in the given `path` with the
    ///   value given in [`set_home`](struct@ExpandPath).
    /// * If [`set_cwd`](struct@ExpandPath) was called, with a value, this
    ///   function will prepend the CWD value to the given `path` if the given
    ///   path is not absolute or starts with a tilde.
    /// * If [`set_fetch`](struct@ExpandPath) was called, with a callback, the
    ///   callback will be used to expand any identifiers contained in the
    ///   given `path`.
    /// * Any identifiers contained in the given `path` which cannot be
    ///   expanded will remain in the returned value.
    ///
    /// # Arguments
    /// * `path` - a string-like reference to a [`str`] containing the
    ///   path that will be expanded.
    ///
    /// # Errors
    /// * [`ExpandPathError`] will be returned if:
    ///   * if the given `path` is empty; or,
    ///   * if the given `path` contains an identifier which cannot be
    ///     expanded by the function given to [`set_fetch`](struct@ExpandPath);
    ///     or,
    ///   * the given `path` contains an open curly bracket `{` with no preceding
    ///     dollar sign `$`; or,
    ///   * the given `path` contains an identifier that has an invalid start
    ///     character; or,
    ///   * the given `path` contains an identifier that is missing a closing
    ///     curly bracket `}`; or,
    ///   * the given `path` contains an invalid character after a starting
    ///     tilde `~`; or,
    ///   * the given `path` contains an identifier name that has no value.
    ///
    pub fn path_strict<T>(
        &self,
        path: &T,
    ) -> Result<Utf8PathBuf, ExpandPathError>
    where
        T: AsRef<str> + ?Sized,
    {
        let path = path.as_ref().to_string();
        if path.is_empty() {
            return Err(ExpandPathError::EmptyPathError);
        }
        let mut tokens = self.path_as_tokens(&path)?;

        self.expand_tilde(&mut tokens);
        self.expand_home(&mut tokens);
        self.expand_cwd(&mut tokens);
        self.expand_strict_with(&mut tokens, &path)?;

        let path = tokens_to_string(&tokens);
        Ok(Utf8PathBuf::from(path))
    }
}

impl<State> ExpandPath<State> {
    fn str_as_tokens(
        &self,
        path: &str,
    ) -> Result<Vec<Token>, ExpandPathError> {
        Ok(tokenize(&path)
            .map_err(|e| ExpandPathError::lexer_error(&path, e))?
            .into_iter()
            .collect::<Vec<Token>>())
    }

    /// Set the home value to be used when expanding tildes
    ///
    /// # Arguments
    /// * `path` - a string-like reference to a [`str`] containing the
    ///   desired path to the home directory.
    ///
    /// # Errors
    /// * [`ExpandPathError`] will be returned if the given path is not an
    ///   absolute path.
    ///
    pub fn set_home<T>(
        self,
        path: &T,
    ) -> Result<ExpandPath<Unlocked>, ExpandPathError>
    where
        T: AsRef<str> + ?Sized,
    {
        let path = path.as_ref();
        let home = Utf8PathBuf::from(&path);
        if !home.is_absolute() {
            return Err(ExpandPathError::NotAbsoluteHome(
                path.to_string(),
            ));
        }
        let home = self.str_as_tokens(path)?;
        Ok(ExpandPath {
            home: Some(home),
            cwd: self.cwd,
            fetch: self.fetch,
            state: PhantomData::<Unlocked>,
        })
    }
    /// Set the current working directory ("CWD") value to be used when
    /// expanding non absolute paths.
    ///
    /// # Arguments
    /// * `path` - a string-like reference to a [`str`] containing the
    ///   desired path to the CWD.
    ///
    /// # Errors
    /// * [`ExpandPathError`] will be returned if the given path is not an
    ///   absolute path.
    ///
    pub fn set_cwd<T>(
        self,
        path: &T,
    ) -> Result<ExpandPath<Unlocked>, ExpandPathError>
    where
        T: AsRef<str> + ?Sized,
    {
        let path = path.as_ref();
        let cwd = Utf8PathBuf::from(&path);
        if !cwd.is_absolute() {
            return Err(ExpandPathError::NotAbsoluteCwd(
                path.to_string(),
            ));
        }
        let cwd = self.str_as_tokens(path)?;
        Ok(ExpandPath {
            home: self.home,
            cwd: Some(cwd),
            fetch: self.fetch,
            state: PhantomData::<Unlocked>,
        })
    }

    /// Set the fetch function
    pub fn set_fetch(
        self,
        fetch: fn(&str) -> Option<String>,
    ) -> ExpandPath<Unlocked> {
        ExpandPath {
            home: self.home,
            cwd: self.cwd,
            fetch: Some(fetch),
            state: PhantomData::<Unlocked>,
        }
    }
}