diff --git a/crates/ruff_server/src/server/api/requests/format.rs b/crates/ruff_server/src/server/api/requests/format.rs index 853be16618..77bc1fc8c3 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), +}