Skip to main content

alopex_cli/commands/
version.rs

1use std::io::{self, Write};
2
3use serde::Serialize;
4
5use crate::cli::OutputFormat;
6use crate::error::{CliError, Result};
7use crate::version::{cli_version, supported_format_max, supported_format_min};
8
9#[derive(Debug, Serialize)]
10pub struct VersionInfo {
11    pub cli_version: String,
12    pub supported_format_min: String,
13    pub supported_format_max: String,
14    pub build_date: Option<String>,
15    pub git_commit: Option<String>,
16}
17
18impl VersionInfo {
19    fn new() -> Self {
20        let build_date = option_env!("ALOPEX_BUILD_DATE").map(|value| value.to_string());
21        let git_commit = option_env!("ALOPEX_GIT_COMMIT").map(|value| value.to_string());
22
23        Self {
24            cli_version: cli_version().to_string(),
25            supported_format_min: supported_format_min().to_string(),
26            supported_format_max: supported_format_max().to_string(),
27            build_date,
28            git_commit,
29        }
30    }
31}
32
33pub fn execute_version(output: OutputFormat) -> Result<()> {
34    let info = VersionInfo::new();
35    match output {
36        OutputFormat::Table => write_table(&info),
37        OutputFormat::Json => write_json(&info),
38        other => Err(CliError::InvalidArgument(format!(
39            "Unsupported output format for version: {:?}",
40            other
41        ))),
42    }
43}
44
45fn write_table(info: &VersionInfo) -> Result<()> {
46    let mut stdout = io::stdout();
47    writeln!(stdout, "alopex-cli {}", info.cli_version)?;
48    writeln!(
49        stdout,
50        "Supported file format: {} - {}",
51        info.supported_format_min, info.supported_format_max
52    )?;
53    if let Some(build_date) = &info.build_date {
54        writeln!(stdout, "Build date: {}", build_date)?;
55    }
56    if let Some(git_commit) = &info.git_commit {
57        writeln!(stdout, "Git commit: {}", git_commit)?;
58    }
59    Ok(())
60}
61
62fn write_json(info: &VersionInfo) -> Result<()> {
63    let mut stdout = io::stdout();
64    serde_json::to_writer_pretty(&mut stdout, info)?;
65    writeln!(stdout)?;
66    Ok(())
67}