Skip to content

Commit 81c39ae

Browse files
committed
Format code with Ruff and run doc8 for documentation validation.
Signed-off-by: Chin Yeung Li <tli@nexb.com>
1 parent 6676be6 commit 81c39ae

File tree

20 files changed

+2998
-2432
lines changed

20 files changed

+2998
-2432
lines changed

docs/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
# -- Project information -----------------------------------------------------
1919

20-
project = 'aboutcode-toolkit'
20+
project = "aboutcode-toolkit"
2121
copyright = "nexB Inc. and others."
2222
author = "AboutCode.org authors and contributors"
2323

src/attributecode/__init__.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020

2121
import saneyaml
2222

23-
__version__ = '11.1.1'
23+
__version__ = "11.1.1"
2424

25-
__about_spec_version__ = '4.0.0'
25+
__about_spec_version__ = "4.0.0"
2626

2727
__copyright__ = """
2828
Copyright (c) nexB Inc. All rights reserved. http://dejacode.org
@@ -38,7 +38,7 @@
3838
"""
3939

4040

41-
class Error(namedtuple('Error', ['severity', 'message'])):
41+
class Error(namedtuple("Error", ["severity", "message"])):
4242
"""
4343
An Error data with a severity and message.
4444
"""
@@ -51,12 +51,11 @@ def __new__(self, severity, message):
5151
message = self._clean_string(repr(message))
5252
message = message.strip('"')
5353

54-
return super(Error, self).__new__(
55-
Error, severity, message)
54+
return super(Error, self).__new__(Error, severity, message)
5655

5756
def __repr__(self, *args, **kwargs):
5857
sev, msg = self._get_values()
59-
return 'Error(%(sev)s, %(msg)s)' % locals()
58+
return "Error(%(sev)s, %(msg)s)" % locals()
6059

6160
def __eq__(self, other):
6261
return repr(self) == repr(other)
@@ -68,7 +67,7 @@ def _get_values(self):
6867

6968
def render(self):
7069
sev, msg = self._get_values()
71-
return '%(sev)s: %(msg)s' % locals()
70+
return "%(sev)s: %(msg)s" % locals()
7271

7372
def to_dict(self, *args, **kwargs):
7473
"""
@@ -85,7 +84,7 @@ def _clean_string(s):
8584
if not s:
8685
return s
8786
if s.startswith(('u"', "u'")):
88-
s = s.lstrip('u')
87+
s = s.lstrip("u")
8988
s = s.replace('[u"', '["')
9089
s = s.replace("[u'", "['")
9190
s = s.replace("(u'", "('")
@@ -107,10 +106,10 @@ def _clean_string(s):
107106
NOTSET = 0
108107

109108
severities = {
110-
CRITICAL: 'CRITICAL',
111-
ERROR: 'ERROR',
112-
WARNING: 'WARNING',
113-
INFO: 'INFO',
114-
DEBUG: 'DEBUG',
115-
NOTSET: 'NOTSET'
109+
CRITICAL: "CRITICAL",
110+
ERROR: "ERROR",
111+
WARNING: "WARNING",
112+
INFO: "INFO",
113+
DEBUG: "DEBUG",
114+
NOTSET: "NOTSET",
116115
}

src/attributecode/__main__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
# limitations under the License.
1515
# ============================================================================
1616

17-
if __name__ == '__main__': # pragma: nocover
17+
if __name__ == "__main__": # pragma: nocover
1818
from attributecode import cmd
19+
1920
cmd.about()

src/attributecode/api.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -36,18 +36,14 @@ def request_license_data(api_url, api_key, license_key):
3636
`license_key`. Send a request to `api_url` authenticating with `api_key`.
3737
"""
3838
headers = {
39-
'Authorization': 'Token %s' % api_key,
40-
}
41-
payload = {
42-
'api_key': api_key,
43-
'key': license_key,
44-
'format': 'json'
39+
"Authorization": "Token %s" % api_key,
4540
}
41+
payload = {"api_key": api_key, "key": license_key, "format": "json"}
4642

47-
api_url = api_url.rstrip('/')
43+
api_url = api_url.rstrip("/")
4844
payload = urlencode(payload)
4945

50-
full_url = '%(api_url)s/?%(payload)s' % locals()
46+
full_url = "%(api_url)s/?%(payload)s" % locals()
5147
# handle special characters in URL such as space etc.
5248
quoted_url = quote(full_url, safe="%/:=&?~#+!$,;'@()*[]")
5349

@@ -58,23 +54,21 @@ def request_license_data(api_url, api_key, license_key):
5854
response_content = response.text
5955
# FIXME: this should be an ordered dict
6056
license_data = json.loads(response_content)
61-
if not license_data.get('results', []):
62-
msg = u"Invalid 'license': %s" % license_key
57+
if not license_data.get("results", []):
58+
msg = "Invalid 'license': %s" % license_key
6359
errors.append(Error(ERROR, msg))
6460
except HTTPError as http_e:
65-
msg = (u"Authorization denied. Invalid '--api_key'. "
66-
u"License generation is skipped.")
61+
msg = "Authorization denied. Invalid '--api_key'. License generation is skipped."
6762
errors.append(Error(ERROR, msg))
6863
except Exception as e:
6964
# Already checked the authorization and accessible of the URL.
7065
# The only exception left is URL is accessible, but it's not a valid API URL
71-
msg = (u"Invalid '--api_url'. "
72-
u"License generation is skipped.")
66+
msg = "Invalid '--api_url'. License generation is skipped."
7367
errors.append(Error(ERROR, msg))
7468

7569
finally:
76-
if license_data.get('count') == 1:
77-
license_data = license_data.get('results')[0]
70+
if license_data.get("count") == 1:
71+
license_data = license_data.get("results")[0]
7872
else:
7973
license_data = {}
8074

src/attributecode/attrib.py

Lines changed: 60 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,19 @@
3030
from attributecode.attrib_util import multi_sort
3131

3232
DEFAULT_TEMPLATE_FILE = os.path.join(
33-
os.path.dirname(os.path.realpath(__file__)), 'templates', 'default_html.template')
33+
os.path.dirname(os.path.realpath(__file__)), "templates", "default_html.template"
34+
)
3435

3536
DEFAULT_TEMPLATE_SCANCODE_FILE = os.path.join(
36-
os.path.dirname(os.path.realpath(__file__)), 'templates', 'scancode_html.template')
37+
os.path.dirname(os.path.realpath(__file__)), "templates", "scancode_html.template"
38+
)
3739

3840
DEFAULT_LICENSE_SCORE = 100
3941

4042

41-
def generate(abouts, is_about_input, license_dict, scancode, min_license_score, template=None, vartext=None):
43+
def generate(
44+
abouts, is_about_input, license_dict, scancode, min_license_score, template=None, vartext=None
45+
):
4246
"""
4347
Generate an attribution text from an `abouts` list of About objects, a
4448
`template` template text and a `vartext` optional dict of extra
@@ -53,9 +57,7 @@ def generate(abouts, is_about_input, license_dict, scancode, min_license_score,
5357
if template_error:
5458
lineno, message = template_error
5559
error = Error(
56-
CRITICAL,
57-
'Template validation error at line: {lineno}: "{message}"'.format(
58-
**locals())
60+
CRITICAL, 'Template validation error at line: {lineno}: "{message}"'.format(**locals())
5961
)
6062
errors.append(error)
6163
return error, None
@@ -87,14 +89,13 @@ def generate(abouts, is_about_input, license_dict, scancode, min_license_score,
8789
filename = list(about.license_file.value.keys())[index]
8890
text = list(about.license_file.value.values())[index]
8991
else:
90-
error = Error(
91-
CRITICAL, 'No license file found for ' + name)
92+
error = Error(CRITICAL, "No license file found for " + name)
9293
errors.append(error)
9394
break
9495
if about.license_url.value:
9596
url = about.license_url.value[index]
9697
else:
97-
url = ''
98+
url = ""
9899
license_object = License(key, name, filename, url, text)
99100
licenses_list.append(license_object)
100101
index = index + 1
@@ -114,7 +115,8 @@ def generate(abouts, is_about_input, license_dict, scancode, min_license_score,
114115
# The process will update the license_key, license_name and license_score.
115116
if scancode:
116117
abouts, meet_score_licenses_list = generate_sctk_input(
117-
abouts, min_license_score, license_dict)
118+
abouts, min_license_score, license_dict
119+
)
118120
# Remove the license object
119121
remove_list = []
120122
for lic in licenses_list:
@@ -126,7 +128,7 @@ def generate(abouts, is_about_input, license_dict, scancode, min_license_score,
126128

127129
for about in abouts:
128130
# Create a license expression with license name
129-
lic_name_expression = ''
131+
lic_name_expression = ""
130132
lic_name_expression_list = []
131133
if about.license_expression.value:
132134
for segment in about.license_expression.value.split():
@@ -139,12 +141,13 @@ def generate(abouts, is_about_input, license_dict, scancode, min_license_score,
139141
if not_lic:
140142
lic_name_expression_list.append(segment)
141143
# Join the license name expression into a single string
142-
lic_name_expression = ' '.join(lic_name_expression_list)
144+
lic_name_expression = " ".join(lic_name_expression_list)
143145

144146
# Add the license name expression string into the about object as a custom field
145147
custom_field = StringField(
146-
name='license_name_expression', value=lic_name_expression, present=True)
147-
setattr(about, 'license_name_expression', custom_field)
148+
name="license_name_expression", value=lic_name_expression, present=True
149+
)
150+
setattr(about, "license_name_expression", custom_field)
148151

149152
# Sort the about objects by name
150153
abouts = sorted(abouts, key=lambda x: x.name.value.lower())
@@ -158,7 +161,7 @@ def generate(abouts, is_about_input, license_dict, scancode, min_license_score,
158161
licenses_list=licenses_list,
159162
utcnow=utcnow,
160163
tkversion=__version__,
161-
vartext=vartext
164+
vartext=vartext,
162165
)
163166

164167
return errors, rendered
@@ -211,13 +214,11 @@ def generate_sctk_input(abouts, min_license_score, license_dict):
211214
previous_score, _name = updated_dict[key]
212215
current_score = lic_score[index]
213216
if current_score > previous_score:
214-
updated_dict[key] = (
215-
lic_score[index], lic_name[index])
217+
updated_dict[key] = (lic_score[index], lic_name[index])
216218
# Track the duplicated index
217219
removed_index.append(index)
218220
else:
219-
updated_dict[key] = (
220-
lic_score[index], lic_name[index])
221+
updated_dict[key] = (lic_score[index], lic_name[index])
221222
updated_lic_key_expression.append(key)
222223
# Remove the duplication
223224
for index, key in enumerate(about.license_key.value):
@@ -231,8 +232,7 @@ def generate_sctk_input(abouts, min_license_score, license_dict):
231232
updated_lic_name = []
232233
updated_lic_score = []
233234
for index, lic in enumerate(updated_dict):
234-
_sp_char, lic_keys, _invalid_lic_exp = parse_license_expression(
235-
lic)
235+
_sp_char, lic_keys, _invalid_lic_exp = parse_license_expression(lic)
236236
score, name = updated_dict[lic]
237237
if score >= min_license_score:
238238
for lic_key in lic_keys:
@@ -259,10 +259,10 @@ def generate_sctk_input(abouts, min_license_score, license_dict):
259259

260260

261261
def get_license_file_key(license_text_name):
262-
if license_text_name.endswith('.LICENSE'):
262+
if license_text_name.endswith(".LICENSE"):
263263
# See https://github.com/aboutcode-org/aboutcode-toolkit/issues/439
264264
# for why using split instead of strip
265-
return license_text_name.rsplit('.', 1)[0]
265+
return license_text_name.rsplit(".", 1)[0]
266266
else:
267267
return license_text_name
268268

@@ -273,13 +273,21 @@ def check_template(template_string):
273273
message) if the template is invalid or None if it is valid.
274274
"""
275275
try:
276-
jinja2.filters.FILTERS['multi_sort'] = multi_sort
276+
jinja2.filters.FILTERS["multi_sort"] = multi_sort
277277
jinja2.Template(template_string)
278278
except (jinja2.TemplateSyntaxError, jinja2.TemplateAssertionError) as e:
279279
return e.lineno, e.message
280280

281281

282-
def generate_from_file(abouts, is_about_input, license_dict, scancode, min_license_score, template_loc=None, vartext=None):
282+
def generate_from_file(
283+
abouts,
284+
is_about_input,
285+
license_dict,
286+
scancode,
287+
min_license_score,
288+
template_loc=None,
289+
vartext=None,
290+
):
283291
"""
284292
Generate an attribution text from an `abouts` list of About objects, a
285293
`template_loc` template file location and a `vartext` optional
@@ -295,12 +303,29 @@ def generate_from_file(abouts, is_about_input, license_dict, scancode, min_licen
295303
template_loc = add_unc(DEFAULT_TEMPLATE_FILE)
296304
else:
297305
template_loc = add_unc(template_loc)
298-
with open(template_loc, encoding='utf-8', errors='replace') as tplf:
306+
with open(template_loc, encoding="utf-8", errors="replace") as tplf:
299307
tpls = tplf.read()
300-
return generate(abouts, is_about_input, license_dict, scancode, min_license_score, template=tpls, vartext=vartext)
308+
return generate(
309+
abouts,
310+
is_about_input,
311+
license_dict,
312+
scancode,
313+
min_license_score,
314+
template=tpls,
315+
vartext=vartext,
316+
)
301317

302318

303-
def generate_and_save(abouts, is_about_input, license_dict, output_location, scancode=False, min_license_score=0, template_loc=None, vartext=None):
319+
def generate_and_save(
320+
abouts,
321+
is_about_input,
322+
license_dict,
323+
output_location,
324+
scancode=False,
325+
min_license_score=0,
326+
template_loc=None,
327+
vartext=None,
328+
):
304329
"""
305330
Generate an attribution text from an `abouts` list of About objects, a
306331
`template_loc` template file location and a `vartext` optional
@@ -314,14 +339,15 @@ def generate_and_save(abouts, is_about_input, license_dict, output_location, sca
314339
if not about.license_expression.value:
315340
continue
316341
special_char_in_expression, lic_list, invalid_lic_exp = parse_license_expression(
317-
about.license_expression.value)
342+
about.license_expression.value
343+
)
318344
if special_char_in_expression or invalid_lic_exp:
319345
if special_char_in_expression:
320-
msg = (u"The following character(s) cannot be in the license_expression: " +
321-
str(special_char_in_expression))
346+
msg = "The following character(s) cannot be in the license_expression: " + str(
347+
special_char_in_expression
348+
)
322349
else:
323-
msg = (u"This license_expression is invalid: " +
324-
str(invalid_lic_exp))
350+
msg = "This license_expression is invalid: " + str(invalid_lic_exp)
325351
errors.append(Error(ERROR, msg))
326352

327353
rendering_error, rendered = generate_from_file(
@@ -339,7 +365,7 @@ def generate_and_save(abouts, is_about_input, license_dict, output_location, sca
339365

340366
if rendered:
341367
output_location = add_unc(output_location)
342-
with open(output_location, 'w', encoding='utf-8', errors='replace') as of:
368+
with open(output_location, "w", encoding="utf-8", errors="replace") as of:
343369
of.write(rendered)
344370

345371
return errors, rendered

0 commit comments

Comments
 (0)