Skip to content

Commit a2a3ea8

Browse files
committed
Bring the version command output in line with other rust tools
1 parent 88024c7 commit a2a3ea8

File tree

8 files changed

+105
-66
lines changed

8 files changed

+105
-66
lines changed

crates/rust-analyzer/build.rs

+22-45
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@ use std::{env, path::PathBuf, process::Command};
44

55
fn main() {
66
set_rerun();
7-
println!("cargo:rustc-env=REV={}", rev());
7+
set_commit_info();
8+
if option_env!("CFG_RELEASE").is_none() {
9+
println!("cargo:rustc-env=POKE_RA_DEVS=1");
10+
}
811
}
912

1013
fn set_rerun() {
11-
println!("cargo:rerun-if-env-changed=RUST_ANALYZER_REV");
14+
println!("cargo:rerun-if-env-changed=CFG_RELEASE");
1215

1316
let mut manifest_dir = PathBuf::from(
1417
env::var("CARGO_MANIFEST_DIR").expect("`CARGO_MANIFEST_DIR` is always set by cargo."),
@@ -27,47 +30,21 @@ fn set_rerun() {
2730
println!("cargo:warning=Could not find `.git/HEAD` from manifest dir!");
2831
}
2932

30-
fn rev() -> String {
31-
if let Ok(rev) = env::var("RUST_ANALYZER_REV") {
32-
return rev;
33-
}
34-
35-
if let Some(commit_hash) = commit_hash() {
36-
let mut buf = commit_hash;
37-
38-
if let Some(date) = build_date() {
39-
buf.push(' ');
40-
buf.push_str(&date);
41-
}
42-
43-
let channel = env::var("RUST_ANALYZER_CHANNEL").unwrap_or_else(|_| "dev".to_string());
44-
buf.push(' ');
45-
buf.push_str(&channel);
46-
47-
return buf;
48-
}
49-
50-
"???????".to_string()
51-
}
52-
53-
fn commit_hash() -> Option<String> {
54-
exec("git rev-parse --short HEAD").ok()
55-
}
56-
57-
fn build_date() -> Option<String> {
58-
exec("date -u +%Y-%m-%d").ok()
59-
}
60-
61-
fn exec(command: &str) -> std::io::Result<String> {
62-
let args = command.split_ascii_whitespace().collect::<Vec<_>>();
63-
let output = Command::new(args[0]).args(&args[1..]).output()?;
64-
if !output.status.success() {
65-
return Err(std::io::Error::new(
66-
std::io::ErrorKind::InvalidData,
67-
format!("command {:?} returned non-zero code", command,),
68-
));
69-
}
70-
let stdout = String::from_utf8(output.stdout)
71-
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
72-
Ok(stdout.trim().to_string())
33+
fn set_commit_info() {
34+
let output = match Command::new("git")
35+
.arg("log")
36+
.arg("-1")
37+
.arg("--date=short")
38+
.arg("--format=%H %h %cd")
39+
.output()
40+
{
41+
Ok(output) if output.status.success() => output,
42+
_ => return,
43+
};
44+
let stdout = String::from_utf8(output.stdout).unwrap();
45+
let mut parts = stdout.split_whitespace();
46+
let mut next = || parts.next().unwrap();
47+
println!("cargo:rustc-env=RA_COMMIT_HASH={}", next());
48+
println!("cargo:rustc-env=RA_COMMIT_SHORT_HASH={}", next());
49+
println!("cargo:rustc-env=RA_COMMIT_DATE={}", next())
7350
}

crates/rust-analyzer/src/bin/main.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ fn try_main() -> Result<()> {
7070
return Ok(());
7171
}
7272
if cmd.version {
73-
println!("rust-analyzer {}", env!("REV"));
73+
println!("rust-analyzer {}", rust_analyzer::version());
7474
return Ok(());
7575
}
7676
if cmd.help {
@@ -150,7 +150,7 @@ fn with_extra_thread(
150150
}
151151

152152
fn run_server() -> Result<()> {
153-
tracing::info!("server version {} will start", env!("REV"));
153+
tracing::info!("server version {} will start", rust_analyzer::version());
154154

155155
let (connection, io_threads) = Connection::stdio();
156156

@@ -192,7 +192,7 @@ fn run_server() -> Result<()> {
192192
capabilities: server_capabilities,
193193
server_info: Some(lsp_types::ServerInfo {
194194
name: String::from("rust-analyzer"),
195-
version: Some(String::from(env!("REV"))),
195+
version: Some(rust_analyzer::version().to_string()),
196196
}),
197197
offset_encoding: if supports_utf8(config.caps()) {
198198
Some("utf-8".to_string())

crates/rust-analyzer/src/cli/lsif.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ use crate::cli::{
2222
};
2323
use crate::line_index::{LineEndings, LineIndex, OffsetEncoding};
2424
use crate::to_proto;
25+
use crate::version::version;
2526

2627
/// Need to wrap Snapshot to provide `Clone` impl for `map_with`
2728
struct Snap<DB>(DB);
@@ -312,7 +313,7 @@ impl flags::Lsif {
312313
tool_info: Some(lsp_types::lsif::ToolInfo {
313314
name: "rust-analyzer".to_string(),
314315
args: vec![],
315-
version: Some(env!("REV").to_string()),
316+
version: Some(version().to_string()),
316317
}),
317318
}));
318319
for file in si.files {

crates/rust-analyzer/src/dispatch.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use serde::{de::DeserializeOwned, Serialize};
88
use crate::{
99
global_state::{GlobalState, GlobalStateSnapshot},
1010
main_loop::Task,
11+
version::version,
1112
LspError, Result,
1213
};
1314

@@ -144,7 +145,7 @@ impl<'a> RequestDispatcher<'a> {
144145
match res {
145146
Ok(params) => {
146147
let panic_context =
147-
format!("\nversion: {}\nrequest: {} {:#?}", env!("REV"), R::METHOD, params);
148+
format!("\nversion: {}\nrequest: {} {:#?}", version(), R::METHOD, params);
148149
Some((req, params, panic_context))
149150
}
150151
Err(err) => {
@@ -248,7 +249,7 @@ impl<'a> NotificationDispatcher<'a> {
248249
};
249250
let _pctx = stdx::panic_context::enter(format!(
250251
"\nversion: {}\nnotification: {}",
251-
env!("REV"),
252+
version(),
252253
N::METHOD
253254
));
254255
f(self.global_state, params)?;

crates/rust-analyzer/src/lib.rs

+15-13
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,28 @@ macro_rules! eprintln {
1616
($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
1717
}
1818

19-
mod global_state;
20-
mod reload;
21-
mod main_loop;
22-
mod dispatch;
23-
mod handlers;
2419
mod caps;
2520
mod cargo_target_spec;
26-
mod to_proto;
27-
mod from_proto;
28-
mod semantic_tokens;
29-
mod markdown;
3021
mod diagnostics;
22+
mod diff;
23+
mod dispatch;
24+
mod from_proto;
25+
mod global_state;
26+
mod handlers;
3127
mod line_index;
3228
mod lsp_utils;
33-
mod task_pool;
29+
mod main_loop;
30+
mod markdown;
3431
mod mem_docs;
35-
mod diff;
3632
mod op_queue;
37-
pub mod lsp_ext;
33+
mod reload;
34+
mod semantic_tokens;
35+
mod task_pool;
36+
mod to_proto;
37+
mod version;
38+
3839
pub mod config;
40+
pub mod lsp_ext;
3941

4042
#[cfg(test)]
4143
mod integrated_benchmarks;
@@ -44,7 +46,7 @@ use std::fmt;
4446

4547
use serde::de::DeserializeOwned;
4648

47-
pub use crate::{caps::server_capabilities, main_loop::main_loop};
49+
pub use crate::{caps::server_capabilities, main_loop::main_loop, version::version};
4850

4951
pub type Error = Box<dyn std::error::Error + Send + Sync>;
5052
pub type Result<T, E = Error> = std::result::Result<T, E>;

crates/rust-analyzer/src/lsp_utils.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ impl GlobalState {
7474
/// panicky is a good idea, let's see if we can keep our awesome bleeding
7575
/// edge users from being upset!
7676
pub(crate) fn poke_rust_analyzer_developer(&mut self, message: String) {
77-
let from_source_build = env!("REV").contains("dev");
77+
let from_source_build = option_env!("POKE_RA_DEVS").is_some();
7878
let profiling_enabled = std::env::var("RA_PROFILE").is_ok();
7979
if from_source_build || profiling_enabled {
8080
self.show_message(lsp_types::MessageType::ERROR, message)

crates/rust-analyzer/src/version.rs

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
//! Code for representing rust-analyzer's release version number.
2+
3+
use std::fmt;
4+
5+
/// Information about the git repository where rust-analyzer was built from.
6+
pub struct CommitInfo {
7+
pub short_commit_hash: &'static str,
8+
pub commit_hash: &'static str,
9+
pub commit_date: &'static str,
10+
}
11+
12+
/// Cargo's version.
13+
pub struct VersionInfo {
14+
/// rust-analyzer's version, such as "1.57.0", "1.58.0-beta.1", "1.59.0-nightly", etc.
15+
pub version: &'static str,
16+
/// The release channel we were built for (stable/beta/nightly/dev).
17+
///
18+
/// `None` if not built via rustbuild.
19+
pub release_channel: Option<&'static str>,
20+
/// Information about the Git repository we may have been built from.
21+
///
22+
/// `None` if not built from a git repo.
23+
pub commit_info: Option<CommitInfo>,
24+
}
25+
26+
impl fmt::Display for VersionInfo {
27+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28+
write!(f, "{}", self.version)?;
29+
30+
if let Some(ci) = &self.commit_info {
31+
write!(f, " ({} {})", ci.short_commit_hash, ci.commit_date)?;
32+
};
33+
Ok(())
34+
}
35+
}
36+
37+
/// Returns information about cargo's version.
38+
pub const fn version() -> VersionInfo {
39+
let version = match option_env!("CFG_RELEASE") {
40+
Some(x) => x,
41+
None => "0.0.0",
42+
};
43+
44+
let release_channel = option_env!("CFG_RELEASE_CHANNEL");
45+
let commit_info = match (
46+
option_env!("RA_COMMIT_SHORT_HASH"),
47+
option_env!("RA_COMMIT_HASH"),
48+
option_env!("RA_COMMIT_DATE"),
49+
) {
50+
(Some(short_commit_hash), Some(commit_hash), Some(commit_date)) => {
51+
Some(CommitInfo { short_commit_hash, commit_hash, commit_date })
52+
}
53+
_ => None,
54+
};
55+
56+
VersionInfo { version, release_channel, commit_info }
57+
}

xtask/src/dist.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ fn dist_client(
7272
}
7373

7474
fn dist_server(sh: &Shell, release_channel: &str, target: &Target) -> anyhow::Result<()> {
75-
let _e = sh.push_env("RUST_ANALYZER_CHANNEL", release_channel);
75+
let _e = sh.push_env("CFG_RELEASE_CHANNEL", release_channel);
76+
let _e = sh.push_env("CFG_RELEASE", "0.0.0");
7677
let _e = sh.push_env("CARGO_PROFILE_RELEASE_LTO", "thin");
7778

7879
// Uncomment to enable debug info for releases. Note that:

0 commit comments

Comments
 (0)