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, RUMArrayConversions, RUMString};
25 use crate::types::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<RUMString> {
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 Ok(filtered.to_rumstring())
113 }
114
115 pub fn read_some_stdin(input: &mut StdinLock, buf: &mut BufferSlice) -> RUMResult<usize> {
116 let mut chunk: BufferChunk = [0; BUFFER_CHUNK_SIZE];
117 match input.read(&mut chunk) {
118 Ok(s) => {
119 buf.extend_from_slice(&chunk);
120 Ok(s)
121 }
122 Err(e) => Err(rumtk_format!("Error reading stdin chunk because {}!", e)),
123 }
124 }
125
126 pub fn write_stdout(data: &RUMString) -> RUMResult<()> {
127 let mut stdout_handle = stdout();
128 match stdout_handle.write_all(data.as_bytes()) {
129 Ok(_) => match stdout_handle.flush() {
130 Ok(_) => Ok(()),
131 Err(e) => Err(rumtk_format!("Error flushing stdout: {}", e)),
132 },
133 Err(e) => Err(rumtk_format!("Error writing to stdout!")),
134 }
135 }
136
137 pub fn print_license_notice(program: &str, year: &str, author_list: &Vec<&str>) {
138 let authors = author_list.join_compact(", ");
139 let notice = rumtk_format!(
140 " {program} Copyright (C) {year} {authors}
141 This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
142 This is free software, and you are welcome to redistribute it
143 under certain conditions; type `show c' for details."
144 );
145 println!("{}", notice);
146 }
147}
148
149pub mod macros {
150 ///
151 /// Reads STDIN and unescapes the incoming message.
152 /// Return this unescaped message.
153 ///
154 /// # Example
155 /// ```
156 /// use rumtk_core::core::RUMResult;
157 /// use rumtk_core::strings::RUMString;
158 /// use rumtk_core::rumtk_read_stdin;
159 ///
160 /// fn test_read_stdin() -> RUMResult<RUMString> {
161 /// rumtk_read_stdin!()
162 /// }
163 ///
164 /// match test_read_stdin() {
165 /// Ok(s) => (),
166 /// Err(e) => panic!("Error reading stdin because => {}", e)
167 /// }
168 /// ```
169 ///
170 #[macro_export]
171 macro_rules! rumtk_read_stdin {
172 ( ) => {{
173 use $crate::cli::cli_utils::read_stdin;
174 read_stdin()
175 }};
176 }
177
178 ///
179 /// Escapes a message and writes it to stdout via the print! macro.
180 ///
181 /// # Example
182 /// ```
183 /// use rumtk_core::rumtk_write_stdout;
184 ///
185 /// rumtk_write_stdout!("I ❤ my wife!");
186 /// ```
187 ///
188 #[macro_export]
189 macro_rules! rumtk_write_stdout {
190 ( $message:expr ) => {{
191 use $crate::cli::cli_utils::{write_stdout, CLI_ESCAPE_EXCEPTIONS};
192 use $crate::strings::basic_escape;
193 let escaped_message = basic_escape($message, CLI_ESCAPE_EXCEPTIONS);
194 write_stdout(&escaped_message);
195 }};
196 }
197
198 ///
199 /// Prints the mandatory GPL License Notice to terminal!
200 ///
201 /// # Example
202 /// ## Default
203 /// ```
204 /// use rumtk_core::rumtk_print_license_notice;
205 ///
206 /// rumtk_print_license_notice!();
207 /// ```
208 /// ## Program Only
209 /// ```
210 /// use rumtk_core::rumtk_print_license_notice;
211 ///
212 /// rumtk_print_license_notice!("RUMTK");
213 /// ```
214 /// ## Program + Year
215 /// ```
216 /// use rumtk_core::rumtk_print_license_notice;
217 ///
218 /// rumtk_print_license_notice!("RUMTK", "2025");
219 /// ```
220 /// ## Program + Year + Authors
221 /// ```
222 /// use rumtk_core::rumtk_print_license_notice;
223 ///
224 /// rumtk_print_license_notice!("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
225 /// ```
226 ///
227 #[macro_export]
228 macro_rules! rumtk_print_license_notice {
229 ( ) => {{
230 use $crate::cli::cli_utils::print_license_notice;
231
232 print_license_notice("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
233 }};
234 ( $program:expr ) => {{
235 use $crate::cli::cli_utils::print_license_notice;
236 print_license_notice(&$program, "2025", &vec!["2025", "Luis M. Santos, M.D."]);
237 }};
238 ( $program:expr, $year:expr ) => {{
239 use $crate::cli::cli_utils::print_license_notice;
240 print_license_notice(&$program, &$year, &vec!["Luis M. Santos, M.D."]);
241 }};
242 ( $program:expr, $year:expr, $authors:expr ) => {{
243 use $crate::cli::cli_utils::print_license_notice;
244 print_license_notice(&$program, &$year, &$authors);
245 }};
246 }
247}