temp_conv/
lib.rs

1#![warn(clippy::missing_const_for_fn)]
2#![warn(clippy::missing_inline_in_public_items)]
3
4//! # temp-conv
5//!
6//! temp-conv is a framework for converting between different temperature units, but it has also it's own cli-tool which uses said framework.
7
8use anyhow::Result;
9use clap::Parser;
10
11pub mod cli;
12pub mod error;
13pub mod formatted_output;
14pub mod temperature;
15
16/// Runs the main logic of this tool
17///
18/// # Panics
19///
20/// Panics if the output can not be parsed to the specified format.
21///
22/// # Errors
23///
24/// This function will return an error if the conversion is resulting in an I/O error occurs.
25#[allow(clippy::missing_inline_in_public_items)]
26pub fn run() -> Result<()> {
27    let cli = cli::Cli::parse();
28
29    #[cfg(any(feature = "json", feature = "yaml", feature = "toml"))]
30    let temperature_in = cli.temperature_in();
31    #[cfg(any(feature = "json", feature = "yaml", feature = "toml"))]
32    let temperature_out = cli.temperature_out();
33    #[cfg(any(feature = "json", feature = "yaml", feature = "toml"))]
34    let original_value = cli.value();
35
36    let format = cli.format();
37
38    let result = cli.convert()?;
39
40    #[cfg(any(feature = "json", feature = "yaml", feature = "toml"))]
41    let output =
42        formatted_output::Output::new(temperature_in, original_value, temperature_out, result);
43
44    let output_string = if cli.only_value() {
45        format!("{result}")
46    } else if let Some(format) = format {
47        match format {
48            #[cfg(feature = "json")]
49            formatted_output::Format::Json => output.to_json().unwrap(),
50            #[cfg(feature = "yaml")]
51            formatted_output::Format::Yaml => output.to_yaml().unwrap(),
52            #[cfg(feature = "toml")]
53            formatted_output::Format::Toml => output.to_toml().unwrap(),
54        }
55    } else {
56        format!("Result: {result}")
57    };
58
59    if let Some(path) = cli.output() {
60        std::fs::write(path.as_path(), output_string)?;
61
62        if cli.verbose() {
63            println!("Sucessfully saved at {}", path.display());
64        }
65    } else {
66        println!("{}", output_string);
67    };
68
69    Ok(())
70}