1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
from dataclasses import dataclass
from mypy.nodes import CallExpr, IndexExpr, NameExpr, OpExpr, SliceExpr, StrExpr
from refurb.error import Error
from .util import is_pathlike
@dataclass
class ErrorInfo(Error):
"""
A common operation is changing the extension of a file. If you have an
existing `Path` object, you don't need to convert it to a string, slice
it, and append a new extension. Instead, use the `with_suffix()` method:
Bad:
```
new_filepath = str(Path("file.txt"))[:4] + ".md"
```
Good:
```
new_filepath = Path("file.txt").with_suffix(".md")
```
"""
name = "use-pathlib-with-suffix"
code = 100
msg: str = "Use `Path(x).with_suffix(y)` instead of slice and concat"
categories = ("pathlib",)
def check(node: OpExpr, errors: list[Error]) -> None:
match node:
case OpExpr(
op="+",
left=IndexExpr(
base=CallExpr(
callee=NameExpr(name="str"),
args=[arg],
),
index=SliceExpr(begin_index=None),
),
right=StrExpr(),
) if is_pathlike(arg):
errors.append(ErrorInfo.from_node(arg))
|