2023-01-13 01:08:32 -05:00
|
|
|
use super::Cmd;
|
2023-01-21 18:25:09 -05:00
|
|
|
use crate::args;
|
|
|
|
use clap::{Arg, Command};
|
2023-01-07 11:44:35 -05:00
|
|
|
use std::{
|
|
|
|
fs::File,
|
|
|
|
io::{self, BufRead, BufReader, ErrorKind, Write},
|
|
|
|
};
|
|
|
|
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
|
|
|
|
|
2023-01-13 01:08:32 -05:00
|
|
|
#[derive(Debug, Default)]
|
|
|
|
pub struct Rev;
|
2023-01-07 11:44:35 -05:00
|
|
|
|
|
|
|
impl Cmd for Rev {
|
|
|
|
fn cli(&self) -> clap::Command {
|
2023-01-13 01:08:32 -05:00
|
|
|
Command::new("rev")
|
2023-01-07 11:44:35 -05:00
|
|
|
.about("reverse lines characterwise")
|
|
|
|
.author("Nathan Fisher")
|
|
|
|
.args([
|
2023-01-21 18:25:09 -05:00
|
|
|
args::header(),
|
|
|
|
args::color(),
|
2023-01-07 11:44:35 -05:00
|
|
|
Arg::new("file")
|
|
|
|
.help("if file is '-' read from stdin")
|
|
|
|
.num_args(0..),
|
|
|
|
])
|
|
|
|
}
|
|
|
|
|
|
|
|
fn run(&self, matches: Option<&clap::ArgMatches>) -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
let Some(matches) = matches else {
|
|
|
|
return Err(Box::new(io::Error::new(ErrorKind::Other, "No input")));
|
|
|
|
};
|
|
|
|
let files: Vec<_> = match matches.get_many::<String>("file") {
|
|
|
|
Some(c) => c.cloned().collect(),
|
|
|
|
None => vec![String::from("-")],
|
|
|
|
};
|
|
|
|
let color = match matches.get_one::<String>("color").map(String::as_str) {
|
|
|
|
Some("always") => ColorChoice::Always,
|
|
|
|
Some("ansi") => ColorChoice::AlwaysAnsi,
|
|
|
|
Some("auto") => {
|
|
|
|
if atty::is(atty::Stream::Stdout) {
|
|
|
|
ColorChoice::Auto
|
|
|
|
} else {
|
|
|
|
ColorChoice::Never
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => ColorChoice::Never,
|
|
|
|
};
|
|
|
|
for (index, file) in files.into_iter().enumerate() {
|
2023-01-21 18:25:09 -05:00
|
|
|
if matches.get_flag("header") {
|
2023-01-07 11:44:35 -05:00
|
|
|
let mut stdout = StandardStream::stdout(color);
|
|
|
|
stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
|
|
|
|
match index {
|
|
|
|
0 => writeln!(stdout, "===> {file} <==="),
|
|
|
|
_ => writeln!(stdout, "\n===> {file} <==="),
|
|
|
|
}?;
|
|
|
|
stdout.reset()?;
|
|
|
|
}
|
|
|
|
rev_file(&file)?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn path(&self) -> Option<crate::Path> {
|
2023-01-13 01:08:32 -05:00
|
|
|
Some(crate::Path::UsrBin)
|
2023-01-07 11:44:35 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn rev_file(file: &str) -> Result<(), io::Error> {
|
|
|
|
let reader: Box<dyn BufRead> = if file == "-" {
|
|
|
|
Box::new(BufReader::new(io::stdin()))
|
|
|
|
} else {
|
|
|
|
let buf = File::open(file)?;
|
|
|
|
Box::new(BufReader::new(buf))
|
|
|
|
};
|
|
|
|
for line in reader.lines() {
|
|
|
|
println!("{}", line.unwrap().chars().rev().collect::<String>());
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|