feat(cli): add line by line file reversal

This commit is contained in:
Kristofers Solo 2025-01-15 15:58:27 +02:00
parent 3168fe9851
commit 36705f8c1a

View File

@ -1,6 +1,6 @@
use std::{ use std::{
fs::{read_to_string, File}, fs::{read_to_string, write},
io::{self, Write}, io::{self},
path::PathBuf, path::PathBuf,
}; };
@ -17,6 +17,9 @@ pub struct Cli {
/// Output file path (optional) /// Output file path (optional)
#[arg(short, long)] #[arg(short, long)]
pub output: Option<PathBuf>, pub output: Option<PathBuf>,
/// Reverse by line instead of the whole content
#[arg(short, long)]
pub line_by_line: bool,
} }
pub fn encode(s: &str) -> String { pub fn encode(s: &str) -> String {
@ -27,27 +30,28 @@ pub fn encode_string(s: &str) -> String {
encode(s) encode(s)
} }
pub fn encode_file(path: impl Into<PathBuf>) -> io::Result<String> { pub fn encode_file(path: impl Into<PathBuf>, line_by_line: bool) -> io::Result<String> {
let path = path.into(); let path = path.into();
let content = read_to_string(path)?; let content = read_to_string(path)?;
if line_by_line {
return Ok(content
.lines()
.map(|line| encode(line))
.collect::<Vec<String>>()
.join("\n"));
}
Ok(encode(&content)) Ok(encode(&content))
} }
pub fn write_output(content: &str, path: &PathBuf) -> io::Result<()> {
let mut file = File::create(path)?;
file.write_all(content.as_bytes())?;
Ok(())
}
pub fn process_input(cli: &Cli) -> io::Result<Option<String>> { pub fn process_input(cli: &Cli) -> io::Result<Option<String>> {
let result = if cli.file { let result = if cli.file {
encode_file(&cli.input)? encode_file(&cli.input, cli.line_by_line)?
} else { } else {
encode_string(&cli.input) encode_string(&cli.input)
}; };
if let Some(output_path) = &cli.output { if let Some(output_path) = &cli.output {
write_output(&result, &output_path)?; write(output_path, result)?;
return Ok(None); return Ok(None);
} }
Ok(Some(result)) Ok(Some(result))