|
| 1 | +use chrono; |
| 2 | +use std::fmt::{Display, Formatter}; |
| 3 | +use std::io::{self, BufWriter, Write}; |
| 4 | + |
| 5 | +use anyhow::Result; |
| 6 | +use serde::Serialize; |
| 7 | + |
| 8 | +use crate::args::HelpFormat; |
| 9 | +use crate::build; |
| 10 | + |
| 11 | +#[derive(Serialize)] |
| 12 | +struct VersionMetadata { |
| 13 | + ruff_version: &'static str, |
| 14 | + rust_version: &'static str, |
| 15 | + build_time: &'static str, |
| 16 | + cargo_version: &'static str, |
| 17 | + build_os: &'static str, |
| 18 | + commit: &'static str, |
| 19 | + commit_time: &'static str, |
| 20 | + target: &'static str, |
| 21 | + dirty: bool, |
| 22 | + release: bool, |
| 23 | +} |
| 24 | + |
| 25 | +impl<'a> VersionMetadata { |
| 26 | + const fn from_build() -> Self { |
| 27 | + Self { |
| 28 | + ruff_version: build::PKG_VERSION, |
| 29 | + rust_version: build::RUST_VERSION, |
| 30 | + build_time: build::BUILD_TIME_3339, |
| 31 | + cargo_version: build::CARGO_VERSION, |
| 32 | + build_os: build::BUILD_OS, |
| 33 | + target: build::BUILD_TARGET, |
| 34 | + release: !build::TAG.is_empty(), |
| 35 | + commit: build::SHORT_COMMIT, |
| 36 | + commit_time: build::COMMIT_DATE_3339, |
| 37 | + dirty: !build::GIT_CLEAN, |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +impl Display for VersionMetadata { |
| 43 | + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { |
| 44 | + write!(f, "ruff {}", self.ruff_version) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +/// Display version information |
| 49 | +pub(crate) fn version(output_format: HelpFormat) -> Result<()> { |
| 50 | + let mut stdout = BufWriter::new(io::stdout().lock()); |
| 51 | + let metadata = VersionMetadata::from_build(); |
| 52 | + |
| 53 | + let build_date = chrono::DateTime::parse_from_rfc3339(metadata.build_time)?; |
| 54 | + |
| 55 | + match output_format { |
| 56 | + HelpFormat::Text => { |
| 57 | + let status = if metadata.dirty { |
| 58 | + "-dirty" |
| 59 | + } else { |
| 60 | + if !metadata.release { |
| 61 | + "-dev" |
| 62 | + } else { |
| 63 | + "" |
| 64 | + } |
| 65 | + }; |
| 66 | + |
| 67 | + writeln!( |
| 68 | + stdout, |
| 69 | + "ruff {}{} ({} {})", |
| 70 | + &metadata.ruff_version, |
| 71 | + &status, |
| 72 | + &metadata.commit, |
| 73 | + build_date.format("%Y-%m-%d") |
| 74 | + )?; |
| 75 | + writeln!(stdout, "{}", &metadata.rust_version)?; |
| 76 | + writeln!(stdout, "{}", &metadata.cargo_version)?; |
| 77 | + } |
| 78 | + HelpFormat::Json => { |
| 79 | + serde_json::to_writer_pretty(stdout, &metadata)?; |
| 80 | + } |
| 81 | + }; |
| 82 | + Ok(()) |
| 83 | +} |
0 commit comments