-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlib.rs
2227 lines (2063 loc) · 72.6 KB
/
lib.rs
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Wax provides opinionated and portable globs that can be matched against file paths and
//! directory trees. Globs use a familiar syntax and support expressive features with semantics
//! that emphasize component boundaries.
//!
//! See the [repository documentation](https://github.com/olson-sean-k/wax/blob/master/README.md)
//! for details about glob expressions and patterns.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_favicon_url = "https://raw.githubusercontent.com/olson-sean-k/wax/master/doc/wax-favicon.svg?sanitize=true"
)]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/olson-sean-k/wax/master/doc/wax.svg?sanitize=true"
)]
#![deny(
clippy::cast_lossless,
clippy::checked_conversions,
clippy::cloned_instead_of_copied,
clippy::explicit_into_iter_loop,
clippy::filter_map_next,
clippy::flat_map_option,
clippy::from_iter_instead_of_collect,
clippy::if_not_else,
clippy::manual_ok_or,
clippy::map_unwrap_or,
clippy::match_same_arms,
clippy::redundant_closure_for_method_calls,
clippy::redundant_else,
clippy::unreadable_literal,
clippy::unused_self
)]
mod capture;
mod diagnostics;
mod encode;
mod filter;
pub mod query;
mod rule;
mod token;
pub mod walk;
/// Re-exports of commonly used items.
///
/// This module anonymously re-exports traits for matching [`Program`]s against file paths and
/// directory trees. A glob import of this module can be used instead of individual imports of
/// these traits.
///
/// # Examples
///
/// ```rust,no_run,ignore
/// use wax::prelude::*;
/// use wax::Glob;
///
/// // This code requires the `Entry` and `FileIterator` traits.
/// let glob = Glob::new("**/*.(?i){jpg,jpeg}").unwrap();
/// for entry in glob.walk("textures").not(["**/.*/**"]).unwrap().flatten() {
/// println!("JPEG: {:?}", entry.path());
/// }
/// ```
pub mod prelude {
pub use crate::query::LocatedError as _;
#[cfg(feature = "walk")]
pub use crate::walk::{Entry as _, FileIterator as _, PathExt as _};
pub use crate::Program as _;
}
#[cfg(feature = "miette")]
use miette::Diagnostic;
use regex::Regex;
use std::borrow::{Borrow, Cow};
use std::cmp::Ordering;
use std::convert::Infallible;
use std::ffi::OsStr;
use std::fmt::{self, Debug, Display, Formatter};
use std::path::{Path, PathBuf};
use std::str::{self, FromStr};
use thiserror::Error;
use crate::diagnostics::LocatedError;
use crate::encode::CompileError;
use crate::query::{CapturingToken, DepthVariance, TextVariance, When};
use crate::rule::{Checked, RuleError};
use crate::token::{
ConcatenationTree, ExpressionMetadata, ParseError, Token, TokenTree, Tokenized,
};
#[cfg(feature = "walk")]
use crate::walk::WalkError;
pub use crate::capture::MatchedText;
#[cfg(windows)]
const PATHS_ARE_CASE_INSENSITIVE: bool = true;
#[cfg(not(windows))]
const PATHS_ARE_CASE_INSENSITIVE: bool = false;
trait CharExt: Sized {
/// Returns `true` if the character (code point) has casing.
fn has_casing(self) -> bool;
}
impl CharExt for char {
fn has_casing(self) -> bool {
self.is_lowercase() != self.is_uppercase()
}
}
trait StrExt {
/// Returns `true` if any characters in the string have casing.
fn has_casing(&self) -> bool;
}
impl StrExt for str {
fn has_casing(&self) -> bool {
self.chars().any(CharExt::has_casing)
}
}
/// A representation of a glob expression.
///
/// This trait is implemented by types that can be converted into a [`Program`], such as `str`
/// slices and compiled [`Program`] types like [`Glob`]. APIs that accept patterns typically do so
/// via this trait.
///
/// # Examples
///
/// [`Result`] types also implement this trait when the success type is a [`Program`] and the error
/// type is [`BuildError`]. This means that APIs that accept a `Pattern` can also accept the
/// intermediate result of constructing a [`Program`] without the need to explicitly inspect the
/// inner result first (error handling can be deferred).
///
/// ```rust
/// use wax::{Glob, Program};
///
/// # fn fallible() -> Result<(), wax::BuildError> {
/// // The inner results of `any` are not checked via `?` and can be passed directly to the
/// // outermost `any` call. This is true of all APIs that accept `Pattern`.
/// #[rustfmt::skip]
/// let any = wax::any([
/// wax::any([Glob::new("**/*.txt")]),
/// wax::any([
/// "**/*.pdf",
/// "**/*.tex",
/// ]),
/// ])?; // Defer error handling until the here.
/// # Ok(())
/// # }
/// ```
///
/// [`BuildError`]: crate::BuildError
/// [`Glob`]: crate::Glob
/// [`Program`]: crate::Program
/// [`Result`]: std::result::Result
pub trait Pattern<'t>:
TryInto<Checked<Self::Tokens>, Error = <Self as Pattern<'t>>::Error>
{
type Tokens: TokenTree<'t>;
type Error: Into<BuildError>;
}
impl<'t, T> Pattern<'t> for Result<T, BuildError>
where
T: Into<Checked<T::Tokens>> + Pattern<'t>,
{
type Tokens = <T as Pattern<'t>>::Tokens;
type Error = BuildError;
}
impl<'t> Pattern<'t> for &'t str {
type Tokens = Tokenized<'t, ExpressionMetadata>;
type Error = BuildError;
}
/// A compiled [`Pattern`] that can be inspected and matched against paths.
///
/// [`Glob::partition`]: crate::Glob::partition
/// [`Path`]: std::path::Path
/// [`PathBuf`]: std::path::PathBuf
/// [`Pattern`]: crate::Pattern
pub trait Program<'t>: Pattern<'t, Error = Infallible> {
/// Returns `true` if the [candidate path][`CandidatePath`] matches the pattern.
///
/// This is a logical operation and does **not** interact with the file system.
///
/// [`CandidatePath`]: crate::CandidatePath
fn is_match<'p>(&self, path: impl Into<CandidatePath<'p>>) -> bool;
/// Gets the [matched text][`MatchedText`] in a [`CandidatePath`], if any.
///
/// Returns `None` if the [`CandidatePath`] does not match the pattern. This is a logical
/// operation and does **not** interact with the file system.
///
/// [`CandidatePath`]: crate::CandidatePath
/// [`MatchedText`]: crate::MatchedText
fn matched<'p>(&self, path: &'p CandidatePath<'_>) -> Option<MatchedText<'p>>;
/// Gets the depth variance of the pattern.
fn depth(&self) -> DepthVariance;
/// Gets the text variance of the pattern.
///
/// # Examples
///
/// Text variance can be used to determine if a pattern can be trivially represented by an
/// equivalent native path using platform file system APIs.
///
/// ```rust
/// use std::path::Path;
/// use wax::{Glob, Program};
///
/// let glob = Glob::new("/home/user").unwrap();
/// let text = glob.text();
/// let path = text.as_path();
///
/// assert_eq!(path, Some(Path::new("/home/user")));
/// ```
fn text(&self) -> TextVariance<'t>;
/// Describes when the pattern matches candidate paths with a root.
///
/// A glob expression that begins with a separator `/` has a root, but less trivial patterns
/// like `/**` and `</root:1,>` can also root an expression. Some `Program` types may have
/// indeterminate roots and may match both candidate paths with and without a root. In this
/// case, this functions returns [`Sometimes`].
///
/// [`Sometimes`]: crate::query::When::Sometimes
fn has_root(&self) -> When;
/// Describes when the pattern matches candidate paths exhaustively.
///
/// A glob expression is exhaustive if, given a matched candidate path, it necessarily matches
/// any and all sub-trees of that path. For example, given the pattern `.local/**` and the
/// matched path `.local/bin`, any and all paths beneath `.local/bin` also match the pattern.
///
/// Patterns that end with tree wildcards are more obviously exhaustive, but less trivial
/// patterns like `<<?>/>`, `<doc/<*/:3,>>`, and `{a/**,b/**}` can also be exhaustive. Patterns
/// with alternations may only be exhaustive for some matched paths. In this case, this
/// function returns [`Sometimes`].
///
/// [`Sometimes`]: crate::query::When::Sometimes
fn is_exhaustive(&self) -> When;
}
/// General errors concerning [`Program`]s.
///
/// This is the most general error and each of its variants exposes a particular error type that
/// describes the details of its associated error condition. This error is not used in any Wax APIs
/// directly, but can be used to encapsulate the more specific errors that are.
///
/// # Examples
///
/// To encapsulate different errors in the Wax API behind a function, convert them into a
/// `GlobError` via `?`.
///
/// ```rust,no_run,ignore
/// use std::path::PathBuf;
/// use wax::{Glob, GlobError};
///
/// fn read_all(directory: impl Into<PathBuf>) -> Result<Vec<u8>, GlobError> {
/// let mut data = Vec::new();
/// let glob = Glob::new("**/*.data.bin")?;
/// for entry in glob.walk(directory) {
/// let entry = entry?;
/// // ...
/// }
/// Ok(data)
/// }
/// ```
///
/// [`Program`]: crate::Program
#[cfg_attr(feature = "miette", derive(Diagnostic))]
#[derive(Debug, Error)]
#[error(transparent)]
pub enum GlobError {
#[cfg_attr(feature = "miette", diagnostic(transparent))]
Build(BuildError),
#[cfg(feature = "walk")]
#[cfg_attr(docsrs, doc(cfg(feature = "walk")))]
#[cfg_attr(feature = "miette", diagnostic(code = "wax::glob::walk"))]
Walk(WalkError),
}
impl From<BuildError> for GlobError {
fn from(error: BuildError) -> Self {
GlobError::Build(error)
}
}
#[cfg(feature = "walk")]
impl From<WalkError> for GlobError {
fn from(error: WalkError) -> Self {
GlobError::Walk(error)
}
}
// TODO: `Diagnostic` is implemented with macros for brevity and to ensure complete coverage of
// features. However, this means that documentation does not annotate the implementation with
// a feature flag requirement. If possible, perhaps in a later version of Rust, close this
// gap.
/// Describes errors that occur when building a [`Program`] from a glob expression.
///
/// Glob expressions may fail to build if they cannot be parsed, violate rules, or cannot be
/// compiled. Parsing errors occur when a glob expression has invalid syntax. Patterns must also
/// follow rules as described in the [repository
/// documentation](https://github.com/olson-sean-k/wax/blob/master/README.md), which are designed
/// to avoid nonsense expressions and ambiguity. Lastly, compilation errors occur **only if the
/// size of the compiled program is too large** (all other compilation errors are considered
/// internal bugs and will panic).
///
/// When the `miette` feature is enabled, this and other error types implement the [`Diagnostic`]
/// trait. Due to a technical limitation, this may not be properly annotated in API documentation.
///
/// [`Diagnostic`]: miette::Diagnostic
/// [`Program`]: crate::Program
#[cfg_attr(feature = "miette", derive(Diagnostic))]
#[cfg_attr(feature = "miette", diagnostic(transparent))]
#[derive(Clone, Debug, Error)]
#[error(transparent)]
pub struct BuildError {
kind: BuildErrorKind,
}
impl BuildError {
/// Gets [`LocatedError`]s detailing the errors within a glob expression.
///
/// This function returns an [`Iterator`] over the [`LocatedError`]s that detail where and why
/// an error occurred when the error has associated [`Span`]s within a glob expression. For
/// errors with no such associated information, the [`Iterator`] yields no items, such as
/// compilation errors.
///
/// # Examples
///
/// [`LocatedError`]s can be used to provide information to users about which parts of a glob
/// expression are associated with an error.
///
/// ```rust
/// use wax::Glob;
///
/// // This glob expression violates rules. The error handling code prints details about the
/// // alternation where the violation occurred.
/// let expression = "**/{foo,**/bar,baz}";
/// match Glob::new(expression) {
/// Ok(glob) => {
/// // ...
/// },
/// Err(error) => {
/// eprintln!("{}", error);
/// for error in error.locations() {
/// let (start, n) = error.span();
/// let fragment = &expression[start..][..n];
/// eprintln!("in sub-expression `{}`: {}", fragment, error);
/// }
/// },
/// }
/// ```
///
/// [`Glob`]: crate::Glob
/// [`Glob::partition`]: crate::Glob::partition
/// [`Iterator`]: std::iter::Iterator
/// [`LocatedError`]: crate::query::LocatedError
/// [`Span`]: crate::query::Span
pub fn locations(&self) -> impl Iterator<Item = &dyn LocatedError> {
let locations: Vec<_> = match self.kind {
BuildErrorKind::Parse(ref error) => error
.locations()
.iter()
.map(|location| location as &dyn LocatedError)
.collect(),
BuildErrorKind::Rule(ref error) => error
.locations()
.iter()
.map(|location| location as &dyn LocatedError)
.collect(),
_ => vec![],
};
locations.into_iter()
}
}
impl From<BuildErrorKind> for BuildError {
fn from(kind: BuildErrorKind) -> Self {
BuildError { kind }
}
}
impl From<CompileError> for BuildError {
fn from(error: CompileError) -> Self {
BuildError {
kind: BuildErrorKind::Compile(error),
}
}
}
impl From<Infallible> for BuildError {
fn from(_: Infallible) -> Self {
unreachable!()
}
}
impl<'t> From<ParseError<'t>> for BuildError {
fn from(error: ParseError<'t>) -> Self {
BuildError {
kind: BuildErrorKind::Parse(error.into_owned()),
}
}
}
impl<'t> From<RuleError<'t>> for BuildError {
fn from(error: RuleError<'t>) -> Self {
BuildError {
kind: BuildErrorKind::Rule(error.into_owned()),
}
}
}
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
#[cfg_attr(feature = "miette", derive(Diagnostic))]
enum BuildErrorKind {
#[error(transparent)]
#[cfg_attr(feature = "miette", diagnostic(transparent))]
Compile(CompileError),
#[error(transparent)]
#[cfg_attr(feature = "miette", diagnostic(transparent))]
Parse(ParseError<'static>),
#[error(transparent)]
#[cfg_attr(feature = "miette", diagnostic(transparent))]
Rule(RuleError<'static>),
}
/// Path that can be matched against a [`Program`].
///
/// `CandidatePath`s are always UTF-8 encoded. On some platforms this requires a lossy conversion
/// that uses Unicode replacement codepoints `�` whenever a part of a path cannot be represented as
/// valid UTF-8 (such as Windows). This means that some byte sequences cannot be matched, though
/// this is uncommon in practice.
///
/// [`Program`]: crate::Program
#[derive(Clone)]
pub struct CandidatePath<'b> {
text: Cow<'b, str>,
}
impl<'b> CandidatePath<'b> {
/// Clones any borrowed data into an owning instance.
pub fn into_owned(self) -> CandidatePath<'static> {
CandidatePath {
text: self.text.into_owned().into(),
}
}
}
impl AsRef<str> for CandidatePath<'_> {
fn as_ref(&self) -> &str {
self.text.as_ref()
}
}
impl Debug for CandidatePath<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.text)
}
}
impl Display for CandidatePath<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.text)
}
}
impl<'b> From<&'b OsStr> for CandidatePath<'b> {
fn from(text: &'b OsStr) -> Self {
CandidatePath {
text: text.to_string_lossy(),
}
}
}
impl<'b> From<&'b Path> for CandidatePath<'b> {
fn from(path: &'b Path) -> Self {
CandidatePath::from(path.as_os_str())
}
}
impl<'b> From<&'b str> for CandidatePath<'b> {
fn from(text: &'b str) -> Self {
CandidatePath { text: text.into() }
}
}
/// Program that can be matched against paths and directory trees.
///
/// `Glob`s are constructed from strings called glob expressions that resemble Unix paths
/// consisting of nominal components delimited by separators. Glob expressions support various
/// patterns that match and capture specified text in a path. These patterns can be used to
/// logically match individual paths and to semantically match and walk directory trees.
///
/// # Examples
///
/// A `Glob` can be used to determine if a path matches a pattern via the [`Program`] trait.
///
/// ```rust
/// use wax::{Glob, Program};
///
/// let glob = Glob::new("*.png").unwrap();
/// assert!(glob.is_match("apple.png"));
/// ```
///
/// Patterns form captures, which can be used to isolate matching sub-text.
///
/// ```rust
/// use wax::{CandidatePath, Glob, Program};
///
/// let glob = Glob::new("**/{*.{go,rs}}").unwrap();
/// let candidate = CandidatePath::from("src/lib.rs");
/// assert_eq!("lib.rs", glob.matched(&candidate).unwrap().get(2).unwrap());
/// ```
///
/// To match a `Glob` against a directory tree, the [`walk`] function can be used to get an
/// iterator over matching paths.
///
/// ```rust,no_run,ignore
/// use wax::walk::Entry;
/// use wax::Glob;
///
/// let glob = Glob::new("**/*.(?i){jpg,jpeg}").unwrap();
/// for entry in glob.walk("./Pictures") {
/// let entry = entry.unwrap();
/// println!("JPEG: {:?}", entry.path());
/// }
/// ```
///
/// [`Program`]: crate::Program
/// [`walk`]: crate::Glob::walk
#[derive(Clone, Debug)]
pub struct Glob<'t> {
tree: Checked<Tokenized<'t, ExpressionMetadata>>,
program: Regex,
}
impl<'t> Glob<'t> {
// TODO: Document pattern syntax in the crate documentation and refer to it here.
/// Constructs a [`Glob`] from a glob expression.
///
/// A glob expression is UTF-8 encoded text that resembles a Unix path consisting of nominal
/// components delimited by separators and patterns that can be matched against native paths.
///
/// # Errors
///
/// Returns an error if the glob expression fails to build. See [`BuildError`].
///
/// [`Glob`]: crate::Glob
/// [`BuildError`]: crate::BuildError
pub fn new(expression: &'t str) -> Result<Self, BuildError> {
let tree = parse_and_check(expression)?;
let program = Glob::compile::<Tokenized<_>>(tree.as_ref())?;
Ok(Glob { tree, program })
}
// TODO: Describe what an empty glob is. In particular, define what it does and does not match.
pub fn empty() -> Self {
Glob::new("").expect("failed to build empty glob")
}
// TODO: Describe what a tree glob is.
pub fn tree() -> Self {
Glob::new("**").expect("failed to build tree glob")
}
// TODO: Describe why and when the `Glob` postfix is `None`.
/// Partitions a [`Glob`] into an invariant [`PathBuf`] prefix and variant [`Glob`] postfix.
///
/// The invariant prefix contains no glob patterns nor other variant components and therefore
/// can be interpreted as a native path. The [`Glob`] postfix is variant and contains the
/// remaining components that follow the prefix. For example, the glob expression
/// `.local/**/*.log` would produce the path `.local` and glob `**/*.log`. It is possible for
/// either partition to be empty.
///
/// Literal components may be considered variant if they contain characters with casing and the
/// configured case sensitivity differs from the target platform's file system. For example,
/// the case-insensitive literal expression `(?i)photos` is considered variant on Unix and
/// invariant on Windows, because the literal `photos` resolves differently in Unix file system
/// APIs.
///
/// Partitioning a [`Glob`] allows any invariant prefix to be used as a native path to
/// establish a working directory or to interpret semantic components that are not recognized
/// by globs, such as parent directory `..` components.
///
/// Partitioned [`Glob`]s are never rooted. If the glob expression has a root component, then
/// it is always included in the invariant [`PathBuf`] prefix.
///
/// # Examples
///
/// To match paths against a [`Glob`] while respecting semantic components, the invariant
/// prefix and candidate path can be canonicalized. The following example canonicalizes both
/// the working directory joined with the prefix as well as the candidate path and then
/// attempts to match the [`Glob`] if the candidate path contains the prefix.
///
/// ```rust,no_run
/// use dunce; // Avoids UNC paths on Windows.
/// use std::path::Path;
/// use wax::{Glob, Program};
///
/// let path: &Path = /* ... */ // Candidate path.
/// # Path::new("");
///
/// let directory = Path::new("."); // Working directory.
/// let (prefix, glob) = Glob::new("../../src/**").unwrap().partition();
/// let prefix = dunce::canonicalize(directory.join(&prefix)).unwrap();
/// if dunce::canonicalize(path)
/// .unwrap()
/// .strip_prefix(&prefix)
/// .ok()
/// .zip(glob)
/// .map_or(false, |(path, glob)| glob.is_match(path))
/// {
/// // ...
/// }
/// ```
///
/// [`Glob`]: crate::Glob
/// [`ParseError`]: crate::ParseError
/// [`PathBuf`]: std::path::PathBuf
/// [`RuleError`]: crate::RuleError
/// [`walk`]: crate::Glob::walk
pub fn partition(self) -> (PathBuf, Option<Self>) {
let Glob { tree, .. } = self;
let (prefix, tree) = tree.partition();
(
prefix,
tree.map(|tree| {
let program = Glob::compile::<Tokenized<_>>(tree.as_ref())
.expect("failed to compile partitioned glob");
Glob { tree, program }
}),
)
}
// TODO: Describe what an empty glob is and how this relates to `Glob::partition`.
pub fn partition_or_empty(self) -> (PathBuf, Self) {
let (prefix, glob) = self.partition();
(prefix, glob.unwrap_or_else(Glob::empty))
}
// TODO: Describe what a tree glob is and how this relates to `Glob::partition`.
pub fn partition_or_tree(self) -> (PathBuf, Self) {
let (prefix, glob) = self.partition();
(prefix, glob.unwrap_or_else(Glob::tree))
}
/// Clones any borrowed data into an owning instance.
///
/// # Examples
///
/// `Glob`s borrow data in the corresponding glob expression. To move a `Glob` beyond the scope
/// of a glob expression, clone the data with this function.
///
/// ```rust
/// use wax::{BuildError, Glob};
///
/// fn local() -> Result<Glob<'static>, BuildError> {
/// let expression = String::from("**/*.txt");
/// Glob::new(&expression).map(Glob::into_owned)
/// }
/// ```
pub fn into_owned(self) -> Glob<'static> {
let Glob { tree, program } = self;
Glob {
tree: tree.into_owned(),
program,
}
}
/// Gets metadata for capturing sub-expressions.
///
/// This function returns an iterator over capturing tokens, which describe the index and
/// location of sub-expressions that capture [matched text][`MatchedText`]. For example, in the
/// expression `src/**/*.rs`, both `**` and `*` form captures.
///
/// [`MatchedText`]: crate::MatchedText
pub fn captures(&self) -> impl '_ + Clone + Iterator<Item = CapturingToken> {
self.tree
.as_ref()
.as_token()
.concatenation()
.iter()
.filter(|token| token.is_capturing())
.enumerate()
.map(|(index, token)| CapturingToken::new(index + 1, *token.annotation()))
}
/// Returns `true` if the glob has literals that have non-nominal semantics on the target
/// platform.
///
/// The most notable semantic literals are the relative path components `.` and `..`, which
/// refer to a current and parent directory on Unix and Windows operating systems,
/// respectively. These are interpreted as literals in glob expressions, and so only logically
/// match paths that contain these exact nominal components (semantic meaning is lost).
///
/// See [`Glob::partition`].
///
/// [`Glob::partition`]: crate::Glob::partition
pub fn has_semantic_literals(&self) -> bool {
self.tree
.as_ref()
.as_token()
.literals()
.any(|(_, literal)| literal.is_semantic_literal())
}
pub fn is_empty(&self) -> bool {
self.tree.as_ref().as_token().is_empty()
}
fn compile<T>(tree: impl Borrow<T>) -> Result<Regex, CompileError>
where
T: ConcatenationTree<'t>,
{
encode::compile(tree)
}
}
impl Display for Glob<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.tree.as_ref().expression())
}
}
impl FromStr for Glob<'static> {
type Err = BuildError;
fn from_str(expression: &str) -> Result<Self, Self::Err> {
Glob::new(expression).map(Glob::into_owned)
}
}
impl<'t> Pattern<'t> for Glob<'t> {
type Tokens = Tokenized<'t, ExpressionMetadata>;
type Error = Infallible;
}
impl<'t> Program<'t> for Glob<'t> {
fn is_match<'p>(&self, path: impl Into<CandidatePath<'p>>) -> bool {
let path = path.into();
self.program.is_match(path.as_ref())
}
fn matched<'p>(&self, path: &'p CandidatePath<'_>) -> Option<MatchedText<'p>> {
self.program.captures(path.as_ref()).map(From::from)
}
fn depth(&self) -> DepthVariance {
self.tree.as_ref().as_token().variance().into()
}
fn text(&self) -> TextVariance<'t> {
self.tree.as_ref().as_token().variance().into()
}
fn has_root(&self) -> When {
self.tree.as_ref().as_token().has_root()
}
fn is_exhaustive(&self) -> When {
self.tree.as_ref().as_token().is_exhaustive()
}
}
impl<'t> TryFrom<&'t str> for Glob<'t> {
type Error = BuildError;
fn try_from(expression: &'t str) -> Result<Self, Self::Error> {
Glob::new(expression)
}
}
/// Combinator that matches any of its component [`Program`]s.
///
/// An instance of `Any` is constructed using the [`any`] function, which combines multiple
/// [`Program`]s for more ergonomic and efficient matching.
///
/// [`any`]: crate::any
/// [`Program`]: crate::Program
#[derive(Clone, Debug)]
pub struct Any<'t> {
tree: Checked<Token<'t, ()>>,
program: Regex,
}
impl<'t> Any<'t> {
fn compile(token: &Token<'t, ()>) -> Result<Regex, CompileError> {
encode::compile::<Token<_>>(token)
}
}
impl<'t> Pattern<'t> for Any<'t> {
type Tokens = Token<'t, ()>;
type Error = Infallible;
}
impl<'t> Program<'t> for Any<'t> {
fn is_match<'p>(&self, path: impl Into<CandidatePath<'p>>) -> bool {
let path = path.into();
self.program.is_match(path.as_ref())
}
fn matched<'p>(&self, path: &'p CandidatePath<'_>) -> Option<MatchedText<'p>> {
self.program.captures(path.as_ref()).map(From::from)
}
fn depth(&self) -> DepthVariance {
self.tree.as_ref().as_token().variance().into()
}
fn text(&self) -> TextVariance<'t> {
self.tree.as_ref().as_token().variance().into()
}
fn has_root(&self) -> When {
self.tree.as_ref().as_token().has_root()
}
fn is_exhaustive(&self) -> When {
self.tree.as_ref().as_token().is_exhaustive()
}
}
// TODO: It may be useful to use dynamic dispatch via trait objects instead. This would allow for a
// variety of types to be composed in an `any` call and would be especially useful if
// additional combinators are introduced.
/// Constructs a combinator that matches if any of its input [`Pattern`]s match.
///
/// This function accepts an [`IntoIterator`] with items that implement [`Pattern`], such as
/// [`Glob`] and `&str`. The output [`Any`] implements [`Program`] by matching its component
/// [`Program`]s. [`Any`] is often more ergonomic and efficient than matching individually against
/// multiple [`Program`]s.
///
/// [`Any`] groups all captures and therefore only exposes the complete text of a match. It is not
/// possible to index a particular capturing token in the component patterns. Combinators only
/// support logical matching and cannot be used to semantically match (walk) a directory tree.
///
/// # Examples
///
/// To match a path against multiple patterns, the patterns can first be combined into an [`Any`].
///
/// ```rust
/// use wax::{Glob, Program};
///
/// let any = wax::any([
/// "src/**/*.rs",
/// "tests/**/*.rs",
/// "doc/**/*.md",
/// "pkg/**/PKGBUILD",
/// ])
/// .unwrap();
/// assert!(any.is_match("src/lib.rs"));
/// ```
///
/// [`Glob`]s and other compiled [`Program`]s can also be composed into an [`Any`].
///
/// ```rust
/// use wax::{Glob, Program};
///
/// let red = Glob::new("**/red/**/*.txt").unwrap();
/// let blue = Glob::new("**/*blue*.txt").unwrap();
/// assert!(wax::any([red, blue]).unwrap().is_match("red/potion.txt"));
/// ```
///
/// This function can only combine patterns of the same type, but intermediate combinators can be
/// used to combine different types into a single combinator.
///
/// ```rust
/// use wax::{Glob, Program};
///
/// # fn fallible() -> Result<(), wax::BuildError> {
/// let glob = Glob::new("**/*.txt")?;
///
/// // ...
///
/// #[rustfmt::skip]
/// let any = wax::any([
/// wax::any([glob]),
/// wax::any([
/// "**/*.pdf",
/// "**/*.tex",
/// ]),
/// ])?;
/// assert!(any.is_match("doc/lattice.tex"));
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if any of the inputs fail to build. If the inputs are a compiled [`Program`]
/// type such as [`Glob`], then this only occurs if the compiled program is too large.
///
/// [`Any`]: crate::Any
/// [`Glob`]: crate::Glob
/// [`IntoIterator`]: std::iter::IntoIterator
/// [`Pattern`]: crate::Pattern
/// [`Program`]: crate::Program
pub fn any<'t, I>(patterns: I) -> Result<Any<'t>, BuildError>
where
I: IntoIterator,
I::Item: Pattern<'t>,
{
let tree = Checked::any(
patterns
.into_iter()
.map(TryInto::try_into)
.collect::<Result<Vec<_>, _>>()
.map_err(Into::into)?,
);
let program = Any::compile(tree.as_ref())?;
Ok(Any { tree, program })
}
// TODO: This function blindly escapes meta-characters, even if they are already escaped. Ignore
// escaped meta-characters in the input.
/// Escapes text as a literal glob expression.
///
/// This function escapes any and all meta-characters in the given string, such that all text is
/// interpreted as a literal or separator when read as a glob expression.
///
/// # Examples
///
/// This function can be used to escape opaque strings, such as a string obtained from a user that
/// must be interpreted literally.
///
/// ```rust
/// use wax::Glob;
///
/// // An opaque file name that this code does not construct.
/// let name: String = {
/// /* ... */
/// # String::from("file.txt")
/// };
///
/// // Do not allow patterns in `name`.
/// let expression = format!("{}{}", "**/", wax::escape(&name));
/// if let Ok(glob) = Glob::new(&expression) { /* ... */ }
/// ```
///
/// Sometimes part of a path contains numerous meta-characters. This function can be used to
/// reliably escape them while making the unescaped part of the expression a bit easier to read.
///
/// ```rust
/// use wax::Glob;
///
/// let expression = format!("{}{}", "logs/**/", wax::escape("ingest[01](L).txt"));
/// let glob = Glob::new(&expression).unwrap();
/// ```
// It is possible to call this function using a mutable reference, which may appear to mutate the
// parameter in place.
#[must_use]
pub fn escape(unescaped: &str) -> Cow<str> {
const ESCAPE: char = '\\';
if unescaped.chars().any(is_meta_character) {
let mut escaped = String::new();
for x in unescaped.chars() {
if is_meta_character(x) {
escaped.push(ESCAPE);
}
escaped.push(x);
}
escaped.into()
}
else {
unescaped.into()
}
}
// TODO: Is it possible for `:` and `,` to be contextual meta-characters?
/// Returns `true` if the given character is a meta-character.
///
/// This function does **not** return `true` for contextual meta-characters that may only be
/// escaped in particular contexts, such as hyphens `-` in character class expressions. To detect
/// these characters, use [`is_contextual_meta_character`].
///
/// [`is_contextual_meta_character`]: crate::is_contextual_meta_character
pub const fn is_meta_character(x: char) -> bool {
matches!(
x,
'?' | '*' | '$' | ':' | '<' | '>' | '(' | ')' | '[' | ']' | '{' | '}' | ','
)
}
/// Returns `true` if the given character is a contextual meta-character.
///
/// Contextual meta-characters may only be escaped in particular contexts, such as hyphens `-` in
/// character class expressions. Elsewhere, they are interpreted as literals. To detect
/// non-contextual meta-characters, use [`is_meta_character`].
///
/// [`is_meta_character`]: crate::is_meta_character
pub const fn is_contextual_meta_character(x: char) -> bool {
matches!(x, '-')
}
fn parse_and_check(