flaggy/
main_impl.rs

1// Copyright 2015 Axel Rasmussen
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::command::{Command, CommandResult};
16use crate::error::*;
17use crate::parse_and_execute::{parse_and_execute, parse_and_execute_single_command};
18use std::env;
19use std::fmt::{Debug, Display};
20use std::process;
21
22/// The integer which is returned from main() if the program exits successfully.
23pub(crate) const EXIT_SUCCESS: i32 = 0;
24/// The integer which is returned from main() if the program exits with any
25/// error.
26pub(crate) const EXIT_FAILURE: i32 = 1;
27
28/// Returns the current program's parameters (accessed essentialy via
29/// `std::env::args`) collected into a Vec. The 0'th parameter (the executable)
30/// is omitted.
31pub(crate) fn get_program_parameters() -> Vec<String> {
32    env::args()
33        .skip(1) // Skip the first argument, which is our executable.
34        .collect()
35}
36
37/// This is a utility function, which handles the given result returned by a
38/// Command implementation. The *outer* Result being an Err means that something
39/// went wrong internally in the command-line argument parsing library. The
40/// *inner* Result, on the other hand, is the actual Result returned by the
41/// caller-provided Command implementation itself.
42///
43/// Overall, if an error is encountered, it is printed to standard output. In
44/// either case, the appropriate exit code (EXIT_SUCCESS or EXIT_FAILURE) is
45/// returned.
46pub(crate) fn handle_result<E: Display + Debug>(r: Result<Option<CommandResult<E>>>) -> i32 {
47    match r {
48        // No internal error.
49        Ok(r) => match r {
50            // The command was not executed, but the error was handled internally.
51            None => EXIT_FAILURE,
52            // The command was executed, and we got a result back from it.
53            Some(r) => match r {
54                // The command returned success.
55                Ok(_) => EXIT_SUCCESS,
56                // The command returned an error to us.
57                Err(e) => {
58                    eprintln!(
59                        "{}",
60                        match cfg!(debug_assertions) {
61                            false => e.to_string(),
62                            true => format!("{:?}", e),
63                        }
64                    );
65                    EXIT_FAILURE
66                }
67            },
68        },
69        // An internal error which should be surfaced to the user.
70        Err(e) => {
71            eprintln!(
72                "Error parsing command-line flags: {}",
73                match cfg!(debug_assertions) {
74                    false => e.to_string(),
75                    true => format!("{:?}", e),
76                },
77            );
78            EXIT_FAILURE
79        }
80    }
81}
82
83/// Parses command-line parameters and executes the specified command.
84///
85/// This function exits this process with an appropriate exit code. Like
86/// `std::process::exit`, because this function never returns and it terminates
87/// the process, no destructors on the current stack or any other thread's
88/// stack will be run. The caller should ensure that this function is called
89/// from the only thread, and that any destructors which need to be run are in
90/// the stack of the command callback.
91pub fn main_impl<E: Display + Debug>(commands: Vec<Command<E>>) -> ! {
92    process::exit(handle_result(parse_and_execute(
93        env::args().next().unwrap().as_ref(),
94        &get_program_parameters(),
95        commands,
96        Some(::std::io::stderr()),
97    )));
98}
99
100/// Parses command-line parameters and executes the given command.
101///
102/// This function exits this process with an appropriate exit code. Like
103/// `std::process::exit`, because this function never returns and it terminates
104/// the process, no destructors on the current stack or any other thread's
105/// stack will be run. The caller should ensure that this function is called
106/// from the only thread, and that any destructors which need to be run are in
107/// the stack of the command callback.
108pub fn main_impl_single_command<E: Display + Debug>(command: Command<E>) -> ! {
109    process::exit(handle_result(parse_and_execute_single_command(
110        env::args().next().unwrap().as_ref(),
111        &get_program_parameters(),
112        command,
113        Some(::std::io::stderr()),
114    )));
115}