From 36705f8c1afa79fc032793329c5b2dda0f037faf Mon Sep 17 00:00:00 2001 From: Kristofers Solo Date: Wed, 15 Jan 2025 15:58:27 +0200 Subject: [PATCH] feat(cli): add line by line file reversal --- src/lib.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index df7a5c2..a76f622 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ use std::{ - fs::{read_to_string, File}, - io::{self, Write}, + fs::{read_to_string, write}, + io::{self}, path::PathBuf, }; @@ -17,6 +17,9 @@ pub struct Cli { /// Output file path (optional) #[arg(short, long)] pub output: Option, + /// Reverse by line instead of the whole content + #[arg(short, long)] + pub line_by_line: bool, } pub fn encode(s: &str) -> String { @@ -27,27 +30,28 @@ pub fn encode_string(s: &str) -> String { encode(s) } -pub fn encode_file(path: impl Into) -> io::Result { +pub fn encode_file(path: impl Into, line_by_line: bool) -> io::Result { let path = path.into(); let content = read_to_string(path)?; + if line_by_line { + return Ok(content + .lines() + .map(|line| encode(line)) + .collect::>() + .join("\n")); + } 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> { let result = if cli.file { - encode_file(&cli.input)? + encode_file(&cli.input, cli.line_by_line)? } else { encode_string(&cli.input) }; if let Some(output_path) = &cli.output { - write_output(&result, &output_path)?; + write(output_path, result)?; return Ok(None); } Ok(Some(result))