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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#![warn(missing_docs)]
extern crate semver;
use semver::{Version, VersionReq, Identifier};
use std::process::Command;
use std::env;
use std::ffi::OsString;
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Channel {
Dev,
Nightly,
Beta,
Stable,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct VersionMeta {
pub semver: Version,
pub git_short_hash: String,
pub date: String,
pub channel: Channel
}
pub fn version() -> Version {
version_meta().semver
}
pub fn version_meta() -> VersionMeta {
let cmd = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
let out = Command::new(&cmd)
.arg("--version")
.output()
.unwrap_or_else(|e| { panic!("failed to execute process: {}", e) });
let version_string = String::from_utf8(out.stdout).unwrap();
let mut parts_iter = version_string.split_whitespace();
let rustc_string = parts_iter.next().unwrap();
assert!(rustc_string == "rustc");
let version_string = parts_iter.next().unwrap();
let version = Version::parse(version_string).unwrap();
let hash_string = parts_iter.next().unwrap();
assert!(hash_string.starts_with('('));
let hash_string = &hash_string[1..];
let date_string = parts_iter.next().unwrap();
assert!(date_string.ends_with(')'));
let date_string = &date_string[..date_string.len() - 1];
let channel = if version.pre.is_empty() {
Channel::Stable
} else {
match version.pre[0] {
Identifier::AlphaNumeric(ref s)
if s == "dev" => Channel::Dev,
Identifier::AlphaNumeric(ref s)
if s == "beta" => Channel::Beta,
Identifier::AlphaNumeric(ref s)
if s == "nightly" => Channel::Nightly,
_ => panic!(),
}
};
VersionMeta {
semver: version,
git_short_hash: hash_string.to_string(),
date: date_string.to_string(),
channel: channel,
}
}
pub fn version_matches(req: &str) -> bool {
VersionReq::parse(req).unwrap().matches(&version())
}
#[test]
fn smoketest() {
let v = version();
assert!(v.major >= 1);
assert!(v.minor >= 2);
let v = version_meta();
assert!(v.semver.major >= 1);
assert!(v.semver.minor >= 2);
assert!(version_matches(">= 1.2.0"));
}