From 0c9165fc3aa628b7dd975dade291bb978318e92b Mon Sep 17 00:00:00 2001 From: Dhruv Manilawala Date: Mon, 25 Nov 2024 15:14:30 +0530 Subject: [PATCH] Use `Result` for failed text document retrieval in LSP requests (#14579) ## Summary Ref: https://github.com/astral-sh/ruff-vscode/issues/644#issuecomment-2496588452 ## Test Plan Not sure how to test this as this is mainly to get more context on the panic that the server is raising. --- .../src/server/api/requests/format.rs | 4 ++- .../src/server/api/requests/format_range.rs | 4 ++- .../src/server/api/requests/hover.rs | 4 ++- crates/ruff_server/src/session/index.rs | 27 +++++++++++++++---- 4 files changed, 31 insertions(+), 8 deletions(-) diff --git a/crates/ruff_server/src/server/api/requests/format.rs b/crates/ruff_server/src/server/api/requests/format.rs index 853be16618a6a..77bc1fc8c3dfc 100644 --- a/crates/ruff_server/src/server/api/requests/format.rs +++ b/crates/ruff_server/src/server/api/requests/format.rs @@ -1,3 +1,4 @@ +use anyhow::Context; use lsp_types::{self as types, request as req}; use types::TextEdit; @@ -64,7 +65,8 @@ pub(super) fn format_document(snapshot: &DocumentSnapshot) -> Result Option<&TextDocument> { + pub(crate) fn as_single_document(&self) -> Result<&TextDocument, SingleDocumentError> { match self { - Self::Text { document, .. } => Some(document), + Self::Text { document, .. } => Ok(document), Self::Notebook { notebook, + file_url, cell_url: cell_uri, .. - } => cell_uri - .as_ref() - .and_then(|cell_uri| notebook.cell_document_by_uri(cell_uri)), + } => { + if let Some(cell_uri) = cell_uri { + let cell = notebook + .cell_document_by_uri(cell_uri) + .ok_or_else(|| SingleDocumentError::CellDoesNotExist(cell_uri.clone()))?; + Ok(cell) + } else { + Err(SingleDocumentError::Notebook(file_url.clone())) + } + } } } @@ -618,3 +627,11 @@ impl DocumentQuery { } } } + +#[derive(Debug, Error)] +pub(crate) enum SingleDocumentError { + #[error("Expected a single text document, but found a notebook document: {0}")] + Notebook(Url), + #[error("Cell with URL {0} does not exist in the internal notebook document")] + CellDoesNotExist(Url), +}