-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
value_parser.rs
2712 lines (2538 loc) · 82.6 KB
/
value_parser.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
use std::convert::TryInto;
use std::ops::RangeBounds;
use crate::builder::Str;
use crate::builder::StyledStr;
use crate::parser::ValueSource;
use crate::util::AnyValue;
use crate::util::AnyValueId;
/// Parse/validate argument values
///
/// Specified with [`Arg::value_parser`][crate::Arg::value_parser].
///
/// `ValueParser` defines how to convert a raw argument value into a validated and typed value for
/// use within an application.
///
/// See
/// - [`value_parser!`][crate::value_parser] for automatically selecting an implementation for a given type
/// - [`ValueParser::new`] for additional [`TypedValueParser`] that can be used
///
/// # Example
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("color")
/// .long("color")
/// .value_parser(["always", "auto", "never"])
/// .default_value("auto")
/// )
/// .arg(
/// clap::Arg::new("hostname")
/// .long("hostname")
/// .value_parser(clap::builder::NonEmptyStringValueParser::new())
/// .action(clap::ArgAction::Set)
/// .required(true)
/// )
/// .arg(
/// clap::Arg::new("port")
/// .long("port")
/// .value_parser(clap::value_parser!(u16).range(3000..))
/// .action(clap::ArgAction::Set)
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(
/// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
/// ).unwrap();
///
/// let color: &String = m.get_one("color")
/// .expect("default");
/// assert_eq!(color, "auto");
///
/// let hostname: &String = m.get_one("hostname")
/// .expect("required");
/// assert_eq!(hostname, "rust-lang.org");
///
/// let port: u16 = *m.get_one("port")
/// .expect("required");
/// assert_eq!(port, 3001);
/// ```
pub struct ValueParser(ValueParserInner);
enum ValueParserInner {
// Common enough to optimize and for possible values
Bool,
// Common enough to optimize
String,
// Common enough to optimize
OsString,
// Common enough to optimize
PathBuf,
Other(Box<dyn AnyValueParser>),
}
impl ValueParser {
/// Custom parser for argument values
///
/// Pre-existing [`TypedValueParser`] implementations include:
/// - `Fn(&str) -> Result<T, E>`
/// - [`EnumValueParser`] and [`PossibleValuesParser`] for static enumerated values
/// - [`BoolishValueParser`] and [`FalseyValueParser`] for alternative `bool` implementations
/// - [`RangedI64ValueParser`] and [`RangedU64ValueParser`]
/// - [`NonEmptyStringValueParser`]
///
/// # Example
///
/// ```rust
/// # use clap_builder as clap;
/// type EnvVar = (String, Option<String>);
/// fn parse_env_var(env: &str) -> Result<EnvVar, std::io::Error> {
/// if let Some((var, value)) = env.split_once('=') {
/// Ok((var.to_owned(), Some(value.to_owned())))
/// } else {
/// Ok((env.to_owned(), None))
/// }
/// }
///
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("env")
/// .value_parser(clap::builder::ValueParser::new(parse_env_var))
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "key=value"]).unwrap();
/// let port: &EnvVar = m.get_one("env")
/// .expect("required");
/// assert_eq!(*port, ("key".into(), Some("value".into())));
/// ```
pub fn new<P>(other: P) -> Self
where
P: TypedValueParser,
{
Self(ValueParserInner::Other(Box::new(other)))
}
/// [`bool`] parser for argument values
///
/// See also:
/// - [`BoolishValueParser`] for different human readable bool representations
/// - [`FalseyValueParser`] for assuming non-false is true
///
/// # Example
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("download")
/// .value_parser(clap::value_parser!(bool))
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
/// let port: bool = *m.get_one("download")
/// .expect("required");
/// assert_eq!(port, true);
///
/// assert!(cmd.try_get_matches_from_mut(["cmd", "forever"]).is_err());
/// ```
pub const fn bool() -> Self {
Self(ValueParserInner::Bool)
}
/// [`String`] parser for argument values
///
/// See also:
/// - [`NonEmptyStringValueParser`]
///
/// # Example
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("port")
/// .value_parser(clap::value_parser!(String))
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "80"]).unwrap();
/// let port: &String = m.get_one("port")
/// .expect("required");
/// assert_eq!(port, "80");
/// ```
pub const fn string() -> Self {
Self(ValueParserInner::String)
}
/// [`OsString`][std::ffi::OsString] parser for argument values
///
/// # Example
///
/// ```rust
/// # #[cfg(unix)] {
/// # use clap_builder as clap;
/// # use clap::{Command, Arg, builder::ValueParser};
/// use std::ffi::OsString;
/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
/// let r = Command::new("myprog")
/// .arg(
/// Arg::new("arg")
/// .required(true)
/// .value_parser(ValueParser::os_string())
/// )
/// .try_get_matches_from(vec![
/// OsString::from("myprog"),
/// OsString::from_vec(vec![0xe9])
/// ]);
///
/// assert!(r.is_ok());
/// let m = r.unwrap();
/// let arg: &OsString = m.get_one("arg")
/// .expect("required");
/// assert_eq!(arg.as_bytes(), &[0xe9]);
/// # }
/// ```
pub const fn os_string() -> Self {
Self(ValueParserInner::OsString)
}
/// [`PathBuf`][std::path::PathBuf] parser for argument values
///
/// # Example
///
/// ```rust
/// # use clap_builder as clap;
/// # use std::path::PathBuf;
/// # use std::path::Path;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("output")
/// .value_parser(clap::value_parser!(PathBuf))
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "hello.txt"]).unwrap();
/// let port: &PathBuf = m.get_one("output")
/// .expect("required");
/// assert_eq!(port, Path::new("hello.txt"));
///
/// assert!(cmd.try_get_matches_from_mut(["cmd", ""]).is_err());
/// ```
pub const fn path_buf() -> Self {
Self(ValueParserInner::PathBuf)
}
}
impl ValueParser {
/// Parse into a `AnyValue`
///
/// When `arg` is `None`, an external subcommand value is being parsed.
pub(crate) fn parse_ref(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
source: ValueSource,
) -> Result<AnyValue, crate::Error> {
self.any_value_parser().parse_ref_(cmd, arg, value, source)
}
/// Describes the content of `AnyValue`
pub fn type_id(&self) -> AnyValueId {
self.any_value_parser().type_id()
}
/// Reflect on enumerated value properties
///
/// Error checking should not be done with this; it is mostly targeted at user-facing
/// applications like errors and completion.
pub fn possible_values(
&self,
) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
self.any_value_parser().possible_values()
}
fn any_value_parser(&self) -> &dyn AnyValueParser {
match &self.0 {
ValueParserInner::Bool => &BoolValueParser {},
ValueParserInner::String => &StringValueParser {},
ValueParserInner::OsString => &OsStringValueParser {},
ValueParserInner::PathBuf => &PathBufValueParser {},
ValueParserInner::Other(o) => o.as_ref(),
}
}
}
/// Convert a [`TypedValueParser`] to [`ValueParser`]
///
/// # Example
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("hostname")
/// .long("hostname")
/// .value_parser(clap::builder::NonEmptyStringValueParser::new())
/// .action(clap::ArgAction::Set)
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(
/// ["cmd", "--hostname", "rust-lang.org"]
/// ).unwrap();
///
/// let hostname: &String = m.get_one("hostname")
/// .expect("required");
/// assert_eq!(hostname, "rust-lang.org");
/// ```
impl<P> From<P> for ValueParser
where
P: TypedValueParser + Send + Sync + 'static,
{
fn from(p: P) -> Self {
Self::new(p)
}
}
impl From<_AnonymousValueParser> for ValueParser {
fn from(p: _AnonymousValueParser) -> Self {
p.0
}
}
/// Create an `i64` [`ValueParser`] from a `N..M` range
///
/// See [`RangedI64ValueParser`] for more control over the output type.
///
/// See also [`RangedU64ValueParser`]
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("port")
/// .long("port")
/// .value_parser(3000..4000)
/// .action(clap::ArgAction::Set)
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
/// let port: i64 = *m.get_one("port")
/// .expect("required");
/// assert_eq!(port, 3001);
/// ```
impl From<std::ops::Range<i64>> for ValueParser {
fn from(value: std::ops::Range<i64>) -> Self {
let inner = RangedI64ValueParser::<i64>::new().range(value.start..value.end);
Self::from(inner)
}
}
/// Create an `i64` [`ValueParser`] from a `N..=M` range
///
/// See [`RangedI64ValueParser`] for more control over the output type.
///
/// See also [`RangedU64ValueParser`]
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("port")
/// .long("port")
/// .value_parser(3000..=4000)
/// .action(clap::ArgAction::Set)
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
/// let port: i64 = *m.get_one("port")
/// .expect("required");
/// assert_eq!(port, 3001);
/// ```
impl From<std::ops::RangeInclusive<i64>> for ValueParser {
fn from(value: std::ops::RangeInclusive<i64>) -> Self {
let inner = RangedI64ValueParser::<i64>::new().range(value.start()..=value.end());
Self::from(inner)
}
}
/// Create an `i64` [`ValueParser`] from a `N..` range
///
/// See [`RangedI64ValueParser`] for more control over the output type.
///
/// See also [`RangedU64ValueParser`]
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("port")
/// .long("port")
/// .value_parser(3000..)
/// .action(clap::ArgAction::Set)
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
/// let port: i64 = *m.get_one("port")
/// .expect("required");
/// assert_eq!(port, 3001);
/// ```
impl From<std::ops::RangeFrom<i64>> for ValueParser {
fn from(value: std::ops::RangeFrom<i64>) -> Self {
let inner = RangedI64ValueParser::<i64>::new().range(value.start..);
Self::from(inner)
}
}
/// Create an `i64` [`ValueParser`] from a `..M` range
///
/// See [`RangedI64ValueParser`] for more control over the output type.
///
/// See also [`RangedU64ValueParser`]
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("port")
/// .long("port")
/// .value_parser(..3000)
/// .action(clap::ArgAction::Set)
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap();
/// let port: i64 = *m.get_one("port")
/// .expect("required");
/// assert_eq!(port, 80);
/// ```
impl From<std::ops::RangeTo<i64>> for ValueParser {
fn from(value: std::ops::RangeTo<i64>) -> Self {
let inner = RangedI64ValueParser::<i64>::new().range(..value.end);
Self::from(inner)
}
}
/// Create an `i64` [`ValueParser`] from a `..=M` range
///
/// See [`RangedI64ValueParser`] for more control over the output type.
///
/// See also [`RangedU64ValueParser`]
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("port")
/// .long("port")
/// .value_parser(..=3000)
/// .action(clap::ArgAction::Set)
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap();
/// let port: i64 = *m.get_one("port")
/// .expect("required");
/// assert_eq!(port, 80);
/// ```
impl From<std::ops::RangeToInclusive<i64>> for ValueParser {
fn from(value: std::ops::RangeToInclusive<i64>) -> Self {
let inner = RangedI64ValueParser::<i64>::new().range(..=value.end);
Self::from(inner)
}
}
/// Create an `i64` [`ValueParser`] from a `..` range
///
/// See [`RangedI64ValueParser`] for more control over the output type.
///
/// See also [`RangedU64ValueParser`]
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("port")
/// .long("port")
/// .value_parser(..)
/// .action(clap::ArgAction::Set)
/// .required(true)
/// );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
/// let port: i64 = *m.get_one("port")
/// .expect("required");
/// assert_eq!(port, 3001);
/// ```
impl From<std::ops::RangeFull> for ValueParser {
fn from(value: std::ops::RangeFull) -> Self {
let inner = RangedI64ValueParser::<i64>::new().range(value);
Self::from(inner)
}
}
/// Create a [`ValueParser`] with [`PossibleValuesParser`]
///
/// See [`PossibleValuesParser`] for more flexibility in creating the
/// [`PossibleValue`][crate::builder::PossibleValue]s.
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("color")
/// .long("color")
/// .value_parser(["always", "auto", "never"])
/// .default_value("auto")
/// );
///
/// let m = cmd.try_get_matches_from_mut(
/// ["cmd", "--color", "never"]
/// ).unwrap();
///
/// let color: &String = m.get_one("color")
/// .expect("default");
/// assert_eq!(color, "never");
/// ```
impl<P, const C: usize> From<[P; C]> for ValueParser
where
P: Into<super::PossibleValue>,
{
fn from(values: [P; C]) -> Self {
let inner = PossibleValuesParser::from(values);
Self::from(inner)
}
}
/// Create a [`ValueParser`] with [`PossibleValuesParser`]
///
/// See [`PossibleValuesParser`] for more flexibility in creating the
/// [`PossibleValue`][crate::builder::PossibleValue]s.
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// let possible = vec!["always", "auto", "never"];
/// let mut cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("color")
/// .long("color")
/// .value_parser(possible)
/// .default_value("auto")
/// );
///
/// let m = cmd.try_get_matches_from_mut(
/// ["cmd", "--color", "never"]
/// ).unwrap();
///
/// let color: &String = m.get_one("color")
/// .expect("default");
/// assert_eq!(color, "never");
/// ```
impl<P> From<Vec<P>> for ValueParser
where
P: Into<super::PossibleValue>,
{
fn from(values: Vec<P>) -> Self {
let inner = PossibleValuesParser::from(values);
Self::from(inner)
}
}
impl std::fmt::Debug for ValueParser {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match &self.0 {
ValueParserInner::Bool => f.debug_struct("ValueParser::bool").finish(),
ValueParserInner::String => f.debug_struct("ValueParser::string").finish(),
ValueParserInner::OsString => f.debug_struct("ValueParser::os_string").finish(),
ValueParserInner::PathBuf => f.debug_struct("ValueParser::path_buf").finish(),
ValueParserInner::Other(o) => write!(f, "ValueParser::other({:?})", o.type_id()),
}
}
}
impl Clone for ValueParser {
fn clone(&self) -> Self {
Self(match &self.0 {
ValueParserInner::Bool => ValueParserInner::Bool,
ValueParserInner::String => ValueParserInner::String,
ValueParserInner::OsString => ValueParserInner::OsString,
ValueParserInner::PathBuf => ValueParserInner::PathBuf,
ValueParserInner::Other(o) => ValueParserInner::Other(o.clone_any()),
})
}
}
/// A type-erased wrapper for [`TypedValueParser`].
trait AnyValueParser: Send + Sync + 'static {
fn parse_ref(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
) -> Result<AnyValue, crate::Error>;
fn parse_ref_(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
_source: ValueSource,
) -> Result<AnyValue, crate::Error> {
self.parse_ref(cmd, arg, value)
}
fn parse(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: std::ffi::OsString,
) -> Result<AnyValue, crate::Error>;
fn parse_(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: std::ffi::OsString,
_source: ValueSource,
) -> Result<AnyValue, crate::Error> {
self.parse(cmd, arg, value)
}
/// Describes the content of `AnyValue`
fn type_id(&self) -> AnyValueId;
fn possible_values(
&self,
) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>>;
fn clone_any(&self) -> Box<dyn AnyValueParser>;
}
impl<T, P> AnyValueParser for P
where
T: std::any::Any + Clone + Send + Sync + 'static,
P: TypedValueParser<Value = T>,
{
fn parse_ref(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
) -> Result<AnyValue, crate::Error> {
let value = ok!(TypedValueParser::parse_ref(self, cmd, arg, value));
Ok(AnyValue::new(value))
}
fn parse_ref_(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
source: ValueSource,
) -> Result<AnyValue, crate::Error> {
let value = ok!(TypedValueParser::parse_ref_(self, cmd, arg, value, source));
Ok(AnyValue::new(value))
}
fn parse(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: std::ffi::OsString,
) -> Result<AnyValue, crate::Error> {
let value = ok!(TypedValueParser::parse(self, cmd, arg, value));
Ok(AnyValue::new(value))
}
fn parse_(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: std::ffi::OsString,
source: ValueSource,
) -> Result<AnyValue, crate::Error> {
let value = ok!(TypedValueParser::parse_(self, cmd, arg, value, source));
Ok(AnyValue::new(value))
}
fn type_id(&self) -> AnyValueId {
AnyValueId::of::<T>()
}
fn possible_values(
&self,
) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
P::possible_values(self)
}
fn clone_any(&self) -> Box<dyn AnyValueParser> {
Box::new(self.clone())
}
}
/// Parse/validate argument values
///
/// As alternatives to implementing `TypedValueParser`,
/// - Use `Fn(&str) -> Result<T, E>` which implements `TypedValueParser`
/// - [`TypedValueParser::map`] or [`TypedValueParser::try_map`] to adapt an existing `TypedValueParser`
///
/// See `ValueParserFactory` to register `TypedValueParser::Value` with
/// [`value_parser!`][crate::value_parser].
///
/// # Example
///
/// ```rust
/// # #[cfg(feature = "error-context")] {
/// # use clap_builder as clap;
/// # use clap::error::ErrorKind;
/// # use clap::error::ContextKind;
/// # use clap::error::ContextValue;
/// #[derive(Clone)]
/// struct Custom(u32);
///
/// #[derive(Clone)]
/// struct CustomValueParser;
///
/// impl clap::builder::TypedValueParser for CustomValueParser {
/// type Value = Custom;
///
/// fn parse_ref(
/// &self,
/// cmd: &clap::Command,
/// arg: Option<&clap::Arg>,
/// value: &std::ffi::OsStr,
/// ) -> Result<Self::Value, clap::Error> {
/// let inner = clap::value_parser!(u32);
/// let val = inner.parse_ref(cmd, arg, value)?;
///
/// const INVALID_VALUE: u32 = 10;
/// if val == INVALID_VALUE {
/// let mut err = clap::Error::new(ErrorKind::ValueValidation)
/// .with_cmd(cmd);
/// if let Some(arg) = arg {
/// err.insert(ContextKind::InvalidArg, ContextValue::String(arg.to_string()));
/// }
/// err.insert(ContextKind::InvalidValue, ContextValue::String(INVALID_VALUE.to_string()));
/// return Err(err);
/// }
///
/// Ok(Custom(val))
/// }
/// }
/// # }
/// ```
pub trait TypedValueParser: Clone + Send + Sync + 'static {
/// Argument's value type
type Value: Send + Sync + Clone;
/// Parse the argument value
///
/// When `arg` is `None`, an external subcommand value is being parsed.
fn parse_ref(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, crate::Error>;
/// Parse the argument value
///
/// When `arg` is `None`, an external subcommand value is being parsed.
fn parse_ref_(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
_source: ValueSource,
) -> Result<Self::Value, crate::Error> {
self.parse_ref(cmd, arg, value)
}
/// Parse the argument value
///
/// When `arg` is `None`, an external subcommand value is being parsed.
fn parse(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: std::ffi::OsString,
) -> Result<Self::Value, crate::Error> {
self.parse_ref(cmd, arg, &value)
}
/// Parse the argument value
///
/// When `arg` is `None`, an external subcommand value is being parsed.
fn parse_(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: std::ffi::OsString,
_source: ValueSource,
) -> Result<Self::Value, crate::Error> {
self.parse(cmd, arg, value)
}
/// Reflect on enumerated value properties
///
/// Error checking should not be done with this; it is mostly targeted at user-facing
/// applications like errors and completion.
fn possible_values(
&self,
) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
None
}
/// Adapt a `TypedValueParser` from one value to another
///
/// # Example
///
/// ```rust
/// # use clap_builder as clap;
/// # use clap::Command;
/// # use clap::Arg;
/// # use clap::builder::TypedValueParser as _;
/// # use clap::builder::BoolishValueParser;
/// let cmd = Command::new("mycmd")
/// .arg(
/// Arg::new("flag")
/// .long("flag")
/// .action(clap::ArgAction::SetTrue)
/// .value_parser(
/// BoolishValueParser::new()
/// .map(|b| -> usize {
/// if b { 10 } else { 5 }
/// })
/// )
/// );
///
/// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap();
/// assert!(matches.contains_id("flag"));
/// assert_eq!(
/// matches.get_one::<usize>("flag").copied(),
/// Some(10)
/// );
///
/// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap();
/// assert!(matches.contains_id("flag"));
/// assert_eq!(
/// matches.get_one::<usize>("flag").copied(),
/// Some(5)
/// );
/// ```
fn map<T, F>(self, func: F) -> MapValueParser<Self, F>
where
T: Send + Sync + Clone,
F: Fn(Self::Value) -> T + Clone,
{
MapValueParser::new(self, func)
}
/// Adapt a `TypedValueParser` from one value to another
///
/// # Example
///
/// ```rust
/// # use clap_builder as clap;
/// # use std::ffi::OsString;
/// # use std::ffi::OsStr;
/// # use std::path::PathBuf;
/// # use std::path::Path;
/// # use clap::Command;
/// # use clap::Arg;
/// # use clap::builder::TypedValueParser as _;
/// # use clap::builder::OsStringValueParser;
/// let cmd = Command::new("mycmd")
/// .arg(
/// Arg::new("flag")
/// .long("flag")
/// .value_parser(
/// OsStringValueParser::new()
/// .try_map(verify_ext)
/// )
/// );
///
/// fn verify_ext(os: OsString) -> Result<PathBuf, &'static str> {
/// let path = PathBuf::from(os);
/// if path.extension() != Some(OsStr::new("rs")) {
/// return Err("only Rust files are supported");
/// }
/// Ok(path)
/// }
///
/// let error = cmd.clone().try_get_matches_from(["mycmd", "--flag", "foo.txt"]).unwrap_err();
/// error.print();
///
/// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "foo.rs"]).unwrap();
/// assert!(matches.contains_id("flag"));
/// assert_eq!(
/// matches.get_one::<PathBuf>("flag").map(|s| s.as_path()),
/// Some(Path::new("foo.rs"))
/// );
/// ```
fn try_map<T, E, F>(self, func: F) -> TryMapValueParser<Self, F>
where
F: Fn(Self::Value) -> Result<T, E> + Clone + Send + Sync + 'static,
T: Send + Sync + Clone,
E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
{
TryMapValueParser::new(self, func)
}
}
impl<F, T, E> TypedValueParser for F
where
F: Fn(&str) -> Result<T, E> + Clone + Send + Sync + 'static,
E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
T: Send + Sync + Clone,
{
type Value = T;
fn parse_ref(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, crate::Error> {
let value = ok!(value.to_str().ok_or_else(|| {
crate::Error::invalid_utf8(
cmd,
crate::output::Usage::new(cmd).create_usage_with_title(&[]),
)
}));
let value = ok!((self)(value).map_err(|e| {
let arg = arg
.map(|a| a.to_string())
.unwrap_or_else(|| "...".to_owned());
crate::Error::value_validation(arg, value.to_owned(), e.into()).with_cmd(cmd)
}));
Ok(value)
}
}
/// Implementation for [`ValueParser::string`]
///
/// Useful for composing new [`TypedValueParser`]s
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub struct StringValueParser {}
impl StringValueParser {
/// Implementation for [`ValueParser::string`]
pub fn new() -> Self {
Self {}
}
}
impl TypedValueParser for StringValueParser {
type Value = String;
fn parse_ref(
&self,
cmd: &crate::Command,
arg: Option<&crate::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, crate::Error> {
TypedValueParser::parse(self, cmd, arg, value.to_owned())
}
fn parse(
&self,
cmd: &crate::Command,
_arg: Option<&crate::Arg>,
value: std::ffi::OsString,
) -> Result<Self::Value, crate::Error> {
let value = ok!(value.into_string().map_err(|_| {
crate::Error::invalid_utf8(
cmd,
crate::output::Usage::new(cmd).create_usage_with_title(&[]),
)
}));
Ok(value)
}
}
impl Default for StringValueParser {
fn default() -> Self {
Self::new()
}
}
/// Implementation for [`ValueParser::os_string`]
///
/// Useful for composing new [`TypedValueParser`]s
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub struct OsStringValueParser {}
impl OsStringValueParser {
/// Implementation for [`ValueParser::os_string`]
pub fn new() -> Self {
Self {}
}
}
impl TypedValueParser for OsStringValueParser {