ruff/crates/ruff_python_stdlib/src/path.rs
Dhruv Manilawala 2fc38d81e6
Experimental release for Jupyter notebook integration (#5363)
## Summary

Experimental release for Jupyter Notebook integration.

Currently, this requires a user to explicitly opt-in using the
[include](https://beta.ruff.rs/docs/settings/#include) configuration:

```toml
[tool.ruff]
include = ["*.py", "*.pyi", "**/pyproject.toml", "*.ipynb"]
```

Or, a user can pass in the file directly:

```sh
ruff check path/to/notebook.ipynb
```

For known limitations, please refer #5188 

## Test Plan

Following command should work without the `--all-features` flag:

```sh
cargo dev round-trip /path/to/notebook.ipynb
```

Following command should work with the above config file along with
`select = ["ALL"]`:

```sh
cargo run --bin ruff -- check --no-cache --config=../test-repos/openai-cookbook/pyproject.toml --fix ../test-repos/openai-cookbook/
```

Passing the Jupyter notebook directly:

```sh
cargo run --bin ruff -- check --no-cache --isolated --select=ALL --fix ../test-repos/openai-cookbook/examples/Classification_using_embeddings.ipynb
```
2023-06-26 21:22:42 +05:30

54 lines
1.5 KiB
Rust

use std::path::Path;
/// Return `true` if the [`Path`] appears to be that of a Python file.
pub fn is_python_file(path: &Path) -> bool {
path.extension()
.map_or(false, |ext| ext == "py" || ext == "pyi")
}
/// Return `true` if the [`Path`] is named `pyproject.toml`.
pub fn is_project_toml(path: &Path) -> bool {
path.file_name()
.map_or(false, |name| name == "pyproject.toml")
}
/// Return `true` if the [`Path`] appears to be that of a Python interface definition file (`.pyi`).
pub fn is_python_stub_file(path: &Path) -> bool {
path.extension().map_or(false, |ext| ext == "pyi")
}
/// Return `true` if the [`Path`] appears to be that of a Jupyter notebook (`.ipynb`).
pub fn is_jupyter_notebook(path: &Path) -> bool {
path.extension().map_or(false, |ext| ext == "ipynb")
}
#[cfg(test)]
mod tests {
use std::path::Path;
use crate::path::{is_jupyter_notebook, is_python_file};
#[test]
fn inclusions() {
let path = Path::new("foo/bar/baz.py");
assert!(is_python_file(path));
let path = Path::new("foo/bar/baz.pyi");
assert!(is_python_file(path));
let path = Path::new("foo/bar/baz.js");
assert!(!is_python_file(path));
let path = Path::new("foo/bar/baz");
assert!(!is_python_file(path));
}
#[test]
fn test_is_jupyter_notebook() {
let path = Path::new("foo/bar/baz.ipynb");
assert!(is_jupyter_notebook(path));
let path = Path::new("foo/bar/baz.py");
assert!(!is_jupyter_notebook(path));
}
}