sula_alus/
lib.rs

1use clap::Parser;
2use std::{
3    fs::{read_to_string, write},
4    io::{self},
5    path::PathBuf,
6};
7
8/// A CLI tool for reversing text content
9///
10/// This tool provides functionality to reverse text, either from direct input
11/// or from files. It supports both whole-content reversal and line-by-line reversal.
12#[derive(Debug, Parser)]
13#[command(author, version, about, long_about = None)]
14pub struct Cli {
15    /// The input text or file path to hash
16    pub input: String,
17    /// Specify if the input is a file
18    #[arg(short, long)]
19    pub file: bool,
20    /// Output file path (optional)
21    #[arg(short, long)]
22    pub output: Option<PathBuf>,
23    /// Reverse by line instead of the whole content
24    #[arg(short, long)]
25    pub line_by_line: bool,
26}
27
28/// Reverses the provided string
29#[inline]
30#[must_use]
31pub fn encode(s: &str) -> String {
32    s.chars().rev().collect()
33}
34/// Reverses a string directly
35///
36/// This is a convenience wrapper around the `encode` function.
37#[inline]
38#[must_use]
39pub fn encode_string(s: &str) -> String {
40    encode(s)
41}
42
43/// Reverses the contents of a file
44///
45/// # Errors
46/// - The file cannot be read
47/// - The file content is not valid UTF-8
48pub fn encode_file(path: impl Into<PathBuf>, line_by_line: bool) -> io::Result<String> {
49    let path = path.into();
50    let content = read_to_string(path)?;
51    if line_by_line {
52        return Ok(content
53            .lines()
54            .map(encode)
55            .collect::<Vec<String>>()
56            .join("\n"));
57    }
58    Ok(encode(&content))
59}
60
61/// Processes the input based on CLI arguments
62///
63/// # Errors
64/// - There was an error reading or writing files
65pub fn process_input(cli: &Cli) -> io::Result<Option<String>> {
66    let result = if cli.file {
67        encode_file(&cli.input, cli.line_by_line)?
68    } else {
69        encode_string(&cli.input)
70    };
71
72    if let Some(output_path) = &cli.output {
73        write(output_path, result)?;
74        return Ok(None);
75    }
76    Ok(Some(result))
77}