Skip to content

Commit 7895fe6

Browse files
author
syui
committed
add pipe
1 parent 291ab5a commit 7895fe6

File tree

4 files changed

+38
-9
lines changed

4 files changed

+38
-9
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@ edition = "2018"
88
url = "1.7"
99
failure = "0.1"
1010
structopt = "0.2"
11+
atty = "0.2"

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
the cli tool of the url decode written in rust.
12

23
```sh
34
$ cargo test

src/main.rs

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,51 @@ use url::percent_encoding::percent_decode;
22

33
use structopt::StructOpt;
44
use failure::Error;
5+
use std::io::{self, Read};
6+
use atty::Stream;
57
pub type Result<T> = std::result::Result<T, Error>;
68

79
#[derive(StructOpt, Debug)]
810
struct Opt {
911
#[structopt(name = "INPUT")]
10-
input: String,
12+
input: Option<String>,
1113
}
1214

15+
fn read_from_stdin() -> Result<String> {
16+
let mut buf = String::new();
17+
let stdin = io::stdin();
18+
let mut handle = stdin.lock();
19+
handle.read_to_string(&mut buf)?;
20+
Ok(buf)
21+
}
22+
23+
fn is_stdin(input: Option<&String>) -> bool {
24+
let is_request = match input {
25+
Some(i) if i == "-" => true,
26+
_ => false,
27+
};
28+
let is_pipe = ! atty::is(Stream::Stdin);
29+
is_request || is_pipe
30+
}
31+
32+
1333
fn main() -> Result<()> {
1434
let opt = Opt::from_args();
15-
Ok(println!("{}", decode(&opt.input)?))
16-
}
1735

18-
//fn main() -> Result<()> {
19-
// let args: Vec<String> = std::env::args().collect();
20-
// let input = &args[1];
21-
//
22-
// Ok(println!("{}", decode(input)?))
23-
//}
36+
if opt.input.is_none() && ! is_stdin(opt.input.as_ref()) {
37+
Opt::clap().print_help()?;
38+
std::process::exit(1);
39+
}
40+
let input = match opt.input {
41+
Some(i) => i,
42+
None => read_from_stdin()?
43+
};
44+
if input.is_empty() {
45+
Opt::clap().get_matches().usage();
46+
}
47+
48+
Ok(println!("{}", decode(&input)?))
49+
}
2450

2551
fn decode(input: &str) -> Result<String> {
2652
let decoded = percent_decode(input.as_bytes()).decode_utf8()?;

0 commit comments

Comments
 (0)