Skip to content

Commit aae1a28

Browse files
pombredanneJonoYang
authored andcommitted
Apply small code updates
Signed-off-by: Philippe Ombredanne <pombredanne@nexb.com>
1 parent 529d516 commit aae1a28

File tree

2 files changed

+37
-31
lines changed

2 files changed

+37
-31
lines changed

etc/scripts/utils_requirements.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -57,21 +57,25 @@ def get_required_name_version(requirement, with_unpinned=False):
5757
>>> assert get_required_name_version("fooA==1.2.3.DEV1") == ("fooa", "1.2.3.dev1")
5858
>>> assert get_required_name_version("foo==1.2.3", with_unpinned=False) == ("foo", "1.2.3")
5959
>>> assert get_required_name_version("foo", with_unpinned=True) == ("foo", "")
60-
>>> assert get_required_name_version("foo>=1.2", with_unpinned=True) == ("foo", ""), get_required_name_version("foo>=1.2")
60+
>>> expected = ("foo", ""), get_required_name_version("foo>=1.2")
61+
>>> assert get_required_name_version("foo>=1.2", with_unpinned=True) == expected
6162
>>> try:
6263
... assert not get_required_name_version("foo", with_unpinned=False)
6364
... except Exception as e:
6465
... assert "Requirement version must be pinned" in str(e)
6566
"""
6667
requirement = requirement and "".join(requirement.lower().split())
67-
assert requirement, f"specifier is required is empty:{requirement!r}"
68+
if not requirement:
69+
raise ValueError(f"specifier is required is empty:{requirement!r}")
6870
name, operator, version = split_req(requirement)
69-
assert name, f"Name is required: {requirement}"
71+
if not name:
72+
raise ValueError(f"Name is required: {requirement}")
7073
is_pinned = operator == "=="
7174
if with_unpinned:
7275
version = ""
7376
else:
74-
assert is_pinned and version, f"Requirement version must be pinned: {requirement}"
77+
if not is_pinned and version:
78+
raise ValueError(f"Requirement version must be pinned: {requirement}")
7579
return name, version
7680

7781

@@ -120,7 +124,7 @@ def get_installed_reqs(site_packages_dir):
120124
# setuptools, pip
121125
args = ["pip", "freeze", "--exclude-editable",
122126
"--all", "--path", site_packages_dir]
123-
return subprocess.check_output(args, encoding="utf-8")
127+
return subprocess.check_output(args, encoding="utf-8") # noqa: S603
124128

125129

126130
comparators = (
@@ -150,9 +154,11 @@ def split_req(req):
150154
>>> assert split_req("foo >= 1.2.3 ") == ("foo", ">=", "1.2.3"), split_req("foo >= 1.2.3 ")
151155
>>> assert split_req("foo>=1.2") == ("foo", ">=", "1.2"), split_req("foo>=1.2")
152156
"""
153-
assert req
157+
if not req:
158+
raise ValueError("req is required")
154159
# do not allow multiple constraints and tags
155-
assert not any(c in req for c in ",;")
160+
if not any(c in req for c in ",;"):
161+
raise Exception(f"complex requirements with : or ; not supported: {req}")
156162
req = "".join(req.split())
157163
if not any(c in req for c in comparators):
158164
return req, "", ""

etc/scripts/utils_thirdparty.py

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
32
#
43
# Copyright (c) nexB Inc. and others. All rights reserved.
54
# ScanCode is a trademark of nexB Inc.
@@ -559,7 +558,8 @@ def download(self, dest_dir=THIRDPARTY_DIR):
559558
Download this distribution into `dest_dir` directory.
560559
Return the fetched filename.
561560
"""
562-
assert self.filename
561+
if not self.filename:
562+
raise ValueError(f"self.filename has no value but is required: {self.filename!r}")
563563
if TRACE_DEEP:
564564
print(
565565
f"Fetching distribution of {self.name}=={self.version}:",
@@ -829,10 +829,9 @@ def fetch_license_files(self, dest_dir=THIRDPARTY_DIR, use_cached_index=False):
829829
urls = LinksRepository.from_url(
830830
use_cached_index=use_cached_index).links
831831
errors = []
832-
extra_lic_names = [l.get("file")
833-
for l in self.extra_data.get("licenses", {})]
832+
extra_lic_names = [lic.get("file") for lic in self.extra_data.get("licenses", {})]
834833
extra_lic_names += [self.extra_data.get("license_file")]
835-
extra_lic_names = [ln for ln in extra_lic_names if ln]
834+
extra_lic_names = [eln for eln in extra_lic_names if eln]
836835
lic_names = [f"{key}.LICENSE" for key in self.get_license_keys()]
837836
for filename in lic_names + extra_lic_names:
838837
floc = os.path.join(dest_dir, filename)
@@ -853,7 +852,7 @@ def fetch_license_files(self, dest_dir=THIRDPARTY_DIR, use_cached_index=False):
853852
if TRACE:
854853
print(f"Fetched license from remote: {lic_url}")
855854

856-
except:
855+
except Exception:
857856
try:
858857
# try licensedb second
859858
lic_url = f"{LICENSEDB_API_URL}/{filename}"
@@ -866,8 +865,9 @@ def fetch_license_files(self, dest_dir=THIRDPARTY_DIR, use_cached_index=False):
866865
if TRACE:
867866
print(f"Fetched license from licensedb: {lic_url}")
868867

869-
except:
870-
msg = f'No text for license {filename} in expression "{self.license_expression}" from {self}'
868+
except Exception:
869+
msg = f"No text for license {filename} in expression "
870+
f"{self.license_expression!r} from {self}"
871871
print(msg)
872872
errors.append(msg)
873873

@@ -1009,7 +1009,7 @@ def get_license_link_for_filename(filename, urls):
10091009
exception if no link is found or if there are more than one link for that
10101010
file name.
10111011
"""
1012-
path_or_url = [l for l in urls if l.endswith(f"/{filename}")]
1012+
path_or_url = [url for url in urls if url.endswith(f"/{filename}")]
10131013
if not path_or_url:
10141014
raise Exception(f"Missing link to file: {filename}")
10151015
if not len(path_or_url) == 1:
@@ -1140,7 +1140,6 @@ def to_filename(self):
11401140

11411141
@attr.attributes
11421142
class Wheel(Distribution):
1143-
11441143
"""
11451144
Represents a wheel file.
11461145
@@ -1301,7 +1300,7 @@ def is_pure(self):
13011300
def is_pure_wheel(filename):
13021301
try:
13031302
return Wheel.from_filename(filename).is_pure()
1304-
except:
1303+
except Exception:
13051304
return False
13061305

13071306

@@ -1489,8 +1488,7 @@ def dists_from_paths_or_urls(cls, paths_or_urls):
14891488
)
14901489
except InvalidDistributionFilename:
14911490
if TRACE_DEEP:
1492-
print(
1493-
f" Skipping invalid distribution from: {path_or_url}")
1491+
print(f" Skipping invalid distribution from: {path_or_url}")
14941492
continue
14951493
return dists
14961494

@@ -1500,8 +1498,7 @@ def get_distributions(self):
15001498
"""
15011499
if self.sdist:
15021500
yield self.sdist
1503-
for wheel in self.wheels:
1504-
yield wheel
1501+
yield from self.wheels
15051502

15061503
def get_url_for_filename(self, filename):
15071504
"""
@@ -1632,7 +1629,8 @@ class PypiSimpleRepository:
16321629
type=dict,
16331630
default=attr.Factory(lambda: defaultdict(dict)),
16341631
metadata=dict(
1635-
help="Mapping of {name: {version: PypiPackage, version: PypiPackage, etc} available in this repo"
1632+
help="Mapping of {name: {version: PypiPackage, version: PypiPackage, etc} "
1633+
"available in this repo"
16361634
),
16371635
)
16381636

@@ -1647,7 +1645,8 @@ class PypiSimpleRepository:
16471645
type=bool,
16481646
default=False,
16491647
metadata=dict(
1650-
help="If True, use any existing on-disk cached PyPI index files. Otherwise, fetch and cache."
1648+
help="If True, use any existing on-disk cached PyPI index files. "
1649+
"Otherwise, fetch and cache."
16511650
),
16521651
)
16531652

@@ -1656,7 +1655,8 @@ def _get_package_versions_map(self, name):
16561655
Return a mapping of all available PypiPackage version for this package name.
16571656
The mapping may be empty. It is ordered by version from oldest to newest
16581657
"""
1659-
assert name
1658+
if not name:
1659+
raise ValueError(f"name is required: {name!r}")
16601660
normalized_name = NameVer.normalize_name(name)
16611661
versions = self.packages[normalized_name]
16621662
if not versions and normalized_name not in self.fetched_package_normalized_names:
@@ -1713,7 +1713,7 @@ def fetch_links(self, normalized_name):
17131713
)
17141714
links = collect_urls(text)
17151715
# TODO: keep sha256
1716-
links = [l.partition("#sha256=") for l in links]
1716+
links = [link.partition("#sha256=") for link in links]
17171717
links = [url for url, _, _sha256 in links]
17181718
return links
17191719

@@ -1936,7 +1936,7 @@ def get_remote_file_content(
19361936
# several redirects and that we can ignore content there. A HEAD request may
19371937
# not get us this last header
19381938
print(f" DOWNLOADING: {url}")
1939-
with requests.get(url, allow_redirects=True, stream=True, headers=headers) as response:
1939+
with requests.get(url, allow_redirects=True, stream=True, headers=headers) as response: # noqa: S113
19401940
status = response.status_code
19411941
if status != requests.codes.ok: # NOQA
19421942
if status == 429 and _delay < 20:
@@ -2161,7 +2161,7 @@ def call(args, verbose=TRACE):
21612161
"""
21622162
if TRACE_DEEP:
21632163
print("Calling:", " ".join(args))
2164-
with subprocess.Popen(
2164+
with subprocess.Popen( # noqa: S603
21652165
args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8"
21662166
) as process:
21672167

@@ -2227,7 +2227,7 @@ def download_wheels_with_pip(
22272227
cli_args.extend(["--requirement", req_file])
22282228

22292229
if TRACE:
2230-
print(f"Downloading wheels using command:", " ".join(cli_args))
2230+
print("Downloading wheels using command:", " ".join(cli_args))
22312231

22322232
existing = set(os.listdir(dest_dir))
22332233
error = False
@@ -2260,7 +2260,7 @@ def download_wheels_with_pip(
22602260

22612261
def check_about(dest_dir=THIRDPARTY_DIR):
22622262
try:
2263-
subprocess.check_output(f"venv/bin/about check {dest_dir}".split())
2263+
subprocess.check_output(f"venv/bin/about check {dest_dir}".split()) # noqa: S603
22642264
except subprocess.CalledProcessError as cpe:
22652265
print()
22662266
print("Invalid ABOUT files:")
@@ -2312,5 +2312,5 @@ def get_license_expression(declared_licenses):
23122312
return get_only_expression_from_extracted_license(declared_licenses)
23132313
except ImportError:
23142314
# Scancode is not installed, clean and join all the licenses
2315-
lics = [python_safe_name(l).lower() for l in declared_licenses]
2315+
lics = [python_safe_name(lic).lower() for lic in declared_licenses]
23162316
return " AND ".join(lics).lower()

0 commit comments

Comments
 (0)