1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use anyhow::{Result};
use clap::Parser;

pub mod cli;
pub mod formatted_output;
pub mod temperature;

pub fn run() -> Result<()> {
    let cli = cli::Cli::parse();

    #[cfg(any(feature = "json", feature = "yaml", feature = "toml"))]
    let temperature_in = cli.temperature_in();
    #[cfg(any(feature = "json", feature = "yaml", feature = "toml"))]
    let temperature_out = cli.temperature_out();
    #[cfg(any(feature = "json", feature = "yaml", feature = "toml"))]
    let original_value = cli.value();

    let format = cli.format();

    let result = cli.convert()?;

    #[cfg(any(feature = "json", feature = "yaml", feature = "toml"))]
    let output =
        formatted_output::Output::new(temperature_in, original_value, temperature_out, result);

    let output_string = if cli.only_value() {
        format!("{result}")
    } else if let Some(format) = format {
        match format {
            #[cfg(feature = "json")]
            formatted_output::Format::Json => output.to_json().unwrap(),
            #[cfg(feature = "yaml")]
            formatted_output::Format::Yaml => output.to_yaml().unwrap(),
            #[cfg(feature = "toml")]
            formatted_output::Format::Toml => output.to_toml().unwrap(),
        }
    } else {
        format!("Result: {result}")
    };

    if let Some(path) = cli.output() {
        std::fs::write(path.as_path(), output_string)?;

        if cli.verbose() {
            println!("Sucessfully saved at {}", path.display());
        }
    } else {
        println!("{}", output_string);
    };

    Ok(())
}