ruff: enable upgrade checks

This commit is contained in:
Jörg Thalheim 2023-08-25 08:53:31 +02:00 committed by mergify[bot]
parent 4f2d6c40e1
commit e0239251cb
18 changed files with 64 additions and 76 deletions

View File

@ -3,7 +3,7 @@ import os
import shutil import shutil
import sys import sys
import tempfile import tempfile
from typing import NoReturn, Optional from typing import NoReturn
from .eval import CargoLockInSource, Package, eval_attr from .eval import CargoLockInSource, Package, eval_attr
from .options import Options from .options import Options
@ -186,7 +186,7 @@ def write_commit_message(path: str, package: Package) -> None:
f.write("\n") f.write("\n")
def find_git_root(path: str) -> Optional[str]: def find_git_root(path: str) -> str | None:
prefix = [path] prefix = [path]
release_nix = [".git"] release_nix = [".git"]
while True: while True:

View File

@ -2,7 +2,7 @@ import json
import os import os
from dataclasses import InitVar, dataclass, field from dataclasses import InitVar, dataclass, field
from textwrap import dedent, indent from textwrap import dedent, indent
from typing import Any, Dict, List, Literal, Optional from typing import Any, Literal
from urllib.parse import ParseResult, urlparse from urllib.parse import ParseResult, urlparse
from .errors import UpdateError from .errors import UpdateError
@ -43,32 +43,32 @@ class Package:
old_version: str old_version: str
filename: str filename: str
line: int line: int
urls: Optional[List[str]] urls: list[str] | None
url: Optional[str] url: str | None
src_homepage: Optional[str] src_homepage: str | None
changelog: Optional[str] changelog: str | None
rev: str rev: str
hash: Optional[str] hash: str | None
go_modules: Optional[str] go_modules: str | None
go_modules_old: Optional[str] go_modules_old: str | None
cargo_deps: Optional[str] cargo_deps: str | None
npm_deps: Optional[str] npm_deps: str | None
tests: List[str] tests: list[str]
has_update_script: bool has_update_script: bool
raw_version_position: InitVar[Optional[Dict[str, Any]]] raw_version_position: InitVar[dict[str, Any] | None]
raw_cargo_lock: InitVar[Literal[False] | str | None] raw_cargo_lock: InitVar[Literal[False] | str | None]
parsed_url: Optional[ParseResult] = None parsed_url: ParseResult | None = None
new_version: Optional[Version] = None new_version: Version | None = None
version_position: Optional[Position] = field(init=False) version_position: Position | None = field(init=False)
cargo_lock: CargoLock = field(init=False) cargo_lock: CargoLock = field(init=False)
diff_url: Optional[str] = None diff_url: str | None = None
def __post_init__( def __post_init__(
self, self,
import_path: str, import_path: str,
raw_version_position: Optional[Dict[str, Any]], raw_version_position: dict[str, Any] | None,
raw_cargo_lock: Literal[False] | str | None, raw_cargo_lock: Literal[False] | str | None,
) -> None: ) -> None:
url = self.url or (self.urls[0] if self.urls else None) url = self.url or (self.urls[0] if self.urls else None)
@ -90,7 +90,7 @@ class Package:
def eval_expression( def eval_expression(
escaped_import_path: str, attr: str, flake: bool, system: Optional[str] escaped_import_path: str, attr: str, flake: bool, system: str | None
) -> str: ) -> str:
system = f'"{system}"' if system else "builtins.currentSystem" system = f'"{system}"' if system else "builtins.currentSystem"

View File

@ -1,12 +1,9 @@
import re import re
from typing import Optional
from .utils import run from .utils import run
def old_version_from_diff( def old_version_from_diff(diff: str, linenumber: int, new_version: str) -> str | None:
diff: str, linenumber: int, new_version: str
) -> Optional[str]:
current_line = 0 current_line = 0
old_str = None old_str = None
new_str = None new_str = None
@ -37,7 +34,7 @@ def old_version_from_diff(
def old_version_from_git( def old_version_from_git(
filename: str, linenumber: int, new_version: str filename: str, linenumber: int, new_version: str
) -> Optional[str]: ) -> str | None:
proc = run( proc = run(
["git", "diff", "--color=never", "--word-diff=porcelain", "--", filename], ["git", "diff", "--color=never", "--word-diff=porcelain", "--", filename],
) )

View File

@ -1,7 +1,6 @@
import json import json
import os import os
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import List, Optional
from .version.version import VersionPreference from .version.version import VersionPreference
@ -14,19 +13,19 @@ class Options:
version_preference: VersionPreference = VersionPreference.STABLE version_preference: VersionPreference = VersionPreference.STABLE
version_regex: str = "(.*)" version_regex: str = "(.*)"
import_path: str = os.getcwd() import_path: str = os.getcwd()
override_filename: Optional[str] = None override_filename: str | None = None
url: Optional[str] = None url: str | None = None
commit: bool = False commit: bool = False
use_update_script: bool = False use_update_script: bool = False
write_commit_message: Optional[str] = None write_commit_message: str | None = None
shell: bool = False shell: bool = False
run: bool = False run: bool = False
build: bool = False build: bool = False
test: bool = False test: bool = False
review: bool = False review: bool = False
format: bool = False format: bool = False
system: Optional[str] = None system: str | None = None
extra_flags: List[str] = field(default_factory=list) extra_flags: list[str] = field(default_factory=list)
def __post_init__(self) -> None: def __post_init__(self) -> None:
self.escaped_attribute = ".".join(map(json.dumps, self.attribute.split("."))) self.escaped_attribute = ".".join(map(json.dumps, self.attribute.split(".")))

View File

@ -9,7 +9,6 @@ import tomllib
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from os import path from os import path
from pathlib import Path from pathlib import Path
from typing import Dict, Optional, Tuple
from .errors import UpdateError from .errors import UpdateError
from .eval import CargoLockInSource, CargoLockInStore, Package, eval_attr from .eval import CargoLockInSource, CargoLockInStore, Package, eval_attr
@ -93,8 +92,8 @@ def get_package(opts: Options) -> str:
def nix_prefetch(opts: Options, attr: str) -> str: def nix_prefetch(opts: Options, attr: str) -> str:
expr = f"{get_package(opts)}.{attr}" expr = f"{get_package(opts)}.{attr}"
extra_env: Dict[str, str] = {} extra_env: dict[str, str] = {}
tempdir: Optional[tempfile.TemporaryDirectory[str]] = None tempdir: tempfile.TemporaryDirectory[str] | None = None
stderr = "" stderr = ""
if extra_env.get("XDG_RUNTIME_DIR") is None: if extra_env.get("XDG_RUNTIME_DIR") is None:
tempdir = tempfile.TemporaryDirectory() tempdir = tempfile.TemporaryDirectory()
@ -135,7 +134,7 @@ def disable_check_meta(opts: Options) -> str:
return f'(if (builtins.hasAttr "config" (builtins.functionArgs (import {opts.escaped_import_path}))) then {{ config.checkMeta = false; overlays = []; }} else {{ }})' return f'(if (builtins.hasAttr "config" (builtins.functionArgs (import {opts.escaped_import_path}))) then {{ config.checkMeta = false; overlays = []; }} else {{ }})'
def git_prefetch(x: Tuple[str, Tuple[str, str]]) -> Tuple[str, str]: def git_prefetch(x: tuple[str, tuple[str, str]]) -> tuple[str, str]:
rev, (key, url) = x rev, (key, url) = x
res = run(["nix-prefetch-git", url, rev, "--fetch-submodules"]) res = run(["nix-prefetch-git", url, rev, "--fetch-submodules"])
return key, to_sri(json.loads(res.stdout)["sha256"]) return key, to_sri(json.loads(res.stdout)["sha256"])
@ -244,7 +243,7 @@ def update_cargo_lock(
print(line, end="") print(line, end="")
def print_hashes(hashes: Dict[str, str], indent: str) -> None: def print_hashes(hashes: dict[str, str], indent: str) -> None:
if not hashes: if not hashes:
return return
print(f"{indent}outputHashes = {{") print(f"{indent}outputHashes = {{")

View File

@ -1,8 +1,9 @@
import os import os
import subprocess import subprocess
import sys import sys
from collections.abc import Callable
from pathlib import Path from pathlib import Path
from typing import IO, Any, Callable, Dict, List, Optional from typing import IO, Any
HAS_TTY = sys.stdout.isatty() HAS_TTY = sys.stdout.isatty()
ROOT = Path(os.path.dirname(os.path.realpath(__file__))) ROOT = Path(os.path.dirname(os.path.realpath(__file__)))
@ -23,12 +24,12 @@ info = color_text(32)
def run( def run(
command: List[str], command: list[str],
cwd: Optional[Path | str] = None, cwd: Path | str | None = None,
stdout: None | int | IO[Any] = subprocess.PIPE, stdout: None | int | IO[Any] = subprocess.PIPE,
stderr: None | int | IO[Any] = None, stderr: None | int | IO[Any] = None,
check: bool = True, check: bool = True,
extra_env: Dict[str, str] = {}, extra_env: dict[str, str] = {},
) -> "subprocess.CompletedProcess[str]": ) -> "subprocess.CompletedProcess[str]":
info("$ " + " ".join(command)) info("$ " + " ".join(command))
env = os.environ.copy() env = os.environ.copy()

View File

@ -1,6 +1,7 @@
import re import re
from collections.abc import Callable
from functools import partial from functools import partial
from typing import Callable, List, Optional, Protocol from typing import Protocol
from urllib.parse import ParseResult from urllib.parse import ParseResult
from ..errors import VersionError from ..errors import VersionError
@ -25,11 +26,11 @@ from .version import Version, VersionPreference
class SnapshotFetcher(Protocol): class SnapshotFetcher(Protocol):
def __call__(self, url: ParseResult, branch: str) -> List[Version]: def __call__(self, url: ParseResult, branch: str) -> list[Version]:
... ...
fetchers: List[Callable[[ParseResult], List[Version]]] = [ fetchers: list[Callable[[ParseResult], list[Version]]] = [
fetch_crate_versions, fetch_crate_versions,
fetch_pypi_versions, fetch_pypi_versions,
fetch_gitea_versions, fetch_gitea_versions,
@ -40,14 +41,14 @@ fetchers: List[Callable[[ParseResult], List[Version]]] = [
fetch_sourcehut_versions, fetch_sourcehut_versions,
] ]
branch_snapshots_fetchers: List[SnapshotFetcher] = [ branch_snapshots_fetchers: list[SnapshotFetcher] = [
fetch_gitea_snapshots, fetch_gitea_snapshots,
fetch_github_snapshots, fetch_github_snapshots,
fetch_gitlab_snapshots, fetch_gitlab_snapshots,
] ]
def extract_version(version: Version, version_regex: str) -> Optional[Version]: def extract_version(version: Version, version_regex: str) -> Version | None:
pattern = re.compile(version_regex) pattern = re.compile(version_regex)
match = re.match(pattern, version.number) match = re.match(pattern, version.number)
if match is not None: if match is not None:
@ -73,12 +74,12 @@ def fetch_latest_version(
url: ParseResult, url: ParseResult,
preference: VersionPreference, preference: VersionPreference,
version_regex: str, version_regex: str,
branch: Optional[str] = None, branch: str | None = None,
old_rev: Optional[str] = None, old_rev: str | None = None,
version_prefix: str = "", version_prefix: str = "",
) -> Version: ) -> Version:
unstable: List[str] = [] unstable: list[str] = []
filtered: List[str] = [] filtered: list[str] = []
used_fetchers = fetchers used_fetchers = fetchers
if preference == VersionPreference.BRANCH: if preference == VersionPreference.BRANCH:
used_fetchers = [partial(f, branch=branch) for f in branch_snapshots_fetchers] used_fetchers = [partial(f, branch=branch) for f in branch_snapshots_fetchers]

View File

@ -1,13 +1,12 @@
import json import json
import urllib.request import urllib.request
from typing import List
from urllib.parse import ParseResult from urllib.parse import ParseResult
from ..utils import info from ..utils import info
from .version import Version from .version import Version
def fetch_crate_versions(url: ParseResult) -> List[Version]: def fetch_crate_versions(url: ParseResult) -> list[Version]:
if url.netloc != "crates.io": if url.netloc != "crates.io":
return [] return []
parts = url.path.split("/") parts = url.path.split("/")

View File

@ -1,12 +1,11 @@
import json import json
from typing import List
from urllib.parse import ParseResult from urllib.parse import ParseResult
from urllib.request import urlopen from urllib.request import urlopen
from .version import Version from .version import Version
def fetch_gitea_versions(url: ParseResult) -> List[Version]: def fetch_gitea_versions(url: ParseResult) -> list[Version]:
if url.netloc not in ["codeberg.org", "gitea.com", "notabug.org"]: if url.netloc not in ["codeberg.org", "gitea.com", "notabug.org"]:
return [] return []
@ -17,7 +16,7 @@ def fetch_gitea_versions(url: ParseResult) -> List[Version]:
return [Version(tag["name"]) for tag in tags] return [Version(tag["name"]) for tag in tags]
def fetch_gitea_snapshots(url: ParseResult, branch: str) -> List[Version]: def fetch_gitea_snapshots(url: ParseResult, branch: str) -> list[Version]:
if url.netloc not in ["codeberg.org", "gitea.com", "notabug.org"]: if url.netloc not in ["codeberg.org", "gitea.com", "notabug.org"]:
return [] return []

View File

@ -1,7 +1,6 @@
import re import re
import urllib.request import urllib.request
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from typing import List
from urllib.parse import ParseResult, urlparse from urllib.parse import ParseResult, urlparse
from xml.etree.ElementTree import Element from xml.etree.ElementTree import Element
@ -21,7 +20,7 @@ def version_from_entry(entry: Element) -> Version:
return Version(url.path.split("/")[-1]) return Version(url.path.split("/")[-1])
def fetch_github_versions(url: ParseResult) -> List[Version]: def fetch_github_versions(url: ParseResult) -> list[Version]:
if url.netloc != "github.com": if url.netloc != "github.com":
return [] return []
parts = url.path.split("/") parts = url.path.split("/")
@ -36,7 +35,7 @@ def fetch_github_versions(url: ParseResult) -> List[Version]:
return [version_from_entry(x) for x in releases] return [version_from_entry(x) for x in releases]
def fetch_github_snapshots(url: ParseResult, branch: str) -> List[Version]: def fetch_github_snapshots(url: ParseResult, branch: str) -> list[Version]:
if url.netloc != "github.com": if url.netloc != "github.com":
return [] return []
parts = url.path.split("/") parts = url.path.split("/")

View File

@ -2,7 +2,6 @@ import json
import re import re
import urllib.request import urllib.request
from datetime import datetime from datetime import datetime
from typing import List
from urllib.parse import ParseResult, quote_plus from urllib.parse import ParseResult, quote_plus
from ..errors import VersionError from ..errors import VersionError
@ -14,7 +13,7 @@ GITLAB_API = re.compile(
) )
def fetch_gitlab_versions(url: ParseResult) -> List[Version]: def fetch_gitlab_versions(url: ParseResult) -> list[Version]:
match = GITLAB_API.match(url.geturl()) match = GITLAB_API.match(url.geturl())
if not match: if not match:
return [] return []
@ -42,7 +41,7 @@ def fetch_gitlab_versions(url: ParseResult) -> List[Version]:
return releases return releases
def fetch_gitlab_snapshots(url: ParseResult, branch: str) -> List[Version]: def fetch_gitlab_snapshots(url: ParseResult, branch: str) -> list[Version]:
match = GITLAB_API.match(url.geturl()) match = GITLAB_API.match(url.geturl())
if not match: if not match:
return [] return []

View File

@ -1,13 +1,12 @@
import json import json
import urllib.request import urllib.request
from typing import List
from urllib.parse import ParseResult from urllib.parse import ParseResult
from ..utils import info from ..utils import info
from .version import Version from .version import Version
def fetch_pypi_versions(url: ParseResult) -> List[Version]: def fetch_pypi_versions(url: ParseResult) -> list[Version]:
if url.netloc != "pypi": if url.netloc != "pypi":
return [] return []
parts = url.path.split("/") parts = url.path.split("/")

View File

@ -1,6 +1,5 @@
import json import json
import urllib.request import urllib.request
from typing import List
from urllib.parse import ParseResult from urllib.parse import ParseResult
from ..errors import VersionError from ..errors import VersionError
@ -8,7 +7,7 @@ from ..utils import info
from .version import Version from .version import Version
def fetch_rubygem_versions(url: ParseResult) -> List[Version]: def fetch_rubygem_versions(url: ParseResult) -> list[Version]:
if url.netloc != "rubygems.org": if url.netloc != "rubygems.org":
return [] return []
parts = url.path.split("/") parts = url.path.split("/")
@ -21,7 +20,7 @@ def fetch_rubygem_versions(url: ParseResult) -> List[Version]:
if len(json_versions) == 0: if len(json_versions) == 0:
raise VersionError("No versions found") raise VersionError("No versions found")
versions: List[Version] = [] versions: list[Version] = []
for version in json_versions: for version in json_versions:
number = version["number"] number = version["number"]
assert isinstance(number, str) assert isinstance(number, str)

View File

@ -1,7 +1,6 @@
import re import re
import urllib.request import urllib.request
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from typing import List, Optional
from urllib.parse import ParseResult, urljoin, urlparse from urllib.parse import ParseResult, urljoin, urlparse
from xml.etree.ElementTree import Element from xml.etree.ElementTree import Element
@ -11,7 +10,7 @@ from .version import Version
filename_regex = re.compile(r"-(\d+(?:\.\d+)*(?:-[^-.]+)?)\.tar\.[^.]+$") filename_regex = re.compile(r"-(\d+(?:\.\d+)*(?:-[^-.]+)?)\.tar\.[^.]+$")
def version_from_link(a: Element, baseurl: str) -> Optional[Version]: def version_from_link(a: Element, baseurl: str) -> Version | None:
try: try:
href = a.attrib["href"] href = a.attrib["href"]
except KeyError: except KeyError:
@ -23,7 +22,7 @@ def version_from_link(a: Element, baseurl: str) -> Optional[Version]:
return Version(m[1]) return Version(m[1])
def fetch_savannah_versions(url: ParseResult) -> List[Version]: def fetch_savannah_versions(url: ParseResult) -> list[Version]:
if url.scheme != "mirror" or url.netloc != "savannah": if url.scheme != "mirror" or url.netloc != "savannah":
return [] return []
pname = url.path.split("/", 2)[1] pname = url.path.split("/", 2)[1]

View File

@ -1,6 +1,5 @@
import urllib.request import urllib.request
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from typing import List
from urllib.parse import ParseResult, urlparse from urllib.parse import ParseResult, urlparse
from xml.etree.ElementTree import Element from xml.etree.ElementTree import Element
@ -18,7 +17,7 @@ def version_from_entry(entry: Element) -> Version:
return Version(url.path.split("/")[-1]) return Version(url.path.split("/")[-1])
def fetch_sourcehut_versions(url: ParseResult) -> List[Version]: def fetch_sourcehut_versions(url: ParseResult) -> list[Version]:
if url.netloc != "git.sr.ht": if url.netloc != "git.sr.ht":
return [] return []
parts = url.path.split("/") parts = url.path.split("/")

View File

@ -1,13 +1,12 @@
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum, auto from enum import Enum, auto
from typing import Optional
@dataclass @dataclass
class Version: class Version:
number: str number: str
prerelease: Optional[bool] = None prerelease: bool | None = None
rev: Optional[str] = None rev: str | None = None
class VersionPreference(Enum): class VersionPreference(Enum):

View File

@ -2,7 +2,7 @@
target-version = "py311" target-version = "py311"
line-length = 88 line-length = 88
select = ["E", "F", "I"] select = ["E", "F", "I", "U"]
ignore = [ "E501" ] ignore = [ "E501" ]
[tool.mypy] [tool.mypy]

View File

@ -3,9 +3,9 @@ import shutil
import subprocess import subprocess
import sys import sys
import tempfile import tempfile
from collections.abc import Iterator
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from typing import Iterator, Type
import pytest import pytest
@ -41,5 +41,5 @@ class Helpers:
@pytest.fixture # type: ignore @pytest.fixture # type: ignore
def helpers() -> Type[Helpers]: def helpers() -> type[Helpers]:
return Helpers return Helpers