Skip to content

Allow cli/ tool to read data from stdin #108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 28 additions & 9 deletions cli/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::fmt;
use std::str::FromStr;
use std::io::{self, Read, Write};

use anyhow::{anyhow, Error, Result};
use multibase::Base;
Expand All @@ -19,24 +20,42 @@ enum Mode {
/// The base to use for encoding.
#[structopt(short = "b", long = "base", default_value = "base58btc")]
base: StrBase,
/// The data need to be encoded.
/// The data to encode. Reads from stdin if not provided.
#[structopt(short = "i", long = "input")]
input: String,
input: Option<String>,
},
#[structopt(name = "decode")]
Decode {
/// The data need to be decoded.
/// The data to decode. Reads from stdin if not provided.
#[structopt(short = "i", long = "input")]
input: String,
input: Option<String>,
},
}

fn main() -> Result<()> {
env_logger::init();
let opts = Opts::from_args();
match opts.mode {
Mode::Encode { base, input } => encode(base, input.as_bytes()),
Mode::Decode { input } => decode(&input),
Mode::Encode { base, input } => {
let input_bytes = if let Some(s) = input {
s.into_bytes()
} else {
let mut buf = Vec::new();
io::stdin().read_to_end(&mut buf)?;
buf
};
encode(base, &input_bytes)
}
Mode::Decode { input } => {
let input_str = if let Some(s) = input {
s
} else {
let mut buf = String::new();
io::stdin().read_to_string(&mut buf)?;
buf
};
decode(&input_str)
}
}
}

Expand Down Expand Up @@ -119,13 +138,13 @@ impl From<StrBase> for Base {
fn encode(base: StrBase, input: &[u8]) -> Result<()> {
log::debug!("Encode {:?} with {}", input, base);
let result = multibase::encode(base.into(), input);
println!("Result: {}", result);
print!("{}", result);
Ok(())
}

fn decode(input: &str) -> Result<()> {
log::debug!("Decode {:?}", input);
let (base, result) = multibase::decode(input)?;
println!("Result: {}, {:?}", StrBase(base), result);
let (_, result) = multibase::decode(input)?;
io::stdout().write_all(&result)?;
Ok(())
}