Skip to main content

rumtk_core/
cli.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2025  Luis M. Santos, M.D.
5 * Copyright (C) 2025  MedicalMasses L.L.C.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20 */
21
22pub mod cli_utils {
23    use crate::core::RUMResult;
24    use crate::strings::{rumtk_format, EscapeExceptions, RUMString};
25    use crate::types::{RUMBuffer, RUMCLIParser};
26    use compact_str::CompactStringExt;
27    use std::io::{stdin, stdout, Read, StdinLock, Write};
28    use std::num::NonZeroU16;
29
30    const BUFFER_SIZE: usize = 1024 * 4;
31    const BUFFER_CHUNK_SIZE: usize = 512;
32
33    pub static CLI_ESCAPE_EXCEPTIONS: EscapeExceptions =
34        &[("\\n", "\n"), ("\\r", "\r"), ("\\\\", "\\")];
35
36    pub type BufferSlice = Vec<u8>;
37    pub type BufferChunk = [u8; BUFFER_CHUNK_SIZE];
38
39    ///
40    /// Example CLI parser that can be used to paste in your binary and adjust as needed.
41    ///
42    /// Note, this is only an example.
43    ///
44    #[derive(RUMCLIParser, Debug)]
45    #[command(author, version, about, long_about = None)]
46    pub struct RUMTKArgs {
47        ///
48        /// For interface crate only. Specifies the ip address to connect to.
49        ///
50        /// In outbound mode, `--ip` and `--port` are required parameters.
51        ///
52        /// In inbound mode, you can omit either or both parameters.
53        ///
54        #[arg(short, long)]
55        ip: Option<RUMString>,
56        ///
57        /// For interface crate only. Specifies the port to connect to.
58        ///
59        /// In outbound mode, `--ip` and `--port` are required parameters.
60        ///
61        /// In inbound mode, you can omit either or both parameters.
62        ///
63        #[arg(short, long)]
64        port: Option<NonZeroU16>,
65        ///
66        /// For process crate only. Specifies command line script to execute on message.
67        ///
68        #[arg(short, long)]
69        x: Option<RUMString>,
70        ///
71        /// Number of processing threads to allocate for this program.
72        ///
73        #[arg(short, long, default_value_t = 1)]
74        threads: usize,
75        ///
76        /// For interface crate only. Specifies if the interface is in outbound mode.
77        ///
78        /// In outbound mode, `--ip` and `--port` are required parameters.
79        ///
80        /// In inbound mode, you can omit either or both parameters.
81        ///
82        #[arg(short, long)]
83        outbound: bool,
84        ///
85        /// Request program runs in debug mode and log more information.
86        ///
87        #[arg(short, long, default_value_t = false)]
88        debug: bool,
89        ///
90        /// Request program runs in dry run mode and simulate as many steps as possible but not commit
91        /// to a critical non-reversible step.
92        ///
93        /// For example, if it was meant to write contents to a file, stop before doing so.
94        ///
95        #[arg(short, long, default_value_t = false)]
96        dry_run: bool,
97    }
98
99    pub fn read_stdin() -> RUMResult<RUMBuffer> {
100        let mut stdin_lock = stdin().lock();
101        let mut stdin_buffer: Vec<u8> = Vec::with_capacity(BUFFER_SIZE);
102        let mut s = read_some_stdin(&mut stdin_lock, &mut stdin_buffer)?;
103        while s == BUFFER_CHUNK_SIZE {
104            s = read_some_stdin(&mut stdin_lock, &mut stdin_buffer)?;
105        }
106        let mut filtered = Vec::<u8>::with_capacity(stdin_buffer.len());
107        for c in stdin_buffer {
108            if c != 0 {
109                filtered.push(c);
110            }
111        }
112
113        Ok(RUMBuffer::from(filtered))
114    }
115
116    pub fn read_some_stdin(input: &mut StdinLock, buf: &mut BufferSlice) -> RUMResult<usize> {
117        let mut chunk: BufferChunk = [0; BUFFER_CHUNK_SIZE];
118        match input.read(&mut chunk) {
119            Ok(s) => {
120                buf.extend_from_slice(&chunk);
121                Ok(s)
122            }
123            Err(e) => Err(rumtk_format!("Error reading stdin chunk because {}!", e)),
124        }
125    }
126
127    //TODO: Turn into a RUMBuffer for future tools.
128    pub fn write_stdout(data: &RUMString) -> RUMResult<()> {
129        let mut stdout_handle = stdout();
130        match stdout_handle.write_all(data.as_bytes()) {
131            Ok(_) => match stdout_handle.flush() {
132                Ok(_) => Ok(()),
133                Err(e) => Err(rumtk_format!("Error flushing stdout: {}", e)),
134            },
135            Err(e) => Err(rumtk_format!("Error writing to stdout!")),
136        }
137    }
138
139    pub fn print_license_notice(program: &str, year: &str, author_list: &Vec<&str>) {
140        let authors = author_list.join_compact(", ");
141        let notice = rumtk_format!(
142            "  {program}  Copyright (C) {year}  {authors}
143        This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
144        This is free software, and you are welcome to redistribute it
145        under certain conditions; type `show c' for details."
146        );
147        println!("{}", notice);
148    }
149}
150
151pub mod macros {
152    ///
153    /// Reads STDIN and unescapes the incoming message.
154    /// Return this unescaped message.
155    ///
156    /// # Example
157    /// ```
158    /// use rumtk_core::core::RUMResult;
159    /// use rumtk_core::strings::RUMString;
160    /// use rumtk_core::rumtk_read_stdin;
161    ///
162    /// fn test_read_stdin() -> RUMResult<RUMString> {
163    ///     rumtk_read_stdin!()
164    /// }
165    ///
166    /// match test_read_stdin() {
167    ///     Ok(s) => (),
168    ///     Err(e) => panic!("Error reading stdin because => {}", e)
169    /// }
170    /// ```
171    ///
172    #[macro_export]
173    macro_rules! rumtk_read_stdin {
174        (  ) => {{
175            use $crate::cli::cli_utils::read_stdin;
176            read_stdin()
177        }};
178    }
179
180    ///
181    /// Escapes a message and writes it to stdout via the print! macro.
182    ///
183    /// # Example
184    /// ```
185    /// use rumtk_core::rumtk_write_stdout;
186    ///
187    /// rumtk_write_stdout!("I ❤ my wife!");
188    /// ```
189    ///
190    #[macro_export]
191    macro_rules! rumtk_write_stdout {
192        ( $message:expr ) => {{
193            use $crate::cli::cli_utils::{write_stdout, CLI_ESCAPE_EXCEPTIONS};
194            use $crate::strings::basic_escape;
195            let escaped_message = basic_escape($message, CLI_ESCAPE_EXCEPTIONS);
196            write_stdout(&escaped_message);
197        }};
198    }
199
200    ///
201    /// Prints the mandatory GPL License Notice to terminal!
202    ///
203    /// # Example
204    /// ## Default
205    /// ```
206    /// use rumtk_core::rumtk_print_license_notice;
207    ///
208    /// rumtk_print_license_notice!();
209    /// ```
210    /// ## Program Only
211    /// ```
212    /// use rumtk_core::rumtk_print_license_notice;
213    ///
214    /// rumtk_print_license_notice!("RUMTK");
215    /// ```
216    /// ## Program + Year
217    /// ```
218    /// use rumtk_core::rumtk_print_license_notice;
219    ///
220    /// rumtk_print_license_notice!("RUMTK", "2025");
221    /// ```
222    /// ## Program + Year + Authors
223    /// ```
224    /// use rumtk_core::rumtk_print_license_notice;
225    ///
226    /// rumtk_print_license_notice!("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
227    /// ```
228    ///
229    #[macro_export]
230    macro_rules! rumtk_print_license_notice {
231        ( ) => {{
232            use $crate::cli::cli_utils::print_license_notice;
233
234            print_license_notice("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
235        }};
236        ( $program:expr ) => {{
237            use $crate::cli::cli_utils::print_license_notice;
238            print_license_notice(&$program, "2025", &vec!["2025", "Luis M. Santos, M.D."]);
239        }};
240        ( $program:expr, $year:expr ) => {{
241            use $crate::cli::cli_utils::print_license_notice;
242            print_license_notice(&$program, &$year, &vec!["Luis M. Santos, M.D."]);
243        }};
244        ( $program:expr, $year:expr, $authors:expr ) => {{
245            use $crate::cli::cli_utils::print_license_notice;
246            print_license_notice(&$program, &$year, &$authors);
247        }};
248    }
249}