2023-01-13 01:08:32 -05:00
|
|
|
use super::Cmd;
|
2023-02-05 00:51:11 -05:00
|
|
|
use clap::Command;
|
2023-02-06 18:57:28 -05:00
|
|
|
use shitbox::args;
|
2023-01-07 11:44:35 -05:00
|
|
|
use std::{
|
|
|
|
fs::File,
|
2023-02-04 08:54:27 -05:00
|
|
|
io::{self, BufRead, BufReader, Write},
|
2023-01-07 11:44:35 -05:00
|
|
|
};
|
|
|
|
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
|
|
|
|
|
2023-04-17 23:27:57 -04:00
|
|
|
#[derive(Debug)]
|
2023-01-13 01:08:32 -05:00
|
|
|
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")
|
2023-02-05 00:51:11 -05:00
|
|
|
.args([args::header(), args::color(), args::file()])
|
2023-01-07 11:44:35 -05:00
|
|
|
}
|
|
|
|
|
2023-02-04 08:54:27 -05:00
|
|
|
fn run(&self, matches: &clap::ArgMatches) -> Result<(), Box<dyn std::error::Error>> {
|
2023-01-07 11:44:35 -05:00
|
|
|
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,
|
|
|
|
};
|
2023-01-27 00:15:04 -05:00
|
|
|
if let Some(files) = matches.get_many::<String>("file") {
|
|
|
|
for (index, file) in files.enumerate() {
|
|
|
|
if matches.get_flag("HEADER") {
|
|
|
|
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()?;
|
|
|
|
}
|
2023-02-20 23:00:35 -05:00
|
|
|
rev_file(file)?;
|
2023-01-07 11:44:35 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-02-05 23:50:59 -05:00
|
|
|
fn path(&self) -> Option<shitbox::Path> {
|
|
|
|
Some(shitbox::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(())
|
|
|
|
}
|