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

Compute NotebookIndex for Diagnostics on stdin #7663

Merged
merged 4 commits into from Sep 29, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 12 additions & 9 deletions crates/ruff_cli/src/diagnostics.rs
Expand Up @@ -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};
Expand Down Expand Up @@ -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()
};
Expand Down Expand Up @@ -474,14 +468,23 @@ 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([(
fs::relativize_path(path.unwrap_or_else(|| Path::new("-"))),
fixed,
)]),
imports,
notebook_indexes: FxHashMap::default(),
notebook_indexes,
})
}

Expand Down
9 changes: 9 additions & 0 deletions crates/ruff_notebook/src/notebook.rs
Expand Up @@ -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] {
Expand Down