Skip to content

Commit

Permalink
Add no-implicit-cwd check
Browse files Browse the repository at this point in the history
  • Loading branch information
dosisod committed Jul 28, 2023
1 parent 3aff865 commit 38e6026
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 0 deletions.
19 changes: 19 additions & 0 deletions docs/checks.md
Original file line number Diff line number Diff line change
Expand Up @@ -1994,4 +1994,23 @@ from datetime import datetime, timezone

datetime.now(timezone.utc)
datetime.fromtimestamp(some_timestamp, tz=timezone.utc)
```

## FURB177: `no-implicit-cwd`

Categories: `pathlib`

If you want to get the current working directory don't call `resolve()` on
an empty `Path()` object, use `Path.cwd()` instead.

Bad:

```python
cwd = Path().resolve()
```

Good:

```python
cwd = Path.cwd()
```
47 changes: 47 additions & 0 deletions refurb/checks/pathlib/no_cwd_resolve.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from dataclasses import dataclass

from mypy.nodes import CallExpr, MemberExpr, RefExpr, StrExpr

from refurb.error import Error


@dataclass
class ErrorInfo(Error):
"""
If you want to get the current working directory don't call `resolve()` on
an empty `Path()` object, use `Path.cwd()` instead.
Bad:
```
cwd = Path().resolve()
```
Good:
```
cwd = Path.cwd()
```
"""

name = "no-implicit-cwd"
code = 177
categories = ("pathlib",)


def check(node: CallExpr, errors: list[Error]) -> None:
match node:
case CallExpr(
callee=MemberExpr(
expr=CallExpr(
callee=RefExpr(fullname="pathlib.Path"),
args=[] | [StrExpr(value="" | ".")] as args,
),
name="resolve",
),
args=[],
):
arg = f'"{args[0].value}"' if args else "" # type: ignore
msg = f"Replace `Path({arg}).resolve()` with `Path.cwd()`"

errors.append(ErrorInfo.from_node(node, msg))
19 changes: 19 additions & 0 deletions test/data/err_177.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import pathlib
from pathlib import Path

# these should match

_ = Path().resolve()
_ = Path("").resolve() # noqa: FURB153
_ = Path(".").resolve() # noqa: FURB153
_ = pathlib.Path().resolve()


# these should not

_ = Path("some_file").resolve()
_ = Path().resolve(True)
_ = Path().resolve(False) # noqa: FURB120

p = Path()
_ = p.resolve()
4 changes: 4 additions & 0 deletions test/data/err_177.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
test/data/err_177.py:6:5 [FURB177]: Replace `Path().resolve()` with `Path.cwd()`
test/data/err_177.py:7:5 [FURB177]: Replace `Path("").resolve()` with `Path.cwd()`
test/data/err_177.py:8:5 [FURB177]: Replace `Path(".").resolve()` with `Path.cwd()`
test/data/err_177.py:9:5 [FURB177]: Replace `Path().resolve()` with `Path.cwd()`

0 comments on commit 38e6026

Please sign in to comment.