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. <lsantos@medicalmasses.com>
5 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program 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
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19 */
20
21///
22/// Tools for handling reading and writing from the standard I/O/E.
23///
24/// Per this [stackoverflow discussion](https://unix.stackexchange.com/questions/37508/in-what-order-do-piped-commands-run).
25/// Note:
26///```text
27///  Piped commands run concurrently. When you run ps | grep …, it's the luck of the draw (or a matter of details of the workings of the shell combined with scheduler fine-tuning deep in the bowels of the kernel) as to whether ps or grep starts first, and in any case they continue to execute concurrently.
28///
29///  This is very commonly used to allow the second program to process data as it comes out from the first program, before the first program has completed its operation. For example
30///
31///  grep pattern very-large-file | tr a-z A-Z
32///  begins to display the matching lines in uppercase even before grep has finished traversing the large file.
33///
34///  grep pattern very-large-file | head -n 1
35///  displays the first matching line, and may stop processing well before grep has finished reading its input file.
36///
37///  If you read somewhere that piped programs run in sequence, flee this document. Piped programs run concurrently and always have.
38/// ```
39///
40/// I bring the note above because that was my original understanding, but I have had to spend a
41/// crazy amount of time trying to get data flowing from one process to another without the initial
42/// process first exiting.
43///
44pub mod cli_utils {
45    use crate::base::{RUMResult, RUMVec};
46    use crate::cpu::CPU_PAGE_SIZE;
47    use crate::strings::{rumtk_format, RUMString};
48    use crate::types::RUMCLIParser;
49    use rumtk_arena::AsRUMSlice;
50    use std::io::{stdin, stdout, BufReader, BufWriter, Read, Write};
51    #[cfg(any(target_family = "unix", target_os = "linux", target_os = "macos"))]
52    use std::os::fd::{AsRawFd, FromRawFd};
53
54    pub type BufferSlice = RUMVec<u8>;
55    pub type CliSTDInput = RUMVec<u8>;
56    pub type CliSTDOutput<R: AsRUMSlice> = R;
57    pub type BufferChunk = [u8; STD_IN_STEP_SIZE];
58    pub type CliDirectExecutor<Args: RUMCLIParser> = Box<dyn Fn(Args) -> RUMResult<()>>;
59    pub type CliMessageExecutor<Args: RUMCLIParser, R: AsRUMSlice> = Box<dyn Fn(CliSTDInput, &Args) -> RUMResult<CliSTDOutput<R>>>;
60
61    const STD_IN_STEP_SIZE: usize = u16::MAX as usize * 4;
62
63    pub enum CliProcessor<Args>
64    where
65        Args: RUMCLIParser
66    {
67        Direct(CliDirectExecutor<Args>),
68        Message(CliMessageExecutor<Args, RUMString>),
69
70    }
71
72    ///
73    /// Consumes the incoming buffer in chunks of [CPU_PAGE_SIZE](CPU_PAGE_SIZE) bytes size
74    /// until no more bytes are present.
75    ///
76    /// To avoid calling a blocking read, we check if the read yielded an amount of bytes fewer than
77    /// the requested chunk size.
78    ///
79    /// ## Example
80    ///
81    /// ```
82    /// use rumtk_core::cli::cli_utils::{read_stdin};
83    /// use rumtk_core::cpu::CPU_PAGE_SIZE;
84    ///
85    /// let stdin_data = read_stdin(CPU_PAGE_SIZE).unwrap();
86    ///
87    /// assert_eq!(stdin_data.len(), 0, "Returned data with {} size even though we expected 0 bytes!", stdin_data.len())
88    /// ```
89    ///
90    pub fn read_stdin(minimum_size: usize) -> RUMResult<CliSTDInput> {
91        let mut stdin_buffer = CliSTDInput::with_capacity(minimum_size);
92
93        loop {
94            let s = read_some_stdin(&mut stdin_buffer)?;
95
96            // If we attempt the next read, it is likely to be a 0 byte read. Why does this matter?
97            // Well, if the other end of the pipe is still open, the read call will stall in Rust's
98            // std and it is because it expects EOF but that never comes.
99            // If you look at https://man7.org/linux/man-pages/man2/read.2.html, read should return
100            // 0 and simply let us naturally break, but a read < than requested buffer appears to be
101            // an equally valid way to handle terminal and piped data.
102            // We have to check against 0 because the more optimal the buffer size we ask for (e.g.
103            // larger reads for minimum syscall time) the less likely the kernel is ready with the
104            // requested data.
105
106            // Example reads at u16::Max
107            // Read 65535 bytes
108            // Read 61441 bytes
109            // Read 65535 bytes
110            // Read 61441 bytes
111            // Read 8192 bytes
112            // Read 65535 bytes
113            // Read 61441 bytes
114            // Read 65535 bytes
115            // Read 61441 bytes
116            // Read 8192 bytes
117            // Read 65535 bytes
118            // Read 61441 bytes
119            // Read 65535 bytes
120            // Read 61441 bytes
121            // Read 8192 bytes
122            // Read 65535 bytes
123            // Read 61441 bytes
124            // Read 65535 bytes
125            // Read 61441 bytes
126            // Read 8192 bytes
127            // Read 65535 bytes
128            // Read 61441 bytes
129            // Read 65535 bytes
130            // Read 61441 bytes
131            // Read 8192 bytes
132            // Read 65535 bytes
133            // Read 61441 bytes
134            // Read 65535 bytes
135            // Read 61441 bytes
136            // Read 8192 bytes
137            // Read 65535 bytes
138            // Read 61441 bytes
139            // Read 65535 bytes
140            // Read 61441 bytes
141            // Read 8192 bytes
142            // Read 65535 bytes
143            // Read 61441 bytes
144            // Read 65535 bytes
145            // Read 61441 bytes
146            // Read 8192 bytes
147            // Read 65535 bytes
148            // Read 61441 bytes
149            // Read 65535 bytes
150            // Read 41974 bytes
151            // Read 0 bytes
152            // Total: 2331637 => 2.2MB
153            if s == 0 {
154                break;
155            }
156        }
157
158        Ok(stdin_buffer)
159    }
160
161    ///
162    /// Consumes the incoming buffer in chunks of [CPU_SIMD_64_SIZE](crate::cpu::CPU_SIMD_64_SIZE) bytes size.
163    ///
164    /// ## Example
165    ///
166    /// ```
167    /// use std::io::stdin;
168    /// use std::io::prelude::*;
169    /// use std::process::{Command, Stdio};
170    /// use rumtk_core::cli::cli_utils::{read_some_stdin};
171    /// use rumtk_core::cpu::CPU_PAGE_SIZE;
172    /// use rumtk_core::base::RUMVec;
173    ///
174    /// let mut stdin_buffer = RUMVec::with_capacity(CPU_PAGE_SIZE);
175    /// let mut s = read_some_stdin(&mut stdin_buffer).unwrap();
176    /// let mut totas_s = s;
177    /// while s > 0 {
178    ///    s = read_some_stdin(&mut stdin_buffer).unwrap();
179    ///    totas_s += s;
180    /// }
181    ///
182    /// assert_eq!(totas_s, 0, "Returned data with {} size even though we expected 0 bytes!", totas_s)
183    /// ```
184    ///
185    #[inline]
186    #[cfg(target_os = "windows")]
187    pub fn read_some_stdin(buf: &mut BufferSlice) -> RUMResult<usize> {
188        let mut chunk: BufferChunk = [0; STD_IN_STEP_SIZE];
189
190        match stdin().lock().read(&mut chunk[..]) {
191            Ok(s) => {
192                buf.extend_from_slice(&chunk[..s]);
193                Ok(s)
194            }
195            Err(e) => Err(rumtk_format!("Error reading stdin chunk because {}!", e)),
196        }
197    }
198
199    ///
200    /// Consumes the incoming buffer in chunks of [CPU_SIMD_64_SIZE](crate::cpu::CPU_SIMD_64_SIZE) bytes size.
201    ///
202    /// ## Example
203    ///
204    /// ```
205    /// use std::io::stdin;
206    /// use std::io::prelude::*;
207    /// use std::process::{Command, Stdio};
208    /// use rumtk_core::cli::cli_utils::{read_some_stdin};
209    /// use rumtk_core::cpu::CPU_PAGE_SIZE;
210    /// use rumtk_core::base::RUMVec;
211    ///
212    /// let mut stdin_buffer = RUMVec::with_capacity(CPU_PAGE_SIZE);
213    /// let mut s = read_some_stdin(&mut stdin_buffer).unwrap();
214    /// let mut totas_s = s;
215    /// while s > 0 {
216    ///    s = read_some_stdin(&mut stdin_buffer).unwrap();
217    ///    totas_s += s;
218    /// }
219    ///
220    /// assert_eq!(totas_s, 0, "Returned data with {} size even though we expected 0 bytes!", totas_s)
221    /// ```
222    ///
223    #[cfg(any(target_family = "unix", target_os = "linux", target_os = "macos"))]
224    pub fn read_some_stdin(buf: &mut BufferSlice) -> RUMResult<usize> {
225        // Create an unbuffered File handle from file descriptor 1 (stdout)
226        let locked = stdin().lock();
227        let stdin_fd = locked.as_raw_fd();
228        let mut chunk: BufferChunk = [0; STD_IN_STEP_SIZE];
229
230        let mut file = BufReader::new(unsafe { std::fs::File::from_raw_fd(stdin_fd) });
231
232        //Read directly from std input
233        let count = match file.read(&mut chunk[..]) {
234            Ok(s) => {
235                buf.extend_from_slice(&chunk[..s]);
236                std::mem::forget(file);
237                s
238            },
239            Err(e) => return Err(rumtk_format!("Error writing to stdout because {}", e)),
240        };
241
242        Ok(count)
243    }
244
245    ///
246    /// Writes [RUMBuffer] to `stdout`.
247    ///
248    #[cfg(target_os = "windows")]
249    pub fn write_stdout<R: AsSlice>(data: CliSTDOutput<R>) -> RUMResult<()> {
250        match stdout().lock().write_all(data.as_rum_slice()) {
251            Ok(_) => {}
252            Err(e) => return Err(rumtk_format!("Error writing to stdout because => {}", e)),
253        };
254        flush_stdout()?;
255        Ok(())
256    }
257
258    #[cfg(any(target_family = "unix", target_os = "linux", target_os = "macos"))]
259    pub fn write_stdout<R: AsRUMSlice>(data: CliSTDOutput<R>) -> RUMResult<()> {
260        // Create an unbuffered File handle from file descriptor 1 (stdout)
261        let locked = stdout().lock();
262        let stdout_fd = locked.as_raw_fd();
263        println!("stdin_fd: {}", stdout_fd);
264
265        let mut file = BufWriter::new(unsafe { std::fs::File::from_raw_fd(stdout_fd) });
266
267        // Write bytes directly
268        match file.write_all(data.as_rum_slice()) {
269            Ok(_) => {
270                file.flush().unwrap_or_default();
271                std::mem::forget(file);
272            },
273            Err(e) => return Err(rumtk_format!("Error writing to stdout because {}", e)),
274        };
275
276        flush_stdout()?;
277        Ok(())
278    }
279
280    fn flush_stdout() -> RUMResult<()> {
281        match stdout().flush() {
282            Ok(_) => Ok(()),
283            Err(e) => Err(rumtk_format!("Error flushing stdout because => {}", e)),
284        }
285    }
286
287    pub fn process_message<Args, PF, R>(args: &Args, processor: PF) -> RUMResult<()>
288    where
289        Args: RUMCLIParser,
290        R: AsRUMSlice,
291        PF: Fn(CliSTDInput, &Args) -> RUMResult<R>
292    {
293        let stdin_msg = read_stdin(CPU_PAGE_SIZE * CPU_PAGE_SIZE)?;
294        if !stdin_msg.is_empty() {
295            let out_data = processor(stdin_msg, args)?;
296
297            write_stdout(out_data)?;
298        }
299        Ok(())
300    }
301
302    ///
303    /// Runs a closure (or any `Fn`) that owns the whole lifecycle of the program. Unlike
304    /// [CliProcessor::Direct], the closure is not boxed, so it can borrow from its environment.
305    ///
306    pub fn run_direct<Args, F>(args: &Args, logic: F) -> RUMResult<()>
307    where
308        Args: RUMCLIParser,
309        F: Fn(&Args) -> RUMResult<()>
310    {
311        logic(args)
312    }
313
314    pub fn process_message_loop<Args, PF, R>(args: Args, processor: &PF)
315    where
316        Args: RUMCLIParser,
317        R: AsRUMSlice,
318        PF: Fn(CliSTDInput, &Args) -> RUMResult<R>
319    {
320        loop {
321            match process_message(&args, processor) {
322                Ok(()) => continue,
323                Err(e) => println!("{}", e), // TODO: missing log call
324            };
325        }
326    }
327
328    pub fn print_license_notice(program: &str, year: &str, author_list: &Vec<&str>) {
329        let authors = author_list.join(", ");
330        let notice = rumtk_format!(
331            r"  {program}  Copyright (C) {year}  {authors}
332                This program comes with ABSOLUTELY NO WARRANTY.
333                This is free software, and you are welcome to redistribute it
334                under certain conditions."
335        );
336        eprintln!("{}", notice);
337    }
338}
339
340pub mod macros {
341    ///
342    ///
343    ///
344    #[macro_export]
345    macro_rules! rumtk_cli_define_args {
346        (
347            $(
348                $(#[$field_meta:meta])*
349                $field_name:ident : $field_typ:ty
350            ),* $(,)?
351        ) => {
352            #[derive($crate::types::RUMCLIParser, Debug)]
353            #[command(author, version, about, long_about = None)]
354            pub struct RUMTKInterfaceArgs {
355                $(
356                    $(#[$field_meta])*
357                    pub $field_name: $field_typ,
358                )*
359                ///
360                /// Specifies command line script to execute on message.
361                ///
362                #[arg(short, long, default_value_t = 1)]
363                pub threads: usize,
364                ///
365                /// Don't write to stdout. Mostly used to distinguish between performance issues with parser
366                /// vs. serde's JSON serialization.
367                ///
368                #[arg(short, long)]
369                pub quiet: bool,
370                ///
371                /// Only used if in client/outbound mode. Places the interface into a loop constantly looking
372                /// for messages in stdin to ship to the connected listening interface.
373                ///
374                #[arg(short, long)]
375                pub daemon: bool,
376            }
377        };
378    }
379
380    ///
381    /// Reads STDIN and unescapes the incoming message.
382    /// Return this unescaped message.
383    ///
384    /// # Example
385    ///
386    /// ## Without specifying the minimum read size.
387    /// ```
388    /// use rumtk_core::base::{RUMResult, RUMVec};
389    /// use rumtk_core::buffers::*;
390    /// use rumtk_core::rumtk_read_stdin;
391    ///
392    /// fn test_read_stdin() -> RUMResult<RUMVec<u8>> {
393    ///     rumtk_read_stdin!()
394    /// }
395    ///
396    /// match test_read_stdin() {
397    ///     Ok(s) => (),
398    ///     Err(e) => panic!("Error reading stdin because => {}", e)
399    /// }
400    /// ```
401    ///
402    /// ## With specifying the minimum read size.
403    /// ```
404    /// use rumtk_core::base::{RUMResult, RUMVec};
405    /// use rumtk_core::buffers::*;
406    /// use rumtk_core::rumtk_read_stdin;
407    ///
408    /// fn test_read_stdin() -> RUMResult<RUMVec<u8>> {
409    ///     rumtk_read_stdin!(1024)
410    /// }
411    ///
412    /// match test_read_stdin() {
413    ///     Ok(s) => (),
414    ///     Err(e) => panic!("Error reading stdin because => {}", e)
415    /// }
416    /// ```
417    ///
418    #[macro_export]
419    macro_rules! rumtk_read_stdin {
420        (  ) => {{
421            use $crate::cpu::CPU_PAGE_SIZE;
422            use $crate::cli::cli_utils::{read_stdin};
423            read_stdin(CPU_PAGE_SIZE * CPU_PAGE_SIZE)
424        }};
425        ( $min_expected_size:expr ) => {{
426            use $crate::cli::cli_utils::{read_stdin};
427            read_stdin($min_expected_size)
428        }};
429    }
430
431    ///
432    /// Writes [RUMString](crate::strings::RUMString) or [RUMBuffer](crate::types::RUMBuffer) to `stdout`.
433    ///
434    /// If the `binary` parameter is passed, we push the `message` parameter directly to `stdout`. the
435    /// `message` parameter has to be of type [RUMBuffer](crate::types::RUMBuffer).
436    ///
437    /// ## Example
438    ///
439    /// ### Default / Pushing a String
440    /// ```
441    /// use rumtk_core::rumtk_write_stdout;
442    ///
443    /// rumtk_write_stdout!("I ❤ my wife!");
444    /// ```
445    ///
446    /// ## Pushing Binary Buffer
447    /// ```
448    /// use rumtk_core::rumtk_write_stdout;
449    /// use rumtk_core::buffers::{new_random_rumbuffer, DEFAULT_BUFFER_CHUNK_SIZE};
450    ///
451    /// let buffer = new_random_rumbuffer::<DEFAULT_BUFFER_CHUNK_SIZE>();
452    /// rumtk_write_stdout!(buffer);
453    /// ```
454    ///
455    #[macro_export]
456    macro_rules! rumtk_write_stdout {
457        ( $message:expr ) => {{
458            use $crate::cli::cli_utils::write_stdout;
459            write_stdout(&$message)
460        }};
461    }
462
463    ///
464    /// Prints the mandatory GPL License Notice to terminal!
465    ///
466    /// # Example
467    /// ## Default
468    /// ```
469    /// use rumtk_core::rumtk_print_license_notice;
470    ///
471    /// rumtk_print_license_notice!();
472    /// ```
473    /// ## Program Only
474    /// ```
475    /// use rumtk_core::rumtk_print_license_notice;
476    ///
477    /// rumtk_print_license_notice!("RUMTK");
478    /// ```
479    /// ## Program + Year
480    /// ```
481    /// use rumtk_core::rumtk_print_license_notice;
482    ///
483    /// rumtk_print_license_notice!("RUMTK", "2025");
484    /// ```
485    /// ## Program + Year + Authors
486    /// ```
487    /// use rumtk_core::rumtk_print_license_notice;
488    ///
489    /// rumtk_print_license_notice!("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
490    /// ```
491    ///
492    #[macro_export]
493    macro_rules! rumtk_print_license_notice {
494        ( ) => {{
495            use $crate::cli::cli_utils::print_license_notice;
496
497            print_license_notice("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
498        }};
499        ( $program:expr ) => {{
500            use $crate::cli::cli_utils::print_license_notice;
501            print_license_notice(&$program, "2025", &vec!["2025", "Luis M. Santos, M.D."]);
502        }};
503        ( $program:expr, $year:expr ) => {{
504            use $crate::cli::cli_utils::print_license_notice;
505            print_license_notice(&$program, &$year, &vec!["Luis M. Santos, M.D."]);
506        }};
507        ( $program:expr, $year:expr, $authors:expr ) => {{
508            use $crate::cli::cli_utils::print_license_notice;
509            print_license_notice(&$program, &$year, &$authors);
510        }};
511    }
512
513    ///
514    /// Defines the CLI arguments of the program, parses the command line, and wires the message
515    /// processing logic.
516    ///
517    /// The macro expects an optional list of CLI argument definitions (same syntax accepted by
518    /// [rumtk_cli_define_args](crate::rumtk_cli_define_args)) followed by either the two message
519    /// handlers:
520    ///
521    /// + `ok`  => Called when the incoming message could be deserialized into the expected type.
522    /// + `err` => Called with the raw bytes when deserialization was not possible.
523    ///
524    /// or a single piece of logic receiving the parsed arguments. In the latter case, the logic
525    /// owns the whole interface lifecycle and is called once with a reference to the parsed
526    /// arguments.
527    ///
528    /// The generated argument struct is named `RUMTKInterfaceArgs` and is available to the
529    /// handlers. If the `--daemon` flag is passed, the `ok`/`err` handlers are called in a loop for
530    /// every message coming through `stdin`. Otherwise, a single message is processed.
531    ///
532    /// ## Example
533    ///
534    /// ### Example 1 - With Parsed and Unparsed Message Closures
535    /// 
536    /// ```no_run
537    /// use rumtk_core::base::{RUMResult, RUMVec};
538    /// use rumtk_core::strings::RUMString;
539    /// use rumtk_core::types::RUMCLIParser;
540    /// use rumtk_core::rumtk_cli_process;
541    ///
542    /// fn main() {
543    ///     rumtk_cli_process!(
544    ///         ///
545    ///         /// Pretty print the outgoing message.
546    ///         ///
547    ///         #[arg(short, long)]
548    ///         pretty: bool,
549    ///         ///
550    ///         /// Run in debug mode?
551    ///         ///
552    ///         #[arg(short, long)]
553    ///         debug: bool,
554    ///         Message(|data: RUMVec<u8>, args: &RUMTKInterfaceArgs| -> RUMResult<RUMString> {
555    ///             Ok(RUMString::default())
556    ///         })
557    ///     );
558    /// }
559    /// ```
560    ///
561    /// ### Example 2 - With Raw Logic
562    ///
563    /// ```no_run
564    /// use rumtk_core::base::{RUMResult, RUMVec};
565    /// use rumtk_core::strings::RUMString;
566    /// use rumtk_core::types::RUMCLIParser;
567    /// use rumtk_core::rumtk_cli_process;
568    ///
569    /// fn main() {
570    ///     rumtk_cli_process!(
571    ///         ///
572    ///         /// Pretty print the outgoing message.
573    ///         ///
574    ///         #[arg(short, long)]
575    ///         pretty: bool,
576    ///         ///
577    ///         /// Run in debug mode?
578    ///         ///
579    ///         #[arg(short, long)]
580    ///         debug: bool,
581    ///         Direct(|args: &RUMTKInterfaceArgs| -> RUMResult<()> {
582    ///             Ok(())
583    ///         })
584    ///     );
585    /// }
586    /// ```
587    ///
588    /// ## Notes
589    ///
590    /// I let `Claude Opus 5` help complete this macro. I did not understand how to wire the
591    /// token tree muncher into the argument pattern to pass to [rumtk_cli_define_args](crate::rumtk_cli_define_args)
592    /// and the two additional arguments representing the closures to be executed if message parsing is successful or not.
593    ///
594    #[macro_export]
595    macro_rules! rumtk_cli_process {
596        (
597            @collect [$($cli_args:tt)*]
598            $(#[$field_meta:meta])+
599            $field_name:ident : $field_typ:ty,
600            $($rest:tt)*
601        ) => {
602            $crate::rumtk_cli_process!(
603                @collect [$($cli_args)* $(#[$field_meta])* $field_name : $field_typ,]
604                $($rest)*
605            )
606        };
607        (
608            @collect [$($cli_args:tt)*]
609            $field_name:ident : $field_typ:ty,
610            $($rest:tt)*
611        ) => {
612            $crate::rumtk_cli_process!(
613                @collect [$($cli_args)* $field_name : $field_typ,]
614                $($rest)*
615            )
616        };
617        (
618            @collect [$($cli_args:tt)*]
619            Direct($logic:expr) $(,)?
620        ) => {{
621            use $crate::cli::cli_utils::run_direct;
622            use $crate::types::RUMCLIParser;
623
624            $crate::rumtk_cli_define_args!($($cli_args)*);
625
626            let args = RUMTKInterfaceArgs::parse();
627
628            match run_direct(&args, $logic) {
629                Ok(_) => {},
630                Err(e) => println!("Error: {}", e),
631            };
632        }};
633        (
634            @collect [$($cli_args:tt)*]
635            Message($logic:expr) $(,)?
636        ) => {{
637            use $crate::cli::cli_utils::{process_message_loop, process_message};
638            use $crate::types::RUMCLIParser;
639
640            $crate::rumtk_cli_define_args!($($cli_args)*);
641
642            let args = RUMTKInterfaceArgs::parse();
643            let processor = $logic;
644
645            let r = if args.daemon {
646                process_message_loop(args, &processor);
647                Ok(())
648            } else {
649                process_message(&args, &processor)
650            };
651
652            match r {
653                Ok(_) => {},
654                Err(e) => println!("Error: {}", e),
655            };
656        }};
657        (
658            $($tokens:tt)*
659        ) => {
660            $crate::rumtk_cli_process!(@collect [] $($tokens)*)
661        };
662    }
663}