diff --git a/README.md b/README.md index 238da53..e80bd94 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,18 @@ cargo build --release The LSP server binary will be available at `target/release/comline-lsp`. +`comline-lsp --version` prints the server's version and the `comline-core` +commit it was built against: + +``` +comline-lsp 0.1.0 (core 14ce54658455206d639ddc4fbe6d609d20292587) +``` + +The `initialize` result's `serverInfo.version` is the same text without the +name, so a client can tell which grammar and checks the running server has. +The commit is read from `Cargo.lock` at build time, else from `Cargo.toml`, +else it is `unknown`. + ## Editor Integration ### Visual Studio Code diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..8b1a55d --- /dev/null +++ b/build.rs @@ -0,0 +1,63 @@ +//! Records the `comline-core` commit this build links, for `comline-lsp +//! --version` and the `initialize` result (`src/version.rs`). +//! +//! The commit comes from `Cargo.lock` (the `#` of the `comline-core` +//! git source), which is what the build resolved. The lock isn't committed +//! here, and a build that doesn't see one (`cargo install`, a git dependency) +//! falls back to the full `rev` in `Cargo.toml`, then to `unknown`. + +use std::{env, fs, path::Path}; + +fn main() { + let dir = env::var("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"); + let dir = Path::new(&dir); + + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed=Cargo.toml"); + if dir.join("Cargo.lock").exists() { + println!("cargo:rerun-if-changed=Cargo.lock"); + } + + let rev = dir + .ancestors() + .filter_map(|d| fs::read_to_string(d.join("Cargo.lock")).ok()) + .find_map(|lock| rev_from_lock(&lock)) + .or_else(|| { + let manifest = fs::read_to_string(dir.join("Cargo.toml")).ok()?; + rev_from_manifest(&manifest) + }) + .unwrap_or_else(|| "unknown".to_string()); + + println!("cargo:rustc-env=COMLINE_CORE_REV={rev}"); +} + +fn is_sha(s: &str) -> bool { + s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// `source = "git+https://github.com/ComlineProject/core?rev=...#"` of +/// the `comline-core` package. +fn rev_from_lock(lock: &str) -> Option { + let mut package = ""; + for line in lock.lines() { + if let Some(name) = line.strip_prefix("name = \"") { + package = name.trim_end_matches('"'); + } else if package == "comline-core" { + if let Some(source) = line.strip_prefix("source = \"git+") { + let sha = source.rsplit('#').next()?.trim_end_matches('"'); + return is_sha(sha).then(|| sha.to_ascii_lowercase()); + } + } + } + None +} + +/// `comline-core = { git = "...", rev = "" }`. +fn rev_from_manifest(manifest: &str) -> Option { + let line = manifest + .lines() + .find(|l| l.trim_start().starts_with("comline-core"))?; + let rest = line.split("rev = \"").nth(1)?; + let sha = rest.split('"').next()?; + is_sha(sha).then(|| sha.to_ascii_lowercase()) +} diff --git a/src/backend.rs b/src/backend.rs index 59e33ba..42a85cb 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -375,7 +375,7 @@ impl LanguageServer for Backend { }, server_info: Some(ServerInfo { name: "Comline Language Server".to_string(), - version: Some(env!("CARGO_PKG_VERSION").to_string()), + version: Some(crate::version::server_version()), }), }) } diff --git a/src/lib.rs b/src/lib.rs index 0cb4a2e..46d57a0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ pub mod parser; pub mod util; +pub mod version; pub mod analysis; pub mod handlers; diff --git a/src/main.rs b/src/main.rs index 2b35768..bb5d143 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,11 +2,17 @@ //! library. Built only with the `server` feature (see Cargo.toml). use comline_language_server::backend::Backend; +use comline_language_server::version; use tower_lsp::{LspService, Server}; use tracing_subscriber::{fmt, prelude::*, EnvFilter}; #[tokio::main] async fn main() { + if std::env::args().any(|arg| arg == "--version" || arg == "-V") { + println!("comline-lsp {}", version::server_version()); + return; + } + tracing_subscriber::registry() .with(fmt::layer().with_writer(std::io::stderr)) .with(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into())) diff --git a/src/version.rs b/src/version.rs new file mode 100644 index 0000000..a063749 --- /dev/null +++ b/src/version.rs @@ -0,0 +1,54 @@ +//! What this build is: the server's version and the `comline-core` commit it +//! links. Printed by `comline-lsp --version` and returned as +//! `serverInfo.version` in the `initialize` result, in the same form, so a +//! client reads the core commit from either with one pattern +//! (`core ([0-9a-f]{40})`). + +/// The `comline-core` commit this build links, 40 hex digits, or `unknown` +/// (`build.rs`). +pub const CORE_REV: &str = env!("COMLINE_CORE_REV"); + +/// `0.1.0 (core 14ce54658455206d639ddc4fbe6d609d20292587)`. +pub fn server_version() -> String { + format!("{} (core {CORE_REV})", env!("CARGO_PKG_VERSION")) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The commit in the manifest's `comline-core` line, which a build with no + /// lock reads and a build with one agrees with. + fn manifest_rev() -> String { + let manifest = include_str!("../Cargo.toml"); + let line = manifest + .lines() + .find(|l| l.trim_start().starts_with("comline-core")) + .expect("a comline-core dependency"); + line.split("rev = \"") + .nth(1) + .and_then(|rest| rest.split('"').next()) + .expect("a rev on it") + .to_string() + } + + #[test] + fn core_rev_is_the_pinned_commit() { + assert_eq!(CORE_REV.len(), 40, "{CORE_REV}"); + assert!( + CORE_REV.bytes().all(|b| b.is_ascii_hexdigit()), + "{CORE_REV}" + ); + assert!(CORE_REV.starts_with(&manifest_rev()), "{CORE_REV}"); + } + + #[test] + fn version_carries_the_core_rev_in_one_pattern() { + let version = server_version(); + assert_eq!( + version, + format!("{} (core {CORE_REV})", env!("CARGO_PKG_VERSION")) + ); + assert!(version.ends_with(&format!("(core {CORE_REV})"))); + } +} diff --git a/tests/version.rs b/tests/version.rs new file mode 100644 index 0000000..bd5c3f7 --- /dev/null +++ b/tests/version.rs @@ -0,0 +1,88 @@ +// What `comline-lsp` says about itself: `--version`, and `serverInfo` in the +// `initialize` result. Both carry the `comline-core` commit the build links. + +#![cfg(feature = "server")] + +use std::io::{BufRead, BufReader, Read, Write}; +use std::process::{Command, Stdio}; + +use comline_language_server::version::{server_version, CORE_REV}; + +const BIN: &str = env!("CARGO_BIN_EXE_comline-lsp"); + +#[test] +fn test_version_flag_prints_server_and_core_rev() { + let output = Command::new(BIN).arg("--version").output().unwrap(); + assert!(output.status.success()); + assert_eq!( + String::from_utf8(output.stdout).unwrap(), + format!("comline-lsp {}\n", server_version()) + ); + assert!(server_version().contains(&format!("core {CORE_REV}"))); +} + +fn frame(message: &serde_json::Value) -> Vec { + let body = message.to_string(); + format!("Content-Length: {}\r\n\r\n{body}", body.len()).into_bytes() +} + +/// The next `Content-Length`-framed message on `stdout`. +fn read_message(stdout: &mut impl BufRead) -> serde_json::Value { + let mut length = None; + loop { + let mut line = String::new(); + assert_ne!( + stdout.read_line(&mut line).unwrap(), + 0, + "the server closed stdout" + ); + let line = line.trim_end(); + if line.is_empty() { + break; + } + if let Some(value) = line.strip_prefix("Content-Length: ") { + length = Some(value.parse::().unwrap()); + } + } + let mut body = vec![0; length.expect("a Content-Length header")]; + stdout.read_exact(&mut body).unwrap(); + serde_json::from_slice(&body).unwrap() +} + +#[test] +fn test_initialize_reports_server_info_with_core_rev() { + let mut child = Command::new(BIN) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + + stdin + .write_all(&frame(&serde_json::json!({ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"processId": null, "rootUri": null, "capabilities": {}} + }))) + .unwrap(); + let initialize = read_message(&mut stdout); + + // Let the server exit rather than leave it for the test runner to reap. + stdin + .write_all(&frame( + &serde_json::json!({"jsonrpc": "2.0", "id": 2, "method": "shutdown"}), + )) + .unwrap(); + stdin + .write_all(&frame( + &serde_json::json!({"jsonrpc": "2.0", "method": "exit"}), + )) + .unwrap(); + drop(stdin); + child.wait().unwrap(); + + let info = &initialize["result"]["serverInfo"]; + assert_eq!(info["name"], "Comline Language Server", "{initialize}"); + assert_eq!(info["version"], server_version().as_str()); +}