|
| 1 | +use std::path::PathBuf; |
1 | 2 | use std::sync::Arc; |
2 | 3 |
|
| 4 | +use anyhow::Context; |
| 5 | +use clap::Parser; |
| 6 | + |
3 | 7 | use super::config::Configuration; |
4 | 8 | use super::console::Console; |
5 | | -use super::service::{CheckError, Service}; |
| 9 | +use super::service::{CheckResult, Service}; |
6 | 10 | use crate::checker::config::parse_from_json; |
7 | 11 |
|
8 | | -pub const NUMBER_OF_ARGUMENTS: usize = 2; |
| 12 | +#[derive(Parser, Debug)] |
| 13 | +#[clap(author, version, about, long_about = None)] |
| 14 | +struct Args { |
| 15 | + config_path: PathBuf, |
| 16 | +} |
9 | 17 |
|
10 | 18 | /// # Errors |
11 | 19 | /// |
12 | | -/// If some checks fails it will return a vector with all failing checks. |
13 | | -/// |
14 | | -/// # Panics |
15 | | -/// |
16 | | -/// Will panic if: |
17 | | -/// |
18 | | -/// - It can't read the json configuration file. |
19 | | -/// - The configuration file is invalid. |
20 | | -pub async fn run() -> Result<(), Vec<CheckError>> { |
21 | | - let args = parse_arguments(); |
22 | | - let config = setup_config(&args); |
| 20 | +/// Will return an error if it can't read or parse the configuration file. |
| 21 | +pub async fn run() -> anyhow::Result<Vec<CheckResult>> { |
| 22 | + let args = Args::parse(); |
| 23 | + |
| 24 | + let config = setup_config(&args)?; |
| 25 | + |
23 | 26 | let console_printer = Console {}; |
| 27 | + |
24 | 28 | let service = Service { |
25 | 29 | config: Arc::new(config), |
26 | 30 | console: console_printer, |
27 | 31 | }; |
28 | 32 |
|
29 | | - service.run_checks().await |
30 | | -} |
31 | | - |
32 | | -pub struct Arguments { |
33 | | - pub config_path: String, |
34 | | -} |
35 | | - |
36 | | -fn parse_arguments() -> Arguments { |
37 | | - let args: Vec<String> = std::env::args().collect(); |
38 | | - |
39 | | - if args.len() < NUMBER_OF_ARGUMENTS { |
40 | | - eprintln!("Usage: cargo run --bin tracker_checker <PATH_TO_CONFIG_FILE>"); |
41 | | - eprintln!("For example: cargo run --bin tracker_checker ./share/default/config/tracker_checker.json"); |
42 | | - std::process::exit(1); |
43 | | - } |
44 | | - |
45 | | - let config_path = &args[1]; |
46 | | - |
47 | | - Arguments { |
48 | | - config_path: config_path.to_string(), |
49 | | - } |
| 33 | + Ok(service.run_checks().await) |
50 | 34 | } |
51 | 35 |
|
52 | | -fn setup_config(args: &Arguments) -> Configuration { |
53 | | - let file_content = std::fs::read_to_string(args.config_path.clone()) |
54 | | - .unwrap_or_else(|_| panic!("Can't read config file {}", args.config_path)); |
| 36 | +fn setup_config(args: &Args) -> anyhow::Result<Configuration> { |
| 37 | + let file_content = |
| 38 | + std::fs::read_to_string(&args.config_path).with_context(|| format!("can't read config file {:?}", args.config_path))?; |
55 | 39 |
|
56 | | - parse_from_json(&file_content).expect("Invalid config format") |
| 40 | + parse_from_json(&file_content).context("invalid config format") |
57 | 41 | } |
0 commit comments