chore: Upgrade Python syntax with pyupgrade

Run with the following pre-commit configuration:

```
repos:
  - repo: https://github.com/asottile/pyupgrade
    rev: v3.1.0
    hooks:
      - id: pyupgrade
        args: [ "--py3-plus", "--py36-plus", "--py37-plus" ]
```

The rationale for every change can be found at https://github.com/asottile/pyupgrade
This commit is contained in:
Sondre Lillebø Gundersen authored and David Wobrock committed 2022-11-03 22:00:00 +01:00
1 parent 92eab3c929
commit bd4eb89b8c
29 files changed
+32 -65

No files matched your search

+3 -3
View File
@@ -6,20 +6,20 @@ class Cache(dict):
def __init__(self, django_folder, database, cache_path):
self.filename = os.path.join(
cache_path,
"{0}_{1}.pickle".format(django_folder.replace(os.sep, "_"), database),
"{}_{}.pickle".format(django_folder.replace(os.sep, "_"), database),
)
if not os.path.exists(os.path.dirname(self.filename)):
os.makedirs(os.path.dirname(self.filename))
super(Cache, self).__init__()
super().__init__()
def load(self):
try:
with open(self.filename, "rb") as f:
tmp_dict = pickle.load(f)
self.update(tmp_dict)
except IOError:
except OSError:
pass
def save(self):
@@ -19,7 +19,7 @@ from ..utils import (
CONFIG_NAME = "django_migration_linter"
PYPROJECT_TOML = "pyproject.toml"
DEFAULT_CONFIG_FILES = (
".{}.cfg".format(CONFIG_NAME),
f".{CONFIG_NAME}.cfg",
"setup.cfg",
"tox.ini",
)
@@ -34,7 +34,7 @@ class Command(MakeMigrationsCommand):
help = "Creates new migration(s) for apps and lints them."
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
super().add_arguments(parser)
parser.add_argument(
"--lint",
action="store_true",
@@ -49,10 +49,10 @@ class Command(MakeMigrationsCommand):
self.warnings_as_errors = options["warnings_as_errors"]
self.sql_analyser = options["sql_analyser"]
configure_logging(options["verbosity"])
return super(Command, self).handle(*app_labels, **options)
return super().handle(*app_labels, **options)
def write_migration_files(self, changes):
super(Command, self).write_migration_files(changes)
super().write_migration_files(changes)
if (
not getattr(settings, "MIGRATION_LINTER_OVERRIDE_MAKEMIGRATIONS", False)
+16 -16
View File
@@ -36,7 +36,7 @@ class MessageType(Enum):
return list(map(lambda c: c.value, MessageType))
class MigrationLinter(object):
class MigrationLinter:
def __init__(
self,
path=None,
@@ -263,17 +263,17 @@ class MigrationLinter(object):
if lint_result.value in self.quiet:
return
if not self.no_output:
print("({0}, {1})... {2}".format(app_label, migration_name, msg))
print(f"({app_label}, {migration_name})... {msg}")
def print_errors(self, errors):
if MessageType.ERROR.value in self.quiet:
return
for err in errors:
error_str = "\t{0}".format(err["msg"])
error_str = "\t{}".format(err["msg"])
if err.get("table"):
error_str += " (table: {0}".format(err["table"])
error_str += " (table: {}".format(err["table"])
if err.get("column"):
error_str += ", column: {0}".format(err["column"])
error_str += ", column: {}".format(err["column"])
error_str += ")"
if not self.no_output:
print(error_str)
@@ -291,10 +291,10 @@ class MigrationLinter(object):
if self.no_output:
return
print("*** Summary ***")
print("Valid migrations: {}/{}".format(self.nb_valid, self.nb_total))
print("Erroneous migrations: {}/{}".format(self.nb_erroneous, self.nb_total))
print("Migrations with warnings: {}/{}".format(self.nb_warnings, self.nb_total))
print("Ignored migrations: {}/{}".format(self.nb_ignored, self.nb_total))
print(f"Valid migrations: {self.nb_valid}/{self.nb_total}")
print(f"Erroneous migrations: {self.nb_erroneous}/{self.nb_total}")
print(f"Migrations with warnings: {self.nb_warnings}/{self.nb_total}")
print(f"Ignored migrations: {self.nb_ignored}/{self.nb_total}")
@property
def has_errors(self):
@@ -302,7 +302,7 @@ class MigrationLinter(object):
def get_sql(self, app_label, migration_name):
logger.info(
"Calling sqlmigrate command {} {}".format(app_label, migration_name)
f"Calling sqlmigrate command {app_label} {migration_name}"
)
dev_null = open(os.devnull, "w")
try:
@@ -327,7 +327,7 @@ class MigrationLinter(object):
from django.db.migrations.loader import MIGRATIONS_MODULE_NAME
return (
re.search(r"/{0}/.*\.py".format(MIGRATIONS_MODULE_NAME), filename)
re.search(fr"/{MIGRATIONS_MODULE_NAME}/.*\.py", filename)
and "__init__" not in filename
)
@@ -343,12 +343,12 @@ class MigrationLinter(object):
migrations = []
try:
with open(migrations_file_path, "r") as file:
with open(migrations_file_path) as file:
for line in file:
if cls.is_migration_file(line):
app_label, name = split_migration_path(line)
migrations.append((app_label, name))
except IOError:
except OSError:
logger.exception("Migrations list path not found %s", migrations_file_path)
raise Exception("Error while reading migrations list file")
@@ -363,9 +363,9 @@ class MigrationLinter(object):
migrations = []
# Get changes since specified commit
git_diff_command = (
"cd {0} && git diff --relative --name-only --diff-filter=AR {1}"
"cd {} && git diff --relative --name-only --diff-filter=AR {}"
).format(self.django_path, git_commit_id)
logger.info("Executing {0}".format(git_diff_command))
logger.info(f"Executing {git_diff_command}")
diff_process = Popen(git_diff_command, shell=True, stdout=PIPE, stderr=PIPE)
for line in map(clean_bytes_to_str, diff_process.stdout.readlines()):
# Only gather lines that include added migrations
@@ -537,7 +537,7 @@ class MigrationLinter(object):
model = model.split(".", 1)[0]
has_get_model_call = (
re.search(
r"{}.*= +\w+\.get_model\(".format(model),
fr"{model}.*= +\w+\.get_model\(",
source_code,
)
is not None
+2 -2
View File
@@ -36,13 +36,13 @@ def has_add_unique(sql_statements, **kwargs):
concerned_table = regex_result.group(1)
table_is_added_in_transaction = any(
sql.startswith("CREATE TABLE {}".format(concerned_table))
sql.startswith(f"CREATE TABLE {concerned_table}")
for sql in sql_statements
)
return not table_is_added_in_transaction
class BaseAnalyser(object):
class BaseAnalyser:
base_migration_tests = [
{
"code": "RENAME_TABLE",
@@ -16,7 +16,7 @@ def has_create_index(sql_statements, **kwargs):
concerned_table = regex_result.group(2)
table_is_added_in_transaction = any(
sql.startswith("CREATE TABLE {}".format(concerned_table))
sql.startswith(f"CREATE TABLE {concerned_table}")
for sql in sql_statements
)
return not table_is_added_in_transaction
+1 -1
View File
@@ -38,7 +38,7 @@ def get_migration_abspath(app_label, migration_name):
from django.db.migrations.loader import MigrationLoader
module_name, _ = MigrationLoader.migrations_module(app_label)
migration_path = "{}.{}".format(module_name, migration_name)
migration_path = f"{module_name}.{migration_name}"
migration_module = import_module(migration_path)
migration_file = migration_module.__file__
+1 -1
View File
@@ -10,7 +10,7 @@ PROJECT_DIR = path.abspath(path.dirname(__file__))
def get_version():
constants = path.join(PROJECT_DIR, "django_migration_linter", "constants.py")
_version_re = re.compile(r"__version__\s+=\s+(?P<version>.*)")
with open(constants, "r") as f:
with open(constants) as f:
match = _version_re.search(f.read())
version = match.group("version") if match is not None else '"unknown"'
return str(ast.literal_eval(version))
+2 -2
View File
@@ -8,7 +8,7 @@ from django_migration_linter import MigrationLinter
from tests import fixtures
class BaseBackwardCompatibilityDetection(object):
class BaseBackwardCompatibilityDetection:
def setUp(self, *args, **kwargs):
self.database = next(iter(self.databases))
self.test_project_path = os.path.dirname(settings.BASE_DIR)
@@ -24,7 +24,7 @@ class BaseBackwardCompatibilityDetection(object):
"app_unique_together",
database=self.database,
)
return super(BaseBackwardCompatibilityDetection, self).setUp(*args, **kwargs)
return super().setUp(*args, **kwargs)
def _test_linter_finds_errors(self, app=None, commit_id=None):
linter = self._launch_linter(app, commit_id)
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 14:54
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 14:55
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import models
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 14:56
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 14:56
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import models
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 14:59
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import models
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 14:59
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 14:59
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import models
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 14:59
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import models
# class A(models.Model):
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 15:02
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 15:02
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import models
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 15:00
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-04-14 15:00
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import models
+2 -2
View File
@@ -19,10 +19,10 @@ class SqlAnalyserTestCase(unittest.TestCase):
def assertValidSql(self, sql, allow_warnings=False):
errors, _, warnings = self.analyse_sql(sql)
self.assertEqual(0, len(errors), "Found errors in sql: {}".format(errors))
self.assertEqual(0, len(errors), f"Found errors in sql: {errors}")
if not allow_warnings:
self.assertEqual(
0, len(warnings), "Found warnings in sql: {}".format(errors)
0, len(warnings), f"Found warnings in sql: {errors}"
)
def assertBackwardIncompatibleSql(self, sql, code=None):