http_mini_lib/utils/
app.rs

1use crate::errors::missing_source_directory::MissingSourceDirectoryError;
2
3use std::convert::Infallible;
4use std::net::{AddrParseError, IpAddr};
5use std::num::ParseIntError;
6use std::path::PathBuf;
7use std::{env, fs};
8
9/// # Get source directory, port and IP address from command line arguments
10///
11/// Retrieve command line arguments which can be used as source directory,
12/// startup port and IP address.
13///
14/// Source directory is mandatory.
15///
16/// Defaults:
17/// * IP address: "::"
18/// * port      : 8080
19pub fn get_params() -> Result<(String, i32, PathBuf), MissingSourceDirectoryError> {
20    let mut address: Option<String> = None;
21    let mut port: Option<i32> = None;
22    let mut source_dir: Option<PathBuf> = None;
23
24    let mut first_argument = true;
25
26    for argument in env::args() {
27        if first_argument {
28            first_argument = false;
29            continue;
30        }
31        if argument.starts_with("-") {
32            continue;
33        }
34
35        if source_dir.is_none() {
36            let x_source_dir: Result<PathBuf, Infallible> = argument.parse();
37            if x_source_dir.is_ok() {
38                let x_source_dir_pathbuf: PathBuf = x_source_dir.unwrap();
39                let canonical = fs::canonicalize(x_source_dir_pathbuf);
40                if canonical.is_ok() {
41                    source_dir = Option::from(canonical.unwrap()); // grcov-excl-line
42                    continue; // grcov-excl-line
43                }
44            }
45        }
46        if port.is_none() {
47            let x_port: Result<i32, ParseIntError> = argument.parse();
48            if x_port.is_ok() {
49                port = Option::from(x_port.unwrap()); // grcov-excl-line
50                continue; // grcov-excl-line
51            }
52        }
53        if address.is_none() {
54            let x_addr: Result<IpAddr, AddrParseError> = argument.parse();
55            if x_addr.is_ok() {
56                address = Option::from(argument); // grcov-excl-line
57                continue; // grcov-excl-line
58            }
59        }
60    }
61
62    // source directory is mandatory when not testing
63    if source_dir.is_none() {
64        if env::var_os("TEST").is_some() || cfg!(test) {
65            source_dir = Option::from(PathBuf::from("./"));
66        } else {
67            return Err(MissingSourceDirectoryError); // grcov-excl-line
68        }
69    }
70
71    Ok((
72        address.unwrap_or("::".to_string()),
73        port.unwrap_or(8080),
74        source_dir.unwrap(),
75    ))
76}