mirror of
https://github.com/kristoferssolo/sula-alus.git
synced 2025-10-21 20:00:36 +00:00
feat(cli): add line by line file reversal
This commit is contained in:
parent
3168fe9851
commit
36705f8c1a
26
src/lib.rs
26
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<PathBuf>,
|
||||
/// 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<PathBuf>) -> io::Result<String> {
|
||||
pub fn encode_file(path: impl Into<PathBuf>, line_by_line: bool) -> io::Result<String> {
|
||||
let path = path.into();
|
||||
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))
|
||||
}
|
||||
|
||||
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>> {
|
||||
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))
|
||||
|
||||
Loading…
Reference in New Issue
Block a user