Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "Open Cargo Toml" Action #6518

Closed
wants to merge 8 commits into from
Closed
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ crates/*/target
generated_assists.adoc
generated_features.adoc
generated_diagnostic.adoc
**/.DS_Store
Binary file added crates/ide/.DS_Store
Binary file not shown.
23 changes: 23 additions & 0 deletions crates/rust-analyzer/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1315,6 +1315,29 @@ pub(crate) fn handle_open_docs(
Ok(remote.and_then(|remote| Url::parse(&remote).ok()))
}

pub(crate) fn handle_open_cargo_toml(
snap: GlobalStateSnapshot,
params: lsp_ext::OpenCargoTomlParams,
) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
let _p = profile::span("handle_open_cargo_toml");
let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
let maybe_cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
if maybe_cargo_spec.is_none() {
return Ok(None);
}

let cargo_spec = maybe_cargo_spec.unwrap();
let cargo_toml_path = cargo_spec.workspace_root.join("Cargo.toml");
if !cargo_toml_path.exists() {
return Ok(None);
}
let cargo_toml_url = to_proto::url_from_abs_path(&cargo_toml_path.clone());
let cargo_toml_location =
Location::new(cargo_toml_url.clone(), Range::new(Position::new(0, 0), Position::new(0, 0)));
let res = lsp_types::GotoDefinitionResponse::from(cargo_toml_location);
Ok(Some(res))
}

fn implementation_title(count: usize) -> String {
if count == 1 {
"1 implementation".into()
Expand Down
14 changes: 14 additions & 0 deletions crates/rust-analyzer/src/lsp_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,3 +355,17 @@ impl Request for ExternalDocs {
type Result = Option<lsp_types::Url>;
const METHOD: &'static str = "experimental/externalDocs";
}

pub enum OpenCargoToml {}

impl Request for OpenCargoToml {
type Params = OpenCargoTomlParams;
type Result = Option<lsp_types::GotoDefinitionResponse>;
const METHOD: &'static str = "experimental/openCargoToml";
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OpenCargoTomlParams {
pub text_document: TextDocumentIdentifier,
}
1 change: 1 addition & 0 deletions crates/rust-analyzer/src/main_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,7 @@ impl GlobalState {
.on::<lsp_ext::ResolveCodeActionRequest>(handlers::handle_resolve_code_action)
.on::<lsp_ext::HoverRequest>(handlers::handle_hover)
.on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
.on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
.on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
.on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
.on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
Expand Down
27 changes: 26 additions & 1 deletion docs/dev/lsp-extensions.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!---
lsp_ext.rs hash: 286f8bbac885531a
lsp_ext.rs hash: abcefcde582a570e

If you need to change the above hash to make the test pass, please check if you
need to adjust this doc as well and ping this issue:
Expand Down Expand Up @@ -561,3 +561,28 @@ Such actions on the client side are appended to a hover bottom as command links:
+-----------------------------+
...
```

## Open Cargo.toml

**Issue:** https://github.com/rust-analyzer/rust-analyzer/issues/6462

This request is sent from client to server to open the current project's Cargo.toml

**Method:** `experimental/openCargoToml`

**Request:** `OpenCargoTomlParams`

**Response:** `Location | null`


### Example

```rust
// Cargo.toml
[package]
// src/main.rs

/* cursor here*/
```

`experimental/openCargoToml` returns a single `Link` to the start of the `[package]` keyword.
9 changes: 9 additions & 0 deletions editors/code/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,11 @@
"command": "rust-analyzer.openDocs",
"title": "Open docs under cursor",
"category": "Rust Analyzer"
},
{
"command": "rust-analyzer.openCargoToml",
"title": "Open Cargo.toml",
"category": "Rust Analyzer"
}
],
"keybindings": [
Expand Down Expand Up @@ -1057,6 +1062,10 @@
{
"command": "rust-analyzer.openDocs",
"when": "inRustProject"
},
{
"command": "rust-analyzer.openCargoToml",
"when": "inRustProject"
}
]
}
Expand Down
23 changes: 22 additions & 1 deletion editors/code/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { applySnippetWorkspaceEdit, applySnippetTextEdits } from './snippets';
import { spawnSync } from 'child_process';
import { RunnableQuickPick, selectRunnable, createTask } from './run';
import { AstInspector } from './ast_inspector';
import { isRustDocument, sleep, isRustEditor } from './util';
import { log, isRustDocument, sleep, isRustEditor } from './util';
import { startDebugSession, makeDebugConfig } from './debug';

export * from './ast_inspector';
Expand Down Expand Up @@ -188,6 +188,27 @@ export function parentModule(ctx: Ctx): Cmd {
};
}

export function openCargoToml(ctx: Ctx): Cmd {
return async () => {
const editor = ctx.activeRustEditor;
const client = ctx.client;
if (!editor || !client) return;

const response = await client.sendRequest(ra.openCargoToml, {
textDocument: ctx.client.code2ProtocolConverter.asTextDocumentIdentifier(editor.document),
});
if (!response) return;

const uri = client.protocol2CodeConverter.asUri(response.uri);
const range = client.protocol2CodeConverter.asRange(response.range);

const doc = await vscode.workspace.openTextDocument(uri);
const e = await vscode.window.showTextDocument(doc);
e.selection = new vscode.Selection(range.start, range.start);
e.revealRange(range, vscode.TextEditorRevealType.InCenter);
};
}

export function ssr(ctx: Ctx): Cmd {
return async () => {
const editor = vscode.window.activeTextEditor;
Expand Down
6 changes: 6 additions & 0 deletions editors/code/src/lsp_ext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,9 @@ export interface CommandLinkGroup {
}

export const openDocs = new lc.RequestType<lc.TextDocumentPositionParams, string | void, void>('experimental/externalDocs');

export const openCargoToml = new lc.RequestType<OpenCargoTomlParams, lc.Location, void>("experimental/openCargoToml");

export interface OpenCargoTomlParams {
textDocument: lc.TextDocumentIdentifier;
}
1 change: 1 addition & 0 deletions editors/code/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ async function tryActivate(context: vscode.ExtensionContext) {
ctx.registerCommand('debug', commands.debug);
ctx.registerCommand('newDebugConfig', commands.newDebugConfig);
ctx.registerCommand('openDocs', commands.openDocs);
ctx.registerCommand('openCargoToml', commands.openCargoToml);

defaultOnEnter.dispose();
ctx.registerCommand('onEnter', commands.onEnter);
Expand Down