File: no_cwd_resolve.py

package info (click to toggle)
python-refurb 1.27.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,700 kB
  • sloc: python: 9,468; makefile: 40; sh: 6
file content (47 lines) | stat: -rw-r--r-- 1,079 bytes parent folder | download
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
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))