diff --git a/crates/ruff_cli/src/diagnostics.rs b/crates/ruff_cli/src/diagnostics.rs index 37a5522ccb391..87e35922abc78 100644 --- a/crates/ruff_cli/src/diagnostics.rs +++ b/crates/ruff_cli/src/diagnostics.rs @@ -8,7 +8,7 @@ use std::ops::AddAssign; use std::os::unix::fs::PermissionsExt; use std::path::Path; -use anyhow::{anyhow, Context, Result}; +use anyhow::{Context, Result}; use colored::Colorize; use filetime::FileTime; use log::{debug, error, warn}; @@ -342,13 +342,7 @@ pub(crate) fn lint_path( } let notebook_indexes = if let SourceKind::IpyNotebook(notebook) = source_kind { - FxHashMap::from_iter([( - path.to_str() - .ok_or_else(|| anyhow!("Unable to parse filename: {:?}", path))? - .to_string(), - // Index needs to be computed always to store in cache. - notebook.index().clone(), - )]) + FxHashMap::from_iter([(path.to_string_lossy().to_string(), notebook.into_index())]) } else { FxHashMap::default() }; @@ -474,6 +468,15 @@ pub(crate) fn lint_stdin( ); } + let notebook_indexes = if let SourceKind::IpyNotebook(notebook) = source_kind { + FxHashMap::from_iter([( + path.map_or_else(|| "-".into(), |path| path.to_string_lossy().to_string()), + notebook.into_index(), + )]) + } else { + FxHashMap::default() + }; + Ok(Diagnostics { messages, fixed: FxHashMap::from_iter([( @@ -481,7 +484,7 @@ pub(crate) fn lint_stdin( fixed, )]), imports, - notebook_indexes: FxHashMap::default(), + notebook_indexes, }) } diff --git a/crates/ruff_notebook/src/notebook.rs b/crates/ruff_notebook/src/notebook.rs index 5b87bc86e332f..4d5d0204eeb2a 100644 --- a/crates/ruff_notebook/src/notebook.rs +++ b/crates/ruff_notebook/src/notebook.rs @@ -369,6 +369,15 @@ impl Notebook { self.index.get_or_init(|| self.build_index()) } + /// Return the Jupyter notebook index, consuming the notebook. + /// + /// The index is built only once when required. This is only used to + /// report diagnostics, so by that time all of the fixes must have + /// been applied if `--fix` was passed. + pub fn into_index(mut self) -> NotebookIndex { + self.index.take().unwrap_or_else(|| self.build_index()) + } + /// Return the cell offsets for the concatenated source code corresponding /// the Jupyter notebook. pub fn cell_offsets(&self) -> &[TextSize] {