shitbox/src/cmd/base64/mod.rs

135 lines
4.1 KiB
Rust
Raw Normal View History

2023-01-03 23:02:43 -05:00
use super::Cmd;
use base64::{decode, encode};
use clap::{value_parser, Arg, ArgAction, ArgMatches, Command};
use std::{
error::Error,
fs,
io::{self, Read},
};
#[derive(Debug)]
pub struct Base64 {
name: &'static str,
path: Option<crate::Path>,
}
pub const BASE_64: Base64 = Base64 {
name: "base64",
path: Some(crate::Path::UsrBin),
};
impl Cmd for Base64 {
fn name(&self) -> &str {
self.name
}
fn cli(&self) -> Command {
Command::new("base64")
.author("Nathan Fisher")
.about("Base64 encode/decode data and print to standard output")
.args([
Arg::new("INPUT")
.help("The input file to use")
.num_args(0..),
Arg::new("DECODE")
.help("Decode rather than encode")
.short('d')
.long("decode")
.action(ArgAction::SetTrue),
Arg::new("IGNORE")
.help("Ignore whitespace when decoding")
.short('i')
.long("ignore-space")
.action(ArgAction::SetTrue),
Arg::new("WRAP")
.help("Wrap encoded lines after n characters")
.short('w')
.long("wrap")
.default_value("76")
.value_parser(value_parser!(usize)),
Arg::new("VERBOSE")
.help("Display a header naming each file")
.short('v')
.long("verbose")
.action(ArgAction::SetTrue),
Arg::new("QUIET")
.help("Do not display header, even with multiple files")
.short('q')
.long("quiet")
.action(ArgAction::SetTrue),
])
}
fn run(&self, matches: Option<&ArgMatches>) -> Result<(), Box<dyn Error>> {
let Some(matches) = matches else {
return Err(Box::new(io::Error::new(io::ErrorKind::Other, "No input")));
};
let files: Vec<_> = match matches.get_many::<String>("INPUT") {
Some(c) => c.map(|x| x.clone()).collect(),
None => vec![String::from("-")],
};
let len = files.len();
for (index, file) in files.into_iter().enumerate() {
if { len > 1 || matches.get_flag("VERBOSE") } && !matches.get_flag("QUIET") {
match index {
0 => println!("===> {file} <==="),
_ => println!("\n===> {file} <==="),
};
} else if index > 0 {
println!();
}
let contents = get_contents(&file)?;
if matches.get_flag("DECODE") {
decode_base64(contents, matches.get_flag("IGNORE"))?;
} else {
encode_base64(
&contents,
match matches.get_one("WRAP") {
Some(c) => *c,
None => 76,
},
);
}
}
Ok(())
}
fn path(&self) -> Option<crate::Path> {
self.path
}
}
fn decode_base64(mut contents: String, ignore: bool) -> Result<(), Box<dyn Error>> {
if ignore {
contents.retain(|c| !c.is_whitespace());
} else {
contents = contents.replace('\n', "");
}
let decoded = decode(&contents)?.to_vec();
let output = String::from_utf8(decoded)?;
println!("{}", output.trim_end());
Ok(())
}
fn encode_base64(contents: &str, wrap: usize) {
let encoded = encode(contents.as_bytes())
.chars()
.collect::<Vec<char>>()
.chunks(wrap)
.map(|c| c.iter().collect::<String>())
.collect::<Vec<String>>();
for line in &encoded {
println!("{line}");
}
}
fn get_contents(file: &str) -> Result<String, Box<dyn Error>> {
let mut contents = String::new();
if file == "-" {
io::stdin().read_to_string(&mut contents)?;
} else {
contents = fs::read_to_string(file)?;
2023-01-03 23:02:43 -05:00
}
Ok(contents)
}