Skip to content

Commit

Permalink
Python - Run pyupgrade on some Python files
Browse files Browse the repository at this point in the history
  • Loading branch information
Gustry authored and nyalldawson committed Feb 1, 2023
1 parent e583792 commit da8bb1d
Show file tree
Hide file tree
Showing 37 changed files with 284 additions and 324 deletions.
5 changes: 2 additions & 3 deletions scripts/appinfo2ui.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
/***************************************************************************
appinfo2cpp.py
Expand Down Expand Up @@ -35,7 +34,7 @@
t = c.text if not l else "".join([et.tostring(x).decode("utf-8") for x in l])
strings[t] = 1

f = open("linux/org.qgis.qgis.desktop.in", "r")
f = open("linux/org.qgis.qgis.desktop.in")

for r in f.readlines():
r = r.strip()
Expand All @@ -58,6 +57,6 @@
""")

for k in strings:
print("<property><string>{}</string></property>".format(escape(k)))
print(f"<property><string>{escape(k)}</string></property>")

print("</ui>")
1 change: 0 additions & 1 deletion scripts/dump_babel_formats.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
***************************************************************************
Expand Down
29 changes: 14 additions & 15 deletions scripts/generate_test_mask_image.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
***************************************************************************
Expand Down Expand Up @@ -72,46 +71,46 @@ def getControlImagePath(path):

matching_control_images = [x[0] for x in os.walk(control_images_folder) if path in x[0]]
if len(matching_control_images) > 1:
error('Found multiple matching control images for {}'.format(path))
error(f'Found multiple matching control images for {path}')
elif len(matching_control_images) == 0:
error('No matching control images found for {}'.format(path))
error(f'No matching control images found for {path}')

found_control_image_path = matching_control_images[0]

# check for a single matching expected image
images = glob.glob(os.path.join(found_control_image_path, '*.png'))
filtered_images = [i for i in images if not i[-9:] == '_mask.png']
if len(filtered_images) > 1:
error('Found multiple matching control images for {}'.format(path))
error(f'Found multiple matching control images for {path}')
elif len(filtered_images) == 0:
error('No matching control images found for {}'.format(path))
error(f'No matching control images found for {path}')

found_image = filtered_images[0]
print('Found matching control image: {}'.format(found_image))
print(f'Found matching control image: {found_image}')
return found_image


def updateMask(control_image_path, rendered_image_path, mask_image_path):
control_image = imageFromPath(control_image_path)
if not control_image:
error('Could not read control image {}'.format(control_image_path))
error(f'Could not read control image {control_image_path}')

rendered_image = imageFromPath(rendered_image_path)
if not rendered_image:
error('Could not read rendered image {}'.format(rendered_image_path))
error(f'Could not read rendered image {rendered_image_path}')
if not rendered_image.width() == control_image.width() or not rendered_image.height() == control_image.height():
print(('Size mismatch - control image is {}x{}, rendered image is {}x{}'.format(control_image.width(),
control_image.height(),
rendered_image.width(),
rendered_image.height())))
print('Size mismatch - control image is {}x{}, rendered image is {}x{}'.format(control_image.width(),
control_image.height(),
rendered_image.width(),
rendered_image.height()))

max_width = min(rendered_image.width(), control_image.width())
max_height = min(rendered_image.height(), control_image.height())

# read current mask, if it exist
mask_image = imageFromPath(mask_image_path)
if mask_image.isNull():
print('Mask image does not exist, creating {}'.format(mask_image_path))
print(f'Mask image does not exist, creating {mask_image_path}')
mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32)
mask_image.fill(QColor(0, 0, 0))

Expand Down Expand Up @@ -142,9 +141,9 @@ def updateMask(control_image_path, rendered_image_path, mask_image_path):
if mismatch_count:
# update mask
mask_image.save(mask_image_path, "png")
print('Updated {} pixels in {}'.format(mismatch_count, mask_image_path))
print(f'Updated {mismatch_count} pixels in {mask_image_path}')
else:
print('No mismatches in {}'.format(mask_image_path))
print(f'No mismatches in {mask_image_path}')


parser = argparse.ArgumentParser() # OptionParser("usage: %prog control_image rendered_image mask_image")
Expand Down
1 change: 0 additions & 1 deletion scripts/mkuidefaults.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
***************************************************************************
Expand Down
25 changes: 12 additions & 13 deletions scripts/parse_dash_results.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
***************************************************************************
Expand Down Expand Up @@ -69,12 +68,12 @@ def colorDiff(c1, c2):
def imageFromPath(path):
if (path[:8] == 'https://' or path[:7] == 'file://'):
# fetch remote image
print('Fetching remote ({})'.format(path))
print(f'Fetching remote ({path})')
data = urllib.request.urlopen(path).read()
image = QImage()
image.loadFromData(data)
else:
print('Using local ({})'.format(path))
print(f'Using local ({path})')
image = QImage(path)
return image

Expand All @@ -92,7 +91,7 @@ def __init__(self, parent, test_name, images):
self.button_box.rejected.connect(self.reject)

layout = QVBoxLayout()
layout.addWidget(QLabel('Found multiple matching reference images for {}'.format(test_name)))
layout.addWidget(QLabel(f'Found multiple matching reference images for {test_name}'))

self.list = QListWidget()
layout.addWidget(self.list, 1)
Expand Down Expand Up @@ -183,7 +182,7 @@ def closeEvent(self, event):
def parse_url(self, url):
parts = urllib.parse.urlsplit(url)
apiurl = urllib.parse.urlunsplit((parts.scheme, parts.netloc, '/api/v1/testDetails.php', parts.query, parts.fragment))
print('Fetching dash results from api: {}'.format(apiurl))
print(f'Fetching dash results from api: {apiurl}')
page = urllib.request.urlopen(apiurl)
content = json.loads(page.read().decode('utf-8'))

Expand All @@ -195,7 +194,7 @@ def parse_url(self, url):
m = re.search(r'Rendered Image (.*?)(\s|$)', img['role'])
test_name = m.group(1)
rendered_image = 'displayImage.php?imgid={}'.format(img['imgid'])
images[test_name] = '{}/{}'.format(dash_url, rendered_image)
images[test_name] = f'{dash_url}/{rendered_image}'

if images:
print('Found images:\n')
Expand Down Expand Up @@ -226,12 +225,12 @@ def load_next(self):
def load_images(self, control_image_path, rendered_image_path, mask_image_path):
self.control_image = imageFromPath(control_image_path)
if not self.control_image:
error('Could not read control image {}'.format(control_image_path))
error(f'Could not read control image {control_image_path}')

self.rendered_image = imageFromPath(rendered_image_path)
if not self.rendered_image:
error(
'Could not read rendered image {}'.format(rendered_image_path))
f'Could not read rendered image {rendered_image_path}')
if not self.rendered_image.width() == self.control_image.width() or not self.rendered_image.height() == self.control_image.height():
print(
'Size mismatch - control image is {}x{}, rendered image is {}x{}'.format(self.control_image.width(),
Expand All @@ -250,7 +249,7 @@ def load_images(self, control_image_path, rendered_image_path, mask_image_path):
self.mask_image = imageFromPath(mask_image_path)
if self.mask_image.isNull():
print(
'Mask image does not exist, creating {}'.format(mask_image_path))
f'Mask image does not exist, creating {mask_image_path}')
self.mask_image = QImage(
self.control_image.width(), self.control_image.height(), QImage.Format_ARGB32)
self.mask_image.fill(QColor(0, 0, 0))
Expand Down Expand Up @@ -371,7 +370,7 @@ def get_control_image_path(self, test_name):

self.found_control_image_path = dlg.selected_image()
elif len(matching_control_images) == 0:
print(termcolor.colored('No matching control images found for {}'.format(test_name), 'yellow'))
print(termcolor.colored(f'No matching control images found for {test_name}', 'yellow'))
return None
else:
self.found_control_image_path = matching_control_images[0]
Expand All @@ -381,12 +380,12 @@ def get_control_image_path(self, test_name):
filtered_images = [i for i in images if not i[-9:] == '_mask.png']
if len(filtered_images) > 1:
error(
'Found multiple matching control images for {}'.format(test_name))
f'Found multiple matching control images for {test_name}')
elif len(filtered_images) == 0:
error('No matching control images found for {}'.format(test_name))
error(f'No matching control images found for {test_name}')

self.found_image = filtered_images[0]
print('Found matching control image: {}'.format(self.found_image))
print(f'Found matching control image: {self.found_image}')
return self.found_image

def create_diff_image(self, control_image, rendered_image, mask_image):
Expand Down
20 changes: 9 additions & 11 deletions scripts/process_function_template.py
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

import sys
import os
import json
Expand Down Expand Up @@ -55,10 +53,10 @@ def quote(v):

for field in ['name', 'type']:
if field not in json_params:
raise BaseException("%s: %s missing" % (f, field))
raise BaseException(f"{f}: {field} missing")

if not json_params['type'] in ['function', 'operator', 'value', 'expression', 'group']:
raise BaseException("%s: invalid type %s " % (f, json_params['type']))
raise BaseException("{}: invalid type {} ".format(f, json_params['type']))

if 'variants' not in json_params:
# convert single variant shortcut to a expanded variant
Expand All @@ -70,7 +68,7 @@ def quote(v):
v['variant_description'] = json_params['description']
json_params['variants'] = [v]

name = "\"{0}\"".format(json_params['name'])
name = "\"{}\"".format(json_params['name'])

if json_params['type'] == 'operator':
for v in json_params['variants']:
Expand All @@ -86,11 +84,11 @@ def quote(v):

for v in json_params['variants']:
cpp.write(
"\n << HelpVariant( tr( \"{0}\" ), tr( \"{1}\" ),\n QList<HelpArg>()".format(v['variant'], v['variant_description']))
"\n << HelpVariant( tr( \"{}\" ), tr( \"{}\" ),\n QList<HelpArg>()".format(v['variant'], v['variant_description']))

if 'arguments' in v:
for a in v['arguments']:
cpp.write("\n << HelpArg( QStringLiteral( \"{0}\" ), tr( \"{1}\" ), {2}, {3}, {4}, {5} )".format(
cpp.write("\n << HelpArg( QStringLiteral( \"{}\" ), tr( \"{}\" ), {}, {}, {}, {} )".format(
a['arg'],
a.get('description', ''),
"true" if a.get('descOnly', False) else "false",
Expand All @@ -100,26 +98,26 @@ def quote(v):
)
)

cpp.write(",\n /* variableLenArguments */ {0}".format(
cpp.write(",\n /* variableLenArguments */ {}".format(
"true" if v.get('variableLenArguments', False) else "false"))
cpp.write(",\n QList<HelpExample>()")

if 'examples' in v:
for e in v['examples']:
cpp.write("\n << HelpExample( tr( \"{0}\" ), tr( \"{1}\" ), tr( \"{2}\" ) )".format(
cpp.write("\n << HelpExample( tr( \"{}\" ), tr( \"{}\" ), tr( \"{}\" ) )".format(
e['expression'],
e['returns'],
e.get('note', ''))
)

if 'notes' in v:
cpp.write(",\n tr( \"{0}\" )".format(v['notes']))
cpp.write(",\n tr( \"{}\" )".format(v['notes']))
else:
cpp.write(",\n QString()")

cpp.write(",\n QStringList()")
if 'tags' in v:
cpp.write("\n << tr( \"{0}\" )".format(",".join(v['tags'])))
cpp.write("\n << tr( \"{}\" )".format(",".join(v['tags'])))

cpp.write("\n )")

Expand Down
2 changes: 0 additions & 2 deletions scripts/pyuic_wrapper.py
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

"""
***************************************************************************
pyuic_wrapper.py
Expand Down
2 changes: 1 addition & 1 deletion scripts/qgis_fixes/fix_absolute_import.py
Expand Up @@ -8,4 +8,4 @@ def probably_a_local_import(self, imp_name):
return False
if imp_name == "AlgorithmsTestBase":
return False
return super(FixAbsoluteImport, self).probably_a_local_import(imp_name)
return super().probably_a_local_import(imp_name)
2 changes: 1 addition & 1 deletion scripts/qgis_fixes/fix_print_with_import.py
Expand Up @@ -10,7 +10,7 @@ def transform(self, node, results):
if "fix_print_with_import" in node.prefix:
return node

r = super(FixPrintWithImport, self).transform(node, results)
r = super().transform(node, results)

if not r or r == node:
return r
Expand Down
28 changes: 14 additions & 14 deletions scripts/qgis_fixes/fix_pyqt.py
Expand Up @@ -404,30 +404,30 @@ def build_pattern():
else:
dotted = old_module.split('.')
if len(dotted) == 3:
from_name = "dotted_name<%r '.' %r '.' %r>" % (dotted[0], dotted[1], dotted[2])
from_name = f"dotted_name<{dotted[0]!r} '.' {dotted[1]!r} '.' {dotted[2]!r}>"
else:
assert len(dotted) == 2
from_name = "dotted_name<%r '.' %r>" % (dotted[0], dotted[1])
from_name = f"dotted_name<{dotted[0]!r} '.' {dotted[1]!r}>"

yield """import_name< 'import' (module=%s
| dotted_as_names< any* module=%s any* >) >
""" % (from_name, from_name)
yield """import_from< 'from' mod_member=%s 'import'
( member=%s | import_as_name< member=%s 'as' any > |
yield """import_name< 'import' (module={}
| dotted_as_names< any* module={} any* >) >
""".format(from_name, from_name)
yield """import_from< 'from' mod_member={} 'import'
( member={} | import_as_name< member={} 'as' any > |
import_as_names< members=any* >) >
""" % (from_name, members, members)
yield """import_from< 'from' mod_member=%s 'import' '('
( member=%s | import_as_name< member=%s 'as' any > |
""".format(from_name, members, members)
yield """import_from< 'from' mod_member={} 'import' '('
( member={} | import_as_name< member={} 'as' any > |
import_as_names< members=any* >) ')' >
""" % (from_name, members, members)
""".format(from_name, members, members)
yield """import_from< 'from' module_star=%s 'import' star='*' >
""" % from_name
yield """import_name< 'import'
dotted_as_name< module_as=%s 'as' any > >
""" % from_name
# bare_with_attr has a special significance for FixImports.match().
yield """power< bare_with_attr=%s trailer< '.' member=%s > any* >
""" % (from_name, members)
yield """power< bare_with_attr={} trailer< '.' member={} > any* >
""".format(from_name, members)


class FixPyqt(FixImports):
Expand Down Expand Up @@ -517,7 +517,7 @@ def transform_member(self, node, results):
found = True
if not found:
f = open("/tmp/missing", "a+")
f.write("member %s of %s not found\n" % (member_name, mod_member.value))
f.write(f"member {member_name} of {mod_member.value} not found\n")
f.close()
missing = True

Expand Down
3 changes: 1 addition & 2 deletions scripts/qgis_fixes/fix_qfiledialog.py
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Migrate QFileDialog methods from PyQt4 to PyQt5
"""
Expand Down Expand Up @@ -34,7 +33,7 @@ def transform(self, node, results):
# we add __ special variable
if nbLeaves < 3:
fileName = node.value
node.value = '{}, __'.format(fileName)
node.value = f'{fileName}, __'
node.changed()

# Rename *AndFilter methods
Expand Down

0 comments on commit da8bb1d

Please sign in to comment.