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
157 changes: 155 additions & 2 deletions crates/editor/src/runnables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -715,7 +715,9 @@ mod tests {
use multi_buffer::{MultiBuffer, PathKey};
use project::{
FakeFs, Project, ProjectPath,
lsp_store::lsp_ext_command::{CargoRunnableArgs, Runnable, RunnableArgs, RunnableKind},
lsp_store::lsp_ext_command::{
CargoRunnableArgs, Runnable, RunnableArgs, ShellRunnableArgs,
},
};
use serde_json::json;
use task::{TaskTemplate, TaskTemplates};
Expand Down Expand Up @@ -1028,7 +1030,6 @@ mod tests {
lsp::Position::new(3, 1),
),
}),
kind: RunnableKind::Cargo,
args: RunnableArgs::Cargo(CargoRunnableArgs {
environment: Default::default(),
cwd: path!("/project").into(),
Expand Down Expand Up @@ -1174,4 +1175,156 @@ mod tests {
"Runnables should appear after the buffer is saved to disk"
);
}

// Verifies that a shell runnable from rust-analyzer produces
// a task template that uses the shell program and args.
#[gpui::test]
async fn test_shell_runnable_produces_correct_task_template(cx: &mut TestAppContext) {
init_test(cx, |_| {});

let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/project"),
json!({
"main.rs": indoc! {"
#[test]
fn test_one() {
assert!(true);
}
"},
}),
)
.await;

let project = Project::test(fs, [path!("/project").as_ref()], cx).await;
let language_registry = project.read_with(cx, |project, _| project.languages().clone());
language_registry.add(rust_lang_with_lsp_task_context());

let mut fake_servers = language_registry.register_fake_lsp(
"Rust",
FakeLspAdapter {
name: FAKE_LSP_NAME,
..FakeLspAdapter::default()
},
);

let buffer = project
.update(cx, |project, cx| {
project.open_local_buffer(path!("/project/main.rs"), cx)
})
.await
.unwrap();

let buffer_id = buffer.read_with(cx, |buffer, _| buffer.remote_id());

let multi_buffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
let editor = cx.add_window(|window, cx| {
build_editor_with_project(project.clone(), multi_buffer, window, cx)
});

let fake_server = fake_servers.next().await.expect("fake LSP server");

use project::lsp_store::lsp_ext_command::Runnables;
fake_server.set_request_handler::<Runnables, _, _>(move |params, _| async move {
let text = params.text_document.uri.path().to_string();
if text.contains("main.rs") {
let uri = lsp::Uri::from_file_path(path!("/project/main.rs")).expect("valid uri");
Ok(vec![Runnable {
label: "nextest test_one".into(),
location: Some(lsp::LocationLink {
origin_selection_range: None,
target_uri: uri,
target_range: lsp::Range::new(
lsp::Position::new(0, 0),
lsp::Position::new(3, 1),
),
target_selection_range: lsp::Range::new(
lsp::Position::new(0, 0),
lsp::Position::new(3, 1),
),
}),
args: RunnableArgs::Shell(ShellRunnableArgs {
environment: Default::default(),
cwd: path!("/project").into(),
program: "cargo".into(),
args: vec![
"nextest".into(),
"run".into(),
"--package".into(),
"my-crate".into(),
"--lib".into(),
"--".into(),
"test_one".into(),
"--exact".into(),
],
}),
}])
} else {
Ok(Vec::new())
}
});

editor
.update(cx, |editor, window, cx| {
editor.refresh_runnables(None, window, cx);
})
.expect("editor update");
cx.executor().advance_clock(UPDATE_DEBOUNCE);
cx.executor().run_until_parked();

let labels = editor
.update(cx, |editor, _, _| collect_runnable_labels(editor))
.expect("editor update");
assert_eq!(
labels,
vec![(buffer_id, 0, vec!["nextest test_one".to_string()])],
"shell runnable should appear for #[test] fn"
);

let templates = editor
.update(cx, |editor, _, _| {
editor
.runnables
.runnables
.iter()
.flat_map(|(_, (_, tasks))| {
tasks.iter().flat_map(|(_, runnable_tasks)| {
runnable_tasks
.templates
.iter()
.map(|(_, template)| {
(
template.label.clone(),
template.command.clone(),
template.args.clone(),
)
})
.collect::<Vec<_>>()
})
})
.collect::<Vec<_>>()
})
.expect("editor update");

let (label, command, args) = templates
.iter()
.find(|(label, _, _)| label == "nextest test_one")
.expect("shell runnable task template should exist");
assert_eq!(label, "nextest test_one");
assert_eq!(command, "cargo");
assert_eq!(
args,
&[
"nextest",
"run",
"--package",
"my-crate",
"--lib",
"--",
"test_one",
"--exact",
],
"shell runnable should preserve program args"
);
}
}
109 changes: 98 additions & 11 deletions crates/project/src/lsp_store/lsp_ext_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,41 @@ impl LspCommand for GoToParentModule {
}

// https://rust-analyzer.github.io/book/contributing/lsp-extensions.html#runnables
// Taken from https://github.com/rust-lang/rust-analyzer/blob/a73a37a757a58b43a796d3eb86a1f7dfd0036659/crates/rust-analyzer/src/lsp/ext.rs#L425-L489
// Taken from https://github.com/rust-lang/rust-analyzer/blob/3aaa35b49ef27e15144952aa4f7ba3eecd36fbb4/crates/rust-analyzer/src/lsp/ext.rs#L425-L489
//
// Note that in rust-analyzer, `Runnable` is defined as:
//
// ```
// #[derive(Deserialize, Serialize, Debug, Clone)]
// #[serde(rename_all = "camelCase")]
// pub struct Runnable {
// pub label: String,
// #[serde(skip_serializing_if = "Option::is_none")]
// pub location: Option<lsp_types::LocationLink>,
// pub kind: RunnableKind,
// pub args: RunnableArgs,
// }
//
// #[derive(Deserialize, Serialize, Debug, Clone)]
// #[serde(rename_all = "camelCase")]
// #[serde(untagged)]
// pub enum RunnableArgs {
// Cargo(CargoRunnableArgs),
// Shell(ShellRunnableArgs),
// }
// ```
//
// i.e., RunnableArgs uses serde(untagged) and is not associated with
// RunnableKind. But rust-analyzer always syncs RunnableKind with RunnableArgs:
//
// * https://github.com/rust-lang/rust-analyzer/blob/3aaa35b49ef27e15144952aa4f7ba3eecd36fbb4/crates/rust-analyzer/src/lsp/to_proto.rs#L1608-L1633
// * https://github.com/rust-lang/rust-analyzer/blob/3aaa35b49ef27e15144952aa4f7ba3eecd36fbb4/crates/rust-analyzer/src/lsp/to_proto.rs#L1648-L1653
// * https://github.com/rust-lang/rust-analyzer/blob/3aaa35b49ef27e15144952aa4f7ba3eecd36fbb4/crates/rust-analyzer/src/handlers/request.rs#L1052-L1066
//
// And it really doesn't make any sense for it to be any other way. On top of
// that, the Shell and Cargo variants are similar enough that serde(untagged)
// deserialization has been observed to confuse one for the other. So we rely on
// RunnableKind to determine which variant to deserialize.
pub enum Runnables {}

impl lsp::request::Request for Runnables {
Expand All @@ -524,25 +558,20 @@ pub struct Runnable {
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<lsp::LocationLink>,
pub kind: RunnableKind,
#[serde(flatten)]
pub args: RunnableArgs,
}

/// The `kind` field in the JSON determines which variant is deserialized; see
/// comment on `Runnables` above for more discussion.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
#[serde(tag = "kind", content = "args")]
#[serde(rename_all = "lowercase")]
pub enum RunnableArgs {
Cargo(CargoRunnableArgs),
Shell(ShellRunnableArgs),
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "lowercase")]
pub enum RunnableKind {
Cargo,
Shell,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CargoRunnableArgs {
Expand Down Expand Up @@ -791,3 +820,61 @@ impl lsp::notification::Notification for LspExtClearFlycheck {
type Params = ();
const METHOD: &'static str = "rust-analyzer/clearFlycheck";
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn shell_runnable_deserializes_as_shell() {
// rust-analyzer sends this when `runnables.test.overrideCommand` is
// configured (e.g. for nextest).
let json = serde_json::json!({
"label": "test my_test",
"kind": "shell",
"args": {
"environment": {"RUSTC_TOOLCHAIN": "/path/to/toolchain"},
"cwd": "/project",
"program": "cargo",
"args": ["nextest", "run", "--package", "my-crate", "--lib", "--", "my_test", "--exact", "--include-ignored"]
}
});

let runnable: Runnable =
serde_json::from_value(json).expect("shell runnable should deserialize");
let RunnableArgs::Shell(shell) = &runnable.args else {
panic!("expected Shell variant, got {:?}", runnable.args);
};
assert_eq!(shell.program, "cargo");
assert_eq!(shell.args[0], "nextest");
assert_eq!(shell.args[1], "run");
}

#[test]
fn cargo_runnable_deserializes_as_cargo() {
// Standard cargo runnable from rust-analyzer.
let json = serde_json::json!({
"label": "cargo test -p my-crate",
"kind": "cargo",
"args": {
"environment": {},
"cwd": "/project",
"overrideCargo": null,
"workspaceRoot": "/project",
"cargoArgs": ["test", "--package", "my-crate", "--lib"],
"executableArgs": ["my_test", "--exact"]
}
});

let runnable: Runnable =
serde_json::from_value(json).expect("cargo runnable should deserialize");
let RunnableArgs::Cargo(cargo) = &runnable.args else {
panic!("expected Cargo variant, got {:?}", runnable.args);
};
assert_eq!(
cargo.cargo_args,
vec!["test", "--package", "my-crate", "--lib"]
);
assert_eq!(cargo.executable_args, vec!["my_test", "--exact"]);
}
}
Loading