rustc_tools_util/
lib.rs

1// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10use std::env;
11
12#[macro_export]
13macro_rules! get_version_info {
14    () => {{
15        let major = env!("CARGO_PKG_VERSION_MAJOR").parse::<u8>().unwrap();
16        let minor = env!("CARGO_PKG_VERSION_MINOR").parse::<u8>().unwrap();
17        let patch = env!("CARGO_PKG_VERSION_PATCH").parse::<u16>().unwrap();
18        let crate_name = String::from(env!("CARGO_PKG_NAME"));
19
20        let host_compiler = $crate::get_channel();
21        let commit_hash = option_env!("GIT_HASH").map(|s| s.to_string());
22        let commit_date = option_env!("COMMIT_DATE").map(|s| s.to_string());
23
24        VersionInfo {
25            major,
26            minor,
27            patch,
28            host_compiler,
29            commit_hash,
30            commit_date,
31            crate_name,
32        }
33    }};
34}
35
36// some code taken and adapted from RLS and cargo
37pub struct VersionInfo {
38    pub major: u8,
39    pub minor: u8,
40    pub patch: u16,
41    pub host_compiler: Option<String>,
42    pub commit_hash: Option<String>,
43    pub commit_date: Option<String>,
44    pub crate_name: String,
45}
46
47impl std::fmt::Display for VersionInfo {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        let hash = self.commit_hash.clone().unwrap_or_default();
50        let hash_trimmed = hash.trim();
51
52        let date = self.commit_date.clone().unwrap_or_default();
53        let date_trimmed = date.trim();
54
55        if (hash_trimmed.len() + date_trimmed.len()) > 0 {
56            write!(
57                f,
58                "{} {}.{}.{} ({} {})",
59                self.crate_name, self.major, self.minor, self.patch, hash_trimmed, date_trimmed,
60            )?;
61        } else {
62            write!(f, "{} {}.{}.{}", self.crate_name, self.major, self.minor, self.patch)?;
63        }
64
65        Ok(())
66    }
67}
68
69impl std::fmt::Debug for VersionInfo {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        write!(
72            f,
73            "VersionInfo {{ crate_name: \"{}\", major: {}, minor: {}, patch: {}",
74            self.crate_name, self.major, self.minor, self.patch,
75        )?;
76        if self.commit_hash.is_some() {
77            write!(
78                f,
79                ", commit_hash: \"{}\", commit_date: \"{}\" }}",
80                self.commit_hash.clone().unwrap_or_default().trim(),
81                self.commit_date.clone().unwrap_or_default().trim()
82            )?;
83        } else {
84            write!(f, " }}")?;
85        }
86
87        Ok(())
88    }
89}
90
91pub fn get_channel() -> Option<String> {
92    if let Ok(channel) = env::var("CFG_RELEASE_CHANNEL") {
93        Some(channel)
94    } else {
95        // we could ask ${RUSTC} -Vv and do some parsing and find out
96        Some(String::from("nightly"))
97    }
98}
99
100pub fn get_commit_hash() -> Option<String> {
101    std::process::Command::new("git")
102        .args(&["rev-parse", "--short", "HEAD"])
103        .output()
104        .ok()
105        .and_then(|r| String::from_utf8(r.stdout).ok())
106}
107
108pub fn get_commit_date() -> Option<String> {
109    std::process::Command::new("git")
110        .args(&["log", "-1", "--date=short", "--pretty=format:%cd"])
111        .output()
112        .ok()
113        .and_then(|r| String::from_utf8(r.stdout).ok())
114}
115
116#[cfg(test)]
117mod test {
118    use super::*;
119
120    #[test]
121    fn test_struct_local() {
122        let vi = get_version_info!();
123        assert_eq!(vi.major, 0);
124        assert_eq!(vi.minor, 1);
125        assert_eq!(vi.patch, 1);
126        assert_eq!(vi.crate_name, "rustc_tools_util");
127        // hard to make positive tests for these since they will always change
128        assert!(vi.commit_hash.is_none());
129        assert!(vi.commit_date.is_none());
130    }
131
132    #[test]
133    fn test_display_local() {
134        let vi = get_version_info!();
135        assert_eq!(vi.to_string(), "rustc_tools_util 0.1.1");
136    }
137
138    #[test]
139    fn test_debug_local() {
140        let vi = get_version_info!();
141        let s = format!("{:?}", vi);
142        assert_eq!(
143            s,
144            "VersionInfo { crate_name: \"rustc_tools_util\", major: 0, minor: 1, patch: 1 }"
145        );
146    }
147
148}