Consider VS Code cell metadata to determine valid code cells (#12864)

## Summary

This PR adds support for VS Code specific cell metadata to consider when
collecting valid code cells.

For context, Ruff only runs on valid code cells. These are the code
cells that doesn't contain cell magics. Previously, Ruff only used the
notebook's metadata to determine whether it's a Python notebook. But, in
VS Code, a notebook's preferred language might be Python but it could
still contain code cells for other languages. This can be determined
with the `metadata.vscode.languageId` field.

### References:
* https://code.visualstudio.com/docs/languages/identifiers
* e6c009a3d4/extensions/ipynb/src/serializers.ts (L104-L107)
*
e6c009a3d4/extensions/ipynb/src/serializers.ts (L117-L122)

This brings us one step closer to fixing #12281.

## Test Plan

Add test cases for `is_valid_python_code_cell` and an integration test
case which showcase running it end to end. The test notebook contains a
JavaScript code cell and a Python code cell.
This commit is contained in:
Dhruv Manilawala 2024-08-13 22:09:56 +05:30 committed by GitHub
parent 899a52390b
commit ff53db3d99
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 226 additions and 21 deletions

View file

@ -6,6 +6,7 @@ use itertools::Itertools;
use ruff_text_size::{TextRange, TextSize};
use crate::schema::{Cell, SourceValue};
use crate::CellMetadata;
impl fmt::Display for SourceValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@ -35,7 +36,7 @@ impl Cell {
matches!(self, Cell::Code(_))
}
pub fn metadata(&self) -> &serde_json::Value {
pub fn metadata(&self) -> &CellMetadata {
match self {
Cell::Code(cell) => &cell.metadata,
Cell::Markdown(cell) => &cell.metadata,
@ -54,11 +55,21 @@ impl Cell {
/// Return `true` if it's a valid code cell.
///
/// A valid code cell is a cell where the cell type is [`Cell::Code`] and the
/// source doesn't contain a cell magic.
pub(crate) fn is_valid_code_cell(&self) -> bool {
/// A valid code cell is a cell where:
/// 1. The cell type is [`Cell::Code`]
/// 2. The source doesn't contain a cell magic
/// 3. If the language id is set, it should be `python`
pub(crate) fn is_valid_python_code_cell(&self) -> bool {
let source = match self {
Cell::Code(cell) => &cell.source,
Cell::Code(cell)
if cell
.metadata
.vscode
.as_ref()
.map_or(true, |vscode| vscode.language_id == "python") =>
{
&cell.source
}
_ => return false,
};
// Ignore cells containing cell magic as they act on the entire cell