Skip to content

Commit c8451a3

Browse files
committed
fixup(findsources): flake8 and codespell
1 parent 9928df2 commit c8451a3

File tree

1 file changed

+27
-29
lines changed

1 file changed

+27
-29
lines changed

capycli/bom/findsources.py

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -56,35 +56,33 @@ def _validate_key(self, key: Tuple[str, str]) -> Tuple[str, str]:
5656
"""Ensure our keys are hashable."""
5757
if len(key) != 2 or key != (str(key[0]), str(key[1])):
5858
raise KeyError(f'{self.__class__.__name__} key must consist of'
59-
'a project name and a version string')
59+
'a project name and a version string')
6060
return key
6161

62-
def add(self, project: str, version:str , tag: str) -> None:
62+
def add(self, project: str, version: str, tag: str) -> None:
6363
"""Cache a tag for a specific project and version."""
6464
key = self._validate_key((project, version))
6565
tags = self.data.setdefault(key, set())
6666
tags.add(tag)
6767

68-
def filter(self, project: str, version: str, data: Any) ->List[str]:
68+
def filter(self, project: str, version: str, data: Any) -> List[str]:
6969
"""Remove all cached entries from @data."""
7070
if isinstance(data, str):
7171
data = [data]
7272
elif not isinstance(data, Iterable):
73-
raise ValueError('Expecting an interable of tags!')
73+
raise ValueError('Expecting an iterable of tags!')
7474
key = self._validate_key((project, version))
7575
return [item for item in data
76-
if item not in self.data.get(key,[])
76+
if item not in self.data.get(key, [])
7777
and len(item) > 0]
7878

79-
def filter_and_cache(self, project: str, version: str, data: Any
80-
) ->List[str]:
79+
def filter_and_cache(self, project: str, version: str, data: Any) -> List[str]:
8180
"""Convenience method to to filtering and adding in one run."""
8281
candidates = set(self.filter(project, version, data))
8382
for tag in candidates:
8483
self.add(project, version, tag)
8584
return list(candidates)
8685

87-
8886
def __init__(self) -> None:
8987
self.verbose: bool = False
9088
self.version_regex = re.compile(r"(\d+[._])+\d+")
@@ -123,18 +121,19 @@ def is_sourcefile_accessible(self, sourcefile_url: str) -> bool:
123121
def github_request(url: str, username: str = "", token: str = "",
124122
return_response: bool = False,
125123
allow_redirects: bool = True, # default in requests
126-
) -> Any:
124+
) -> Any:
127125
try:
128126
headers = {}
129127
if token:
130128
headers["Authorization"] = "token " + token
131129
if username:
132130
headers["Username"] = username
133-
response = requests.get(url, headers=headers, allow_redirects=allow_redirects)
131+
response = requests.get(url, headers=headers,
132+
allow_redirects=allow_redirects)
134133
if not response.ok:
135134
if response.status_code == 429 \
136-
or 'rate limit exceeded' in response.reason \
137-
or 'API rate limit exceeded' in response.json().get('message', ''):
135+
or 'rate limit exceeded' in response.reason \
136+
or 'API rate limit exceeded' in response.json().get('message', ''):
138137
print(
139138
Fore.LIGHTYELLOW_EX +
140139
" Github API rate limit exceeded - wait 60s and retry ... " +
@@ -222,7 +221,7 @@ def _get_github_repo(self, github_ref: str) -> Dict[str, Any]:
222221
"""
223222
url = 'api.github.com/repos/'
224223
gh_ref = urlparse(github_ref, scheme='no_scheme')
225-
if gh_ref.scheme == 'no_scheme': # interprete @github_ref as OWNER/REPO
224+
if gh_ref.scheme == 'no_scheme': # interpret @github_ref as OWNER/REPO
226225
url += gh_ref.path
227226
elif not gh_ref.netloc.endswith('github.com'):
228227
raise ValueError(f'{github_ref} is not an expected @github_ref!')
@@ -241,7 +240,7 @@ def _get_github_repo(self, github_ref: str) -> Dict[str, Any]:
241240
raise ValueError(f"Unable to make @github_ref {github_ref} work!")
242241
return repo
243242

244-
def _get_link_page(self, res: requests.Response, which: str='next') -> int:
243+
def _get_link_page(self, res: requests.Response, which: str = 'next') -> int:
245244
"""Fetch only page number from link-header."""
246245
try:
247246
url = urlparse(res.links[which]['url'])
@@ -250,8 +249,8 @@ def _get_link_page(self, res: requests.Response, which: str='next') -> int:
250249
return 1
251250

252251
def get_matching_source_url(self, version: Any, github_ref: str,
253-
version_prefix: Any=None
254-
) -> str:
252+
version_prefix: Any = None
253+
) -> str:
255254
"""Find a URL to download source code from GitHub. We are
256255
looking for the source code in @github_ref at @version.
257256
@@ -271,23 +270,23 @@ def get_matching_source_url(self, version: Any, github_ref: str,
271270
print_yellow(" " + str(err))
272271
return ""
273272

274-
tags_url = repo['tags_url'] +'?per_page=100'
273+
tags_url = repo['tags_url'] + '?per_page=100'
275274
git_refs_url_tpl = repo['git_refs_url'].replace('{/sha}', '{sha}', 1)
276275

277276
res = self.github_request(tags_url, self.github_name,
278-
self.github_token, return_response=True)
277+
self.github_token, return_response=True)
279278
pages = self._get_link_page(res, 'last')
280279
for _ in range(pages): # we prefer this over "while True"
281280
# note: in res.json() we already have the first results page
282281
try:
283282
tags = [tag for tag in res.json()
284-
if version_prefix is None \
283+
if version_prefix is None
285284
or tag['name'].startswith(version_prefix)]
286285
source_url = self.get_matching_tag(tags, version, tags_url)
287286
if len(source_url) > 0: # we found what we believe is
288287
return source_url # the correct source_url
289288

290-
except (TypeError, KeyError, AttributeError) as err:
289+
except (TypeError, KeyError, AttributeError):
291290
# res.json() did not give us an iterable of things where
292291
# 'name' is a viable index, for instance an error message
293292
tags = []
@@ -307,23 +306,23 @@ def get_matching_source_url(self, version: Any, github_ref: str,
307306

308307
# ORDER BY tag-name-length DESC
309308
by_size = sorted([(len(tag['ref']), tag) for tag in w_prefix],
310-
key=lambda x:x[0])
309+
key=lambda x: x[0])
311310
w_prefix = [itm[1] for itm in reversed(by_size)]
312311

313-
transformed_for_get_matching_tags = [{
314-
'name': tag['ref'].replace('refs/tags/', '', 1),
315-
'zipball_url': tag['url'].replace(
312+
transformed_for_get_matching_tags = [
313+
{'name': tag['ref'].replace('refs/tags/', '', 1),
314+
'zipball_url': tag['url'].replace(
316315
'/git/refs/tags/', '/zipball/refs/tags/', 1),
317-
} for tag in w_prefix]
316+
} for tag in w_prefix]
318317
source_url = self.get_matching_tag(
319318
transformed_for_get_matching_tags, version, tags_url)
320319
if len(source_url) > 0: # we found what we believe is
321320
return source_url # the correct source_url
322321
try:
323322
url = res.links['next']['url']
324323
res = self.github_request(url, self.github_name,
325-
self.github_token, return_response=True)
326-
except KeyError as err: # no more result pages
324+
self.github_token, return_response=True)
325+
except KeyError: # no more result pages
327326
break
328327
print_yellow(" No matching tag for version " + version + " found")
329328
return ""
@@ -364,7 +363,6 @@ def find_github_url(self, component: Component, use_language: bool = True) -> st
364363
name_match = [r for r in repositories.get("items") if component_name in r.get("name", "")]
365364
if len(name_match):
366365
for match in name_match:
367-
tag_info = self.github_request(match["tags_url"], self.github_name, self.github_token)
368366
source_url = self.get_matching_source_url(component.version, match["tags_url"])
369367
if len(name_match) == 1:
370368
return source_url
@@ -457,7 +455,7 @@ def get_github_source_url(self, github_url: str, version: str) -> str:
457455
def check_for_github_error(self, tag_info: get_github_info_type) -> List[Dict[str, Any]]:
458456
"""This method was introduced to check the output of
459457
get_github_info() for errors.
460-
Removed, becasue get_github_info was removed.
458+
Removed, because get_github_info was removed.
461459
"""
462460
raise NotImplementedError(
463461
"Removed with introduction of get_matchting_source_tag!")

0 commit comments

Comments
 (0)