Skip to content

Commit 7bf6549

Browse files
authored
Merge pull request #318 from Mic92/ruff-fixes
automatic ruff fixes
2 parents c2f4539 + b524356 commit 7bf6549

24 files changed

+109
-100
lines changed

nix_update/__init__.py

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import shutil
55
import sys
66
import tempfile
7+
from pathlib import Path
78
from typing import NoReturn
89

910
from .eval import CargoLockInSource, Package, eval_attr
@@ -20,8 +21,8 @@ def die(msg: str) -> NoReturn:
2021

2122
def parse_args(args: list[str]) -> Options:
2223
parser = argparse.ArgumentParser()
23-
help = "File to import rather than default.nix. Examples, ./release.nix"
24-
parser.add_argument("-f", "--file", default="./.", help=help)
24+
help_msg = "File to import rather than default.nix. Examples, ./release.nix"
25+
parser.add_argument("-f", "--file", default="./.", help=help_msg)
2526
parser.add_argument(
2627
"-F", "--flake", action="store_true", help="Update a flake attribute instead"
2728
)
@@ -94,7 +95,7 @@ def parse_args(args: list[str]) -> Options:
9495
parser.add_argument(
9596
"attribute",
9697
default=default_attribute,
97-
nargs="?" if default_attribute else None, # type: ignore
98+
nargs="?" if default_attribute else None, # type: ignore[arg-type]
9899
help="""Attribute name within the file evaluated (defaults to environment variable "UPDATE_NIX_ATTR_PATH")""",
99100
)
100101
parser.add_argument(
@@ -151,18 +152,19 @@ def nix_shell(options: Options) -> None:
151152
"nix",
152153
"shell",
153154
f"{options.import_path}#{options.attribute}",
154-
]
155-
+ options.extra_flags,
155+
*options.extra_flags,
156+
],
156157
stdout=None,
157158
check=False,
158159
)
159160
else:
160161
expr = f"let pkgs = import {options.escaped_import_path} {{}}; in pkgs.mkShell {{ buildInputs = [ pkgs.{options.escaped_attribute} ]; }}"
161162
with tempfile.TemporaryDirectory() as d:
162-
path = os.path.join(d, "default.nix")
163-
with open(path, "w") as f:
164-
f.write(expr)
165-
run(["nix-shell", path] + options.extra_flags, stdout=None, check=False)
163+
path = Path(d) / "default.nix"
164+
path.write_text(expr)
165+
run(
166+
["nix-shell", str(path), *options.extra_flags], stdout=None, check=False
167+
)
166168

167169

168170
def git_has_diff(git_dir: str, package: Package) -> bool:
@@ -197,17 +199,33 @@ def git_commit(git_dir: str, package: Package) -> None:
197199
or (new_version.rev and new_version.rev != package.rev)
198200
):
199201
run(
200-
["git", "-C", git_dir, "commit", "--verbose", "--message", msg]
201-
+ files_changed,
202+
[
203+
"git",
204+
"-C",
205+
git_dir,
206+
"commit",
207+
"--verbose",
208+
"--message",
209+
msg,
210+
*files_changed,
211+
],
202212
stdout=None,
203213
)
204214
else:
205215
with tempfile.NamedTemporaryFile(mode="w") as f:
206216
f.write(msg)
207217
f.flush()
208218
run(
209-
["git", "-C", git_dir, "commit", "--verbose", "--template", f.name]
210-
+ files_changed,
219+
[
220+
"git",
221+
"-C",
222+
git_dir,
223+
"commit",
224+
"--verbose",
225+
"--template",
226+
f.name,
227+
*files_changed,
228+
],
211229
stdout=None,
212230
)
213231

@@ -244,11 +262,7 @@ def validate_git_dir(import_path: str) -> str:
244262

245263

246264
def nix_run(options: Options) -> None:
247-
cmd = [
248-
"nix",
249-
"shell",
250-
"-L",
251-
] + options.extra_flags
265+
cmd = ["nix", "shell", "-L", *options.extra_flags]
252266

253267
if options.flake:
254268
cmd.append(f"{options.import_path}#{options.attribute}")
@@ -265,16 +279,11 @@ def nix_build_tool() -> str:
265279
"Return `nom` if found in $PATH"
266280
if shutil.which("nom"):
267281
return "nom"
268-
else:
269-
return "nix"
282+
return "nix"
270283

271284

272285
def nix_build(options: Options) -> None:
273-
cmd = [
274-
nix_build_tool(),
275-
"build",
276-
"-L",
277-
] + options.extra_flags
286+
cmd = [nix_build_tool(), "build", "-L", *options.extra_flags]
278287
if options.flake:
279288
cmd.append(f"{options.import_path}#{options.attribute}")
280289
else:
@@ -286,7 +295,7 @@ def nix_test(opts: Options, package: Package) -> None:
286295
if not package.tests:
287296
die(f"Package '{package.name}' does not define any tests")
288297

289-
cmd = [nix_build_tool(), "build", "-L"] + opts.extra_flags
298+
cmd = [nix_build_tool(), "build", "-L", *opts.extra_flags]
290299

291300
if opts.flake:
292301
for t in package.tests:

nix_update/eval.py

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,9 @@ def __post_init__(
9393

9494
if raw_cargo_lock is None:
9595
self.cargo_lock = NoCargoLock()
96-
elif raw_cargo_lock is False:
97-
self.cargo_lock = CargoLockInStore()
98-
elif not os.path.realpath(raw_cargo_lock).startswith(import_path):
96+
elif raw_cargo_lock is False or not os.path.realpath(raw_cargo_lock).startswith(
97+
import_path
98+
):
9999
self.cargo_lock = CargoLockInStore()
100100
else:
101101
self.cargo_lock = CargoLockInSource(raw_cargo_lock)
@@ -217,14 +217,7 @@ def eval_attr(opts: Options) -> Package:
217217
opts.system,
218218
opts.override_filename,
219219
)
220-
cmd = [
221-
"nix",
222-
"eval",
223-
"--json",
224-
"--impure",
225-
"--expr",
226-
expr,
227-
] + opts.extra_flags
220+
cmd = ["nix", "eval", "--json", "--impure", "--expr", expr, *opts.extra_flags]
228221
res = run(cmd)
229222
out = json.loads(res.stdout)
230223
if opts.override_filename is not None:
@@ -233,8 +226,7 @@ def eval_attr(opts: Options) -> Package:
233226
out["url"] = opts.url
234227
package = Package(attribute=opts.attribute, import_path=opts.import_path, **out)
235228
if opts.version_preference != VersionPreference.SKIP and package.old_version == "":
236-
raise UpdateError(
237-
f"Nix's builtins.parseDrvName could not parse the version from {package.name}"
238-
)
229+
msg = f"Nix's builtins.parseDrvName could not parse the version from {package.name}"
230+
raise UpdateError(msg)
239231

240232
return package

nix_update/update.py

Lines changed: 17 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,9 @@ def to_sri(hashstr: str) -> str:
6969
elif length == 40:
7070
# could be also base32 == 32, but we ignore this case and hope no one is using it
7171
prefix = "sha1:"
72-
elif length == 64 or length == 52:
72+
elif length in (64, 52):
7373
prefix = "sha256:"
74-
elif length == 103 or length == 128:
74+
elif length in (103, 128):
7575
prefix = "sha512:"
7676
else:
7777
return hashstr
@@ -120,8 +120,8 @@ def nix_prefetch(opts: Options, attr: str) -> str:
120120
"nix-build",
121121
"--expr",
122122
f'let src = {expr}; in (src.overrideAttrs or (f: src // f src)) (_: {{ outputHash = ""; outputHashAlgo = "sha256"; }})',
123-
]
124-
+ opts.extra_flags,
123+
*opts.extra_flags,
124+
],
125125
extra_env=extra_env,
126126
stderr=subprocess.PIPE,
127127
check=False,
@@ -139,11 +139,9 @@ def nix_prefetch(opts: Options, attr: str) -> str:
139139

140140
if got == "":
141141
print(stderr, file=sys.stderr)
142-
raise UpdateError(
143-
f"failed to retrieve hash when trying to update {opts.attribute}.{attr}"
144-
)
145-
else:
146-
return got
142+
msg = f"failed to retrieve hash when trying to update {opts.attribute}.{attr}"
143+
raise UpdateError(msg)
144+
return got
147145

148146

149147
def disable_check_meta(opts: Options) -> str:
@@ -196,19 +194,9 @@ def update_cargo_lock(
196194
"--impure",
197195
"--print-out-paths",
198196
"--expr",
199-
f"""
200-
{get_package(opts)}.overrideAttrs (old: {{
201-
cargoDeps = null;
202-
postUnpack = ''
203-
cp -r "$sourceRoot/${{old.cargoRoot or "."}}/Cargo.lock" $out
204-
exit
205-
'';
206-
outputs = [ "out" ];
207-
separateDebugInfo = false;
208-
}})
209-
""",
210-
]
211-
+ opts.extra_flags,
197+
f'\n{get_package(opts)}.overrideAttrs (old: {{\n cargoDeps = null;\n postUnpack = \'\'\n cp -r "$sourceRoot/${{old.cargoRoot or "."}}/Cargo.lock" $out\n exit\n \'\';\n outputs = [ "out" ];\n separateDebugInfo = false;\n}})\n',
198+
*opts.extra_flags,
199+
],
212200
)
213201
src = Path(res.stdout.strip())
214202
if not src.is_file():
@@ -249,7 +237,7 @@ def update_cargo_lock(
249237
for line in f:
250238
print(line, end="")
251239
return
252-
elif match := expanded.fullmatch(line):
240+
if match := expanded.fullmatch(line):
253241
indent = match[1]
254242
path = match[2]
255243
print(line, end="")
@@ -335,8 +323,8 @@ def disable_copystat():
335323
"--print-out-paths",
336324
"--expr",
337325
getSrcAndBin,
338-
]
339-
+ opts.extra_flags,
326+
*opts.extra_flags,
327+
],
340328
)
341329
src = Path(res.stdout.strip())
342330

@@ -347,7 +335,7 @@ def disable_copystat():
347335
bin_path = (src / "nix-support" / f"{bin_name}-bin").read_text().rstrip("\n")
348336

349337
run(
350-
[bin_path] + cmd,
338+
[bin_path, *cmd],
351339
cwd=tempdir,
352340
)
353341

@@ -421,7 +409,8 @@ def update_version(
421409
new_version = Version(version)
422410
else:
423411
if not package.parsed_url:
424-
raise UpdateError("Could not find a url in the derivations src attribute")
412+
msg = "Could not find a url in the derivations src attribute"
413+
raise UpdateError(msg)
425414

426415
version_prefix = ""
427416
if preference != VersionPreference.BRANCH:
@@ -568,9 +557,7 @@ def update(opts: Options) -> Package:
568557
if package.mix_deps:
569558
update_mix_deps_hash(opts, package.filename, package.mix_deps)
570559

571-
if isinstance(package.cargo_lock, CargoLockInSource) or isinstance(
572-
package.cargo_lock, CargoLockInStore
573-
):
560+
if isinstance(package.cargo_lock, CargoLockInSource | CargoLockInStore):
574561
if opts.generate_lockfile:
575562
generate_lockfile(opts, package.filename, "cargo")
576563
else:

nix_update/utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,10 @@ def run(
3030
stdout: None | int | IO[Any] = subprocess.PIPE,
3131
stderr: None | int | IO[Any] = None,
3232
check: bool = True,
33-
extra_env: dict[str, str] = {},
33+
extra_env: dict[str, str] | None = None,
3434
) -> "subprocess.CompletedProcess[str]":
35+
if extra_env is None:
36+
extra_env = {}
3537
info("$ " + shlex.join(command))
3638
env = os.environ.copy()
3739
env.update(extra_env)

nix_update/version/__init__.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
from typing import Protocol
55
from urllib.parse import ParseResult
66

7-
from ..errors import VersionError
7+
from nix_update.errors import VersionError
8+
89
from .bitbucket import fetch_bitbucket_snapshots, fetch_bitbucket_versions
910
from .crate import fetch_crate_versions
1011
from .gitea import fetch_gitea_snapshots, fetch_gitea_versions
@@ -131,10 +132,8 @@ def fetch_latest_version(
131132
)
132133

133134
if unstable:
134-
raise VersionError(
135-
f"Found an unstable version {unstable[0]}, which is being ignored. To update to unstable version, please use '--version=unstable'"
136-
)
135+
msg = f"Found an unstable version {unstable[0]}, which is being ignored. To update to unstable version, please use '--version=unstable'"
136+
raise VersionError(msg)
137137

138-
raise VersionError(
139-
"Please specify the version. We can only get the latest version from codeberg/crates.io/gitea/github/gitlab/pypi/savannah/sourcehut/rubygems/npm projects right now"
140-
)
138+
msg = "Please specify the version. We can only get the latest version from codeberg/crates.io/gitea/github/gitlab/pypi/savannah/sourcehut/rubygems/npm projects right now"
139+
raise VersionError(msg)

nix_update/version/crate.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import urllib.request
33
from urllib.parse import ParseResult
44

5-
from ..utils import info
5+
from nix_update.utils import info
6+
67
from .version import Version
78

89

nix_update/version/github.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,16 @@
44
from urllib.parse import ParseResult, unquote, urlparse
55
from xml.etree.ElementTree import Element
66

7-
from ..errors import VersionError
8-
from ..utils import info
7+
from nix_update.errors import VersionError
8+
from nix_update.utils import info
9+
910
from .version import Version
1011

1112

1213
def version_from_entry(entry: Element) -> Version:
1314
if entry is None:
14-
raise VersionError("No release found")
15+
msg = "No release found"
16+
raise VersionError(msg)
1517
link = entry.find("{http://www.w3.org/2005/Atom}link")
1618
assert link is not None
1719
href = link.attrib["href"]

nix_update/version/gitlab.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
from datetime import datetime
55
from urllib.parse import ParseResult, quote_plus
66

7-
from ..errors import VersionError
8-
from ..utils import info
7+
from nix_update.errors import VersionError
8+
from nix_update.utils import info
9+
910
from .version import Version
1011

1112
GITLAB_API = re.compile(
@@ -24,7 +25,8 @@ def fetch_gitlab_versions(url: ParseResult) -> list[Version]:
2425
resp = urllib.request.urlopen(gitlab_url)
2526
json_tags = json.loads(resp.read())
2627
if len(json_tags) == 0:
27-
raise VersionError("No git tags found")
28+
msg = "No git tags found"
29+
raise VersionError(msg)
2830
releases = []
2931
tags = []
3032
for tag in json_tags:

nix_update/version/npm.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import urllib.request
33
from urllib.parse import ParseResult
44

5-
from ..utils import info
5+
from nix_update.utils import info
6+
67
from .version import Version
78

89

nix_update/version/pypi.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import urllib.request
33
from urllib.parse import ParseResult
44

5-
from ..utils import info
5+
from nix_update.utils import info
6+
67
from .version import Version
78

89

0 commit comments

Comments
 (0)