You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+42-6Lines changed: 42 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -58,23 +58,26 @@ use clap_stdin::FileOrStdin;
58
58
59
59
#[derive(Debug, Parser)]
60
60
struct Args {
61
-
contents: FileOrStdin,
61
+
input: FileOrStdin,
62
62
}
63
63
64
+
# fn main() -> anyhow::Result<()> {
64
65
let args = Args::parse();
65
-
println!("contents={}", args.contents);
66
+
println!("input={}", args.input.contents()?);
67
+
# Ok(())
68
+
# }
66
69
```
67
70
68
71
Calling this CLI:
69
72
```sh
70
73
# using stdin for positional arg value
71
74
$ echo"testing"| cargo run -- -
72
-
contents=testing
75
+
input=testing
73
76
74
77
# using filename for positional arg value
75
-
$ echo"testing">contents.txt
76
-
$ cargo run -- contents.txt
77
-
contents=testing
78
+
$ echo"testing">input.txt
79
+
$ cargo run -- input.txt
80
+
input=testing
78
81
```
79
82
80
83
## Compatible Types
@@ -100,6 +103,39 @@ $ cat myfile.txt
100
103
$ .example myfile.txt
101
104
```
102
105
106
+
## Reading from Stdin without special characters
107
+
When using [`MaybeStdin`] or [`FileOrStdin`], you can allow your users to omit the "-" character to read from `stdin` by providing a `default_value` to clap. This works with positional and optional args:
108
+
109
+
```rust,no_run
110
+
use clap::Parser;
111
+
112
+
use clap_stdin::FileOrStdin;
113
+
114
+
#[derive(Debug, Parser)]
115
+
struct Args {
116
+
#[clap(default_value = "-")]
117
+
input: FileOrStdin,
118
+
}
119
+
120
+
# fn main() -> anyhow::Result<()> {
121
+
let args = Args::parse();
122
+
println!("input={}", args.input.contents()?);
123
+
# Ok(())
124
+
# }
125
+
```
126
+
127
+
Calling this CLI:
128
+
```sh
129
+
# using stdin for positional arg value
130
+
$ echo"testing"| cargo run
131
+
input=testing
132
+
133
+
# using filename for positional arg value
134
+
$ echo"testing"> input.txt
135
+
$ cargo run -- input.txt
136
+
input=testing
137
+
```
138
+
103
139
## Using `MaybeStdin` or `FileOrStdin` multiple times
104
140
Both [`MaybeStdin`] and [`FileOrStdin`] will check at runtime if `stdin` is being read from multiple times. You can use this
105
141
as a feature if you have mutually exclusive args that should both be able to read from stdin, but know
0 commit comments