Skip to content

Commit 48dc625

Browse files
ArchmongerCopilot
andauthored
Format and lint code using ruff (#634)
- Change formatter and linter to `hatch fmt` (which uses `ruff`) - Implement any changes to make `hatch fmt` happy --------- Co-authored-by: Copilot <[email protected]>
1 parent fae570f commit 48dc625

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+900
-965
lines changed

.github/copilot-instructions.md

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Bootstrap, build, and test the repository:
1717
- `hatch run functional:all` – end-to-end functional (SQLite + PostgreSQL live scripts) (≈10–15s) **NEVER CANCEL.**
1818
- `hatch run functional:sqlite --all` – only SQLite functional cycle
1919
- `hatch run functional:postgres --all` – only PostgreSQL functional cycle
20-
- `hatch run lint:check` – lint (ruff + pylint) (≈5s)
20+
- `hatch run lint:check` – lint (ruff) (≈5s)
2121
- `hatch run docs:build` – build documentation (≈2s, strict)
2222
- `hatch run docs:serve` – local docs server (http://localhost:8000)
2323
- `hatch run docs:linkcheck` – validate internal/external links & spelling
@@ -40,8 +40,7 @@ Run tests in multiple configurations:
4040
- `hatch run functional:all -v` – functional backup/restore (SQLite + PostgreSQL)
4141
- `hatch run functional:sqlite --all -v` – functional (SQLite only)
4242
- `hatch run functional:postgres --all -v` – functional (PostgreSQL only)
43-
- `hatch run lint:check` – linting
44-
- `hatch run lint:format` – auto-format (Ruff)
43+
- `hatch fmt --check` – Python formatting and linting using ruff
4544

4645
Expected test results:
4746

@@ -103,7 +102,7 @@ Modern development process using Hatch:
103102
3. **Run unit tests**: `hatch test` (≈30s) **All must pass - failures are never expected or allowed.**
104103
4. **Run functional tests**: `hatch run functional:all -v` (≈10–15s)
105104
5. **Run linting**: `hatch run lint:check` (5 seconds)
106-
6. **Auto-format code**: `hatch run lint:format` (2 seconds)
105+
6. **Auto-format code**: `hatch fmt` (2 seconds)
107106
7. **Test documentation**: `hatch run docs:build` (2 seconds)
108107
8. **Update documentation** when making changes to Python source code (required)
109108
9. **Add changelog entry** for all significant changes (bug fixes, new features, breaking changes) to `CHANGELOG.md` under the "Unreleased" section.
@@ -136,7 +135,7 @@ Key directories and files:
136135

137136
Key configuration files:
138137

139-
- `pyproject.toml` – all tool configuration (Hatch, Ruff, PyLint, PyTest, Coverage)
138+
- `pyproject.toml` – all tool configuration (Hatch, Ruff, PyTest, Coverage)
140139
- `.pre-commit-config.yaml` – git pre-commit hooks
141140
- `tests/settings.py` – Django test settings (locmem email backend)
142141

@@ -152,9 +151,8 @@ hatch test --python 3.12 # Test specific Python version subset
152151
hatch run functional:all # Functional tests (SQLite + PostgreSQL)
153152
hatch run functional:sqlite --all # Functional tests (SQLite only)
154153
hatch run functional:postgres --all # Functional tests (PostgreSQL only)
155-
hatch run lint:check # Lint (ruff + pylint)
156-
hatch run lint:format # Auto-format
157-
hatch run lint:format-check # Format check only
154+
hatch fmt --check # Check formatting and linting
155+
hatch fmt # Auto-format and lint
158156
hatch run docs:build # Build documentation (strict)
159157
hatch run docs:serve # Serve docs locally
160158
hatch run precommit:check # Run all pre-commit hooks
@@ -168,8 +166,6 @@ hatch build # Build distribution packages
168166
hatch env show # Show all environments
169167
hatch shell # Default dev shell
170168
hatch shell functional # Functional env shell
171-
hatch shell lint # Lint env shell
172-
hatch run --env lint ruff --version # Run command in lint env
173169
hatch python install 3.13 # (Optional) Install Python 3.13 via Hatch
174170
```
175171

@@ -184,7 +180,6 @@ Modern isolated environments configured in pyproject.toml:
184180

185181
### Development Environments
186182

187-
- **lint**: Code quality (ruff, pylint)
188183
- **docs**: Documentation building (mkdocs-material)
189184
- **precommit**: Git hooks management
190185

@@ -225,7 +220,7 @@ Core runtime dependency:
225220
Development dependencies (managed by hatch):
226221

227222
- **Testing**: coverage, django-storages, psycopg2-binary, python-gnupg, testfixtures, python-dotenv
228-
- **Linting**: ruff, pylint
223+
- **Linting**: ruff
229224
- **Documentation**: mkdocs, mkdocs-material, mkdocs-git-revision-date-localized-plugin, mkdocs-include-markdown-plugin, mkdocs-spellcheck[all], mkdocs-git-authors-plugin, mkdocs-minify-plugin, mike, linkcheckmd
230225
- **Pre-commit**: pre-commit
231226

dbbackup/db/base.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@
88
from importlib import import_module
99
from subprocess import Popen
1010
from tempfile import SpooledTemporaryFile
11+
from typing import Any, ClassVar
1112

1213
from django.core.files.base import File
1314

1415
from dbbackup import settings, utils
15-
16-
from . import exceptions
16+
from dbbackup.db import exceptions
1717

1818
logger = logging.getLogger("dbbackup.command")
1919
logger.setLevel(logging.DEBUG)
@@ -69,7 +69,7 @@ class BaseDBConnector:
6969
"""
7070

7171
extension = "dump"
72-
exclude = []
72+
exclude: ClassVar[list[Any]] = []
7373

7474
def __init__(self, database_name=None, **kwargs):
7575
from django.db import DEFAULT_DB_ALIAS, connections
@@ -98,7 +98,8 @@ def _create_dump(self):
9898
"""
9999
Override this method to define dump creation.
100100
"""
101-
raise NotImplementedError("_create_dump not implemented")
101+
msg = "_create_dump not implemented"
102+
raise NotImplementedError(msg)
102103

103104
def restore_dump(self, dump):
104105
"""
@@ -113,7 +114,8 @@ def _restore_dump(self, dump):
113114
:param dump: Dump file
114115
:type dump: file
115116
"""
116-
raise NotImplementedError("_restore_dump not implemented")
117+
msg = "_restore_dump not implemented"
118+
raise NotImplementedError(msg)
117119

118120

119121
class BaseCommandDBConnector(BaseDBConnector):
@@ -127,9 +129,9 @@ class BaseCommandDBConnector(BaseDBConnector):
127129
restore_suffix = ""
128130

129131
use_parent_env = True
130-
env = {}
131-
dump_env = {}
132-
restore_env = {}
132+
env: ClassVar[dict[str, Any]] = {}
133+
dump_env: ClassVar[dict[str, Any]] = {}
134+
restore_env: ClassVar[dict[str, Any]] = {}
133135

134136
def run_command(self, command, stdin=None, env=None):
135137
"""
@@ -180,7 +182,8 @@ def run_command(self, command, stdin=None, env=None):
180182
process.wait()
181183
if process.poll():
182184
stderr.seek(0)
183-
raise exceptions.CommandConnectorError(f"Error running: {command}\n{stderr.read().decode('utf-8')}")
185+
msg = f"Error running: {command}\n{stderr.read().decode('utf-8')}"
186+
raise exceptions.CommandConnectorError(msg)
184187
return self._reset_streams(stdout, stderr)
185188

186189
except OSError as err:
@@ -196,10 +199,11 @@ def run_command(self, command, stdin=None, env=None):
196199
f"Alternatively, you can specify custom command paths using these settings:\n"
197200
f"- DUMP_CMD: Path to the dump command\n"
198201
f"- RESTORE_CMD: Path to the restore command\n\n"
199-
f"Original error: {str(err)}"
202+
f"Original error: {err!s}"
200203
)
201204
raise exceptions.CommandConnectorError(error_msg) from err
202-
raise exceptions.CommandConnectorError(f"Error running: {command}\n{str(err)}") from err
205+
msg = f"Error running: {command}\n{err!s}"
206+
raise exceptions.CommandConnectorError(msg) from err
203207

204208
def _env_shim(self, stdout, stderr, env):
205209
result_env = {}

dbbackup/db/django.py

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

1414
from django.core.management import call_command
1515

16-
from .base import BaseDBConnector
16+
from dbbackup.db.base import BaseDBConnector
1717

1818

1919
class DjangoConnector(BaseDBConnector):

dbbackup/db/mongodb.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import shlex
22

3-
from .base import BaseCommandDBConnector
3+
from dbbackup.db.base import BaseCommandDBConnector
44

55

66
class MongoDumpConnector(BaseCommandDBConnector):

dbbackup/db/mysql.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import shlex
22

3-
from .base import BaseCommandDBConnector
3+
from dbbackup.db.base import BaseCommandDBConnector
44

55

66
class MysqlDumpConnector(BaseCommandDBConnector):

dbbackup/db/postgresql.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
import logging
44
import shlex
5-
from typing import Any, List, Optional
5+
from typing import Any, ClassVar
66
from urllib.parse import quote
77

8-
from .base import BaseCommandDBConnector
8+
from dbbackup.db.base import BaseCommandDBConnector
99

1010
logger = logging.getLogger("dbbackup.command")
1111

@@ -50,7 +50,7 @@ class PgDumpConnector(BaseCommandDBConnector):
5050
single_transaction = True
5151
drop = True
5252
if_exists = True
53-
schemas: Optional[List[str]] = []
53+
schemas: ClassVar[list[str] | None] = []
5454

5555
def _create_dump(self):
5656
cmd_part, pg_env = parse_postgres_settings(self)

dbbackup/db/sqlite.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from django.db import IntegrityError, OperationalError
1010

11-
from .base import BaseDBConnector
11+
from dbbackup.db.base import BaseDBConnector
1212

1313
DUMP_TABLES = """
1414
SELECT "name", "type", "sql"
@@ -55,7 +55,7 @@ def _write_dump(self, fileobj):
5555

5656
# Dump indexes, triggers, and views after all tables are created
5757
cursor.execute(DUMP_ETC)
58-
for name, _, sql in cursor.fetchall():
58+
for _name, _, sql in cursor.fetchall():
5959
if sql.startswith("CREATE INDEX"):
6060
sql = sql.replace("CREATE INDEX", "CREATE INDEX IF NOT EXISTS", 1)
6161
elif sql.startswith("CREATE TRIGGER"):
@@ -129,9 +129,7 @@ def restore_dump(self, dump):
129129

130130
@staticmethod
131131
def _should_suppress_error(msg: str):
132-
return (msg.startswith("index") or msg.startswith("trigger") or msg.startswith("view")) and msg.endswith(
133-
"already exists"
134-
)
132+
return (msg.startswith(("index", "trigger", "view"))) and msg.endswith("already exists")
135133

136134

137135
class SqliteCPConnector(BaseDBConnector):

dbbackup/log.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@
55

66
class DbbackupAdminEmailHandler(AdminEmailHandler):
77
def send_mail(self, subject, message, *args, **kwargs):
8-
from . import utils
8+
from dbbackup import utils
99

1010
utils.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
1111

1212

1313
class MailEnabledFilter(logging.Filter):
1414
def filter(self, record):
15-
from .settings import SEND_EMAIL
15+
from dbbackup.settings import SEND_EMAIL
1616

1717
return SEND_EMAIL
1818

dbbackup/management/commands/_base.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from django.core.management.base import BaseCommand, CommandError
1010

11-
from ...storage import StorageError
11+
from dbbackup.storage import StorageError
1212

1313
USELESS_ARGS = ("callback", "callback_args", "callback_kwargs", "metavar")
1414
TYPES = {
@@ -20,7 +20,7 @@
2020
"choice": list,
2121
}
2222
LOGGING_VERBOSITY = {
23-
0: logging.WARN,
23+
0: logging.WARNING,
2424
1: logging.INFO,
2525
2: logging.DEBUG,
2626
3: logging.DEBUG,
@@ -86,7 +86,7 @@ def write_to_storage(self, file, path):
8686

8787
def read_local_file(self, path):
8888
"""Open file in read mode on local filesystem."""
89-
return open(path, "rb")
89+
return open(path, "rb") # noqa: SIM115
9090

9191
def write_local_file(self, outputfile, path):
9292
"""Write file to the desired path."""

dbbackup/management/commands/dbbackup.py

Lines changed: 12 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -4,50 +4,28 @@
44

55
from django.core.management.base import CommandError
66

7-
from ... import settings, utils
8-
from ...db.base import get_connector
9-
from ...signals import pre_backup, post_backup
10-
from ...storage import StorageError, get_storage
11-
from ._base import BaseDbBackupCommand, make_option
7+
from dbbackup import settings, utils
8+
from dbbackup.db.base import get_connector
9+
from dbbackup.management.commands._base import BaseDbBackupCommand, make_option
10+
from dbbackup.signals import post_backup, pre_backup
11+
from dbbackup.storage import StorageError, get_storage
1212

1313

1414
class Command(BaseDbBackupCommand):
1515
help = "Backup a database, encrypt and/or compress."
1616
content_type = "db"
1717

18-
option_list = BaseDbBackupCommand.option_list + (
18+
option_list = (
19+
*BaseDbBackupCommand.option_list,
1920
make_option(
20-
"-c",
21-
"--clean",
22-
dest="clean",
23-
action="store_true",
24-
default=False,
25-
help="Clean up old backup files",
21+
"-c", "--clean", dest="clean", action="store_true", default=False, help="Clean up old backup files"
2622
),
2723
make_option(
28-
"-d",
29-
"--database",
30-
help="Database(s) to backup specified by key separated by commas(default: all)",
31-
),
32-
make_option(
33-
"-s",
34-
"--servername",
35-
help="Specify server name to include in backup filename",
36-
),
37-
make_option(
38-
"-z",
39-
"--compress",
40-
action="store_true",
41-
default=False,
42-
help="Compress the backup files",
43-
),
44-
make_option(
45-
"-e",
46-
"--encrypt",
47-
action="store_true",
48-
default=False,
49-
help="Encrypt the backup files",
24+
"-d", "--database", help="Database(s) to backup specified by key separated by commas(default: all)"
5025
),
26+
make_option("-s", "--servername", help="Specify server name to include in backup filename"),
27+
make_option("-z", "--compress", action="store_true", default=False, help="Compress the backup files"),
28+
make_option("-e", "--encrypt", action="store_true", default=False, help="Encrypt the backup files"),
5129
make_option("-o", "--output-filename", default=None, help="Specify filename on storage"),
5230
make_option(
5331
"-O",

0 commit comments

Comments
 (0)