-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[flake8-use-pathlib] Add autofix for PTH211
#20009
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
a51d420
[`flake8-use-pathlib`] Add autofix for `PTH102`
chirizxc ac74584
add pr number
chirizxc 6da50c3
fix ci
chirizxc 4e4b643
add snapshots
chirizxc 92a9e59
delete duplicate snapshots
chirizxc 482b218
add test with a space around False
chirizxc 0256054
fix: offer a fix when `dir_fd` is None
chirizxc 71cb3f3
add more whitespace around `True`
chirizxc d01d8ab
use `as_boolean_literal_expr`
chirizxc b6a86e3
fix clippy
chirizxc 994f983
no fix when target_is_directory nonboolean value
dylwil3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
148 changes: 148 additions & 0 deletions
148
crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_symlink.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| use anyhow::anyhow; | ||
| use ruff_diagnostics::{Applicability, Edit, Fix}; | ||
| use ruff_macros::{ViolationMetadata, derive_message_formats}; | ||
| use ruff_python_ast::ExprCall; | ||
| use ruff_text_size::Ranged; | ||
|
|
||
| use crate::checkers::ast::Checker; | ||
| use crate::importer::ImportRequest; | ||
| use crate::preview::is_fix_os_symlink_enabled; | ||
| use crate::rules::flake8_use_pathlib::helpers::{ | ||
| has_unknown_keywords_or_starred_expr, is_keyword_only_argument_non_default, | ||
| is_pathlib_path_call, | ||
| }; | ||
| use crate::{FixAvailability, Violation}; | ||
|
|
||
| /// ## What it does | ||
| /// Checks for uses of `os.symlink`. | ||
| /// | ||
| /// ## Why is this bad? | ||
| /// `pathlib` offers a high-level API for path manipulation, as compared to | ||
| /// the lower-level API offered by `os.symlink`. | ||
| /// | ||
| /// ## Example | ||
| /// ```python | ||
| /// import os | ||
| /// | ||
| /// os.symlink("usr/bin/python", "tmp/python", target_is_directory=False) | ||
| /// ``` | ||
| /// | ||
| /// Use instead: | ||
| /// ```python | ||
| /// from pathlib import Path | ||
| /// | ||
| /// Path("tmp/python").symlink_to("usr/bin/python") | ||
| /// ``` | ||
| /// | ||
| /// ## Known issues | ||
| /// While using `pathlib` can improve the readability and type safety of your code, | ||
| /// it can be less performant than the lower-level alternatives that work directly with strings, | ||
| /// especially on older versions of Python. | ||
| /// | ||
| /// ## Fix Safety | ||
| /// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression. | ||
| /// | ||
| /// ## References | ||
| /// - [Python documentation: `Path.symlink_to`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.symlink_to) | ||
| /// - [PEP 428 – The pathlib module – object-oriented filesystem paths](https://peps.python.org/pep-0428/) | ||
| /// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module) | ||
| /// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/) | ||
| /// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/) | ||
| #[derive(ViolationMetadata)] | ||
| pub(crate) struct OsSymlink; | ||
|
|
||
| impl Violation for OsSymlink { | ||
| const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; | ||
|
|
||
| #[derive_message_formats] | ||
| fn message(&self) -> String { | ||
| "`os.symlink` should be replaced by `Path.symlink_to`".to_string() | ||
| } | ||
|
|
||
| fn fix_title(&self) -> Option<String> { | ||
| Some("Replace with `Path(...).symlink_to(...)`".to_string()) | ||
| } | ||
| } | ||
|
|
||
| /// PTH211 | ||
| pub(crate) fn os_symlink(checker: &Checker, call: &ExprCall, segments: &[&str]) { | ||
| if segments != ["os", "symlink"] { | ||
| return; | ||
| } | ||
|
|
||
| // `dir_fd` is not supported by pathlib, so check if there are non-default values. | ||
| // Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.symlink) | ||
| // ```text | ||
| // 0 1 2 3 | ||
| // os.symlink(src, dst, target_is_directory=False, *, dir_fd=None) | ||
| // ``` | ||
| if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") { | ||
| return; | ||
| } | ||
|
|
||
| let range = call.range(); | ||
| let mut diagnostic = checker.report_diagnostic(OsSymlink, call.func.range()); | ||
|
|
||
| if !is_fix_os_symlink_enabled(checker.settings()) { | ||
| return; | ||
| } | ||
|
|
||
| if call.arguments.len() > 3 { | ||
| return; | ||
| } | ||
|
|
||
| if has_unknown_keywords_or_starred_expr( | ||
| &call.arguments, | ||
| &["src", "dst", "target_is_directory", "dir_fd"], | ||
| ) { | ||
| return; | ||
| } | ||
|
|
||
| let (Some(src), Some(dst)) = ( | ||
| call.arguments.find_argument_value("src", 0), | ||
| call.arguments.find_argument_value("dst", 1), | ||
| ) else { | ||
| return; | ||
| }; | ||
|
|
||
| diagnostic.try_set_fix(|| { | ||
| let (import_edit, binding) = checker.importer().get_or_import_symbol( | ||
| &ImportRequest::import("pathlib", "Path"), | ||
| call.start(), | ||
| checker.semantic(), | ||
| )?; | ||
|
|
||
| let applicability = if checker.comment_ranges().intersects(range) { | ||
| Applicability::Unsafe | ||
| } else { | ||
| Applicability::Safe | ||
| }; | ||
|
|
||
| let locator = checker.locator(); | ||
| let src_code = locator.slice(src.range()); | ||
| let dst_code = locator.slice(dst.range()); | ||
|
|
||
| let target_is_directory = call | ||
| .arguments | ||
| .find_argument_value("target_is_directory", 2) | ||
| .and_then(|expr| { | ||
| let code = locator.slice(expr.range()); | ||
| expr.as_boolean_literal_expr() | ||
| .is_some_and(|bl| !bl.value) | ||
| .then_some(format!(", target_is_directory={code}")) | ||
| }) | ||
| .ok_or_else(|| anyhow!("Non-boolean value passed for `target_is_directory`."))?; | ||
|
|
||
| let replacement = if is_pathlib_path_call(checker, dst) { | ||
| format!("{dst_code}.symlink_to({src_code}{target_is_directory})") | ||
| } else { | ||
| format!("{binding}({dst_code}).symlink_to({src_code}{target_is_directory})") | ||
| }; | ||
|
|
||
| Ok(Fix::applicable_edits( | ||
| Edit::range_replacement(replacement, range), | ||
| [import_edit], | ||
| applicability, | ||
| )) | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.