Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
63 changes: 63 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -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 `#<sha>` 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=...#<sha>"` of
/// the `comline-core` package.
fn rev_from_lock(lock: &str) -> Option<String> {
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 = "<sha>" }`.
fn rev_from_manifest(manifest: &str) -> Option<String> {
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())
}
2 changes: 1 addition & 1 deletion src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
}),
})
}
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

pub mod parser;
pub mod util;
pub mod version;

pub mod analysis;
pub mod handlers;
Expand Down
6 changes: 6 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand Down
54 changes: 54 additions & 0 deletions src/version.rs
Original file line number Diff line number Diff line change
@@ -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})")));
}
}
88 changes: 88 additions & 0 deletions tests/version.rs
Original file line number Diff line number Diff line change
@@ -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<u8> {
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::<usize>().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());
}
Loading