Skip to content

Commit 57ef9fe

Browse files
cclaussjcjones
andauthored
Replace black and flake8 with ruff (#75)
Co-authored-by: J.C. Jones <[email protected]>
1 parent 5bc30a0 commit 57ef9fe

10 files changed

+135
-74
lines changed

.flake8

-4
This file was deleted.

.github/workflows/ci.yml

+9-12
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,16 @@ jobs:
88
runs-on: ubuntu-latest
99

1010
steps:
11-
- uses: actions/checkout@v2
11+
- uses: actions/checkout@v4
1212
- name: Set up Python 3.9
13-
uses: actions/setup-python@v2
13+
uses: actions/setup-python@v5
1414
with:
1515
python-version: 3.9
1616

1717
- name: Install Linting Tools
1818
run: |
1919
python -m pip install --upgrade pip
20-
pip install --user pylint==3.1.0
21-
pip install --user black~=23.9.1
22-
pip install --user flake8~=6.1.0
23-
pip install --user pytest
20+
pip install --user pylint==3.1.0 pytest ruff
2421
2522
- name: Install Partition Manager
2623
run: |
@@ -30,21 +27,21 @@ jobs:
3027
run: |
3128
python -m pylint -E partitionmanager
3229
33-
- name: Checking format with Black
30+
- name: Checking format with Ruff
3431
run: |
35-
python -m black --check .
32+
python -m ruff format .
3633
37-
- name: Checking format with Flake8
34+
- name: Lint Python code with Ruff
3835
run: |
39-
python -m flake8
36+
python -m ruff --output-format=github
4037
4138
test:
4239
runs-on: ubuntu-latest
4340

4441
steps:
45-
- uses: actions/checkout@v2
42+
- uses: actions/checkout@v4
4643
- name: Set up Python 3.9
47-
uses: actions/setup-python@v2
44+
uses: actions/setup-python@v5
4845
with:
4946
python-version: 3.9
5047
- name: Install Partition Manager

.pre-commit-config.yaml

+9-8
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
11
repos:
22
- repo: https://github.com/pre-commit/pre-commit-hooks
3-
rev: v4.4.0
3+
rev: v4.5.0
44
hooks:
55
- id: check-ast
66
- id: check-merge-conflict
77
- id: detect-private-key
88
- id: end-of-file-fixer
99
- id: requirements-txt-fixer
1010
- id: trailing-whitespace
11-
- repo: https://github.com/psf/black
12-
rev: "23.9.1"
11+
12+
- repo: https://github.com/astral-sh/ruff-pre-commit
13+
rev: v0.2.2
1314
hooks:
14-
- id: black
15-
- repo: https://github.com/pycqa/flake8
16-
rev: "6.1.0"
17-
hooks:
18-
- id: flake8
15+
- id: ruff
16+
# - id: ruff-format
17+
1918
- repo: https://github.com/PyCQA/pylint
2019
rev: v3.1.0
2120
hooks:
@@ -26,6 +25,8 @@ repos:
2625
- PyMySQL
2726
- pyyaml
2827
- pytest
28+
- setuptools
29+
2930
- repo: local
3031
hooks:
3132
- id: pytest

partitionmanager/database_helpers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def calculate_exact_timestamp_via_query(database, table, position_partition):
5858
raise partitionmanager.types.NoExactTimeException(
5959
"Unexpected column count for the timestamp result"
6060
)
61-
for key, value in exact_time_result[0].items():
61+
for value in exact_time_result[0].values():
6262
exact_time = datetime.fromtimestamp(value, tz=timezone.utc)
6363
break
6464

partitionmanager/migrate.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,7 @@ def _generate_sql_copy_commands(
175175
yield f"\tPARTITION {max_val_part.name} VALUES LESS THAN {max_val_string}"
176176
yield ");"
177177

178-
for command in alter_commands_iter:
179-
yield command
178+
yield from alter_commands_iter
180179

181180
cols = set(columns)
182181

@@ -214,9 +213,11 @@ def _generate_sql_copy_commands(
214213
):
215214
yield line
216215

217-
yield "\t\tWHERE " + " AND ".join(
218-
_trigger_column_copies(map_data["range_cols"])
219-
) + ";"
216+
yield (
217+
"\t\tWHERE "
218+
+ " AND ".join(_trigger_column_copies(map_data["range_cols"]))
219+
+ ";"
220+
)
220221

221222
return
222223

partitionmanager/stats_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def test_statistics_two_partitions(self):
4646
def test_statistics_weekly_partitions_year(self):
4747
parts = list()
4848
base = datetime(2020, 5, 20, tzinfo=timezone.utc)
49-
for w in range(0, 52):
49+
for w in range(52):
5050
partName = f"p_{base + timedelta(weeks=w):%Y%m%d}"
5151
parts.append(mkPPart(partName, w * 1024))
5252
parts.append(MaxValuePartition(f"p_{base + timedelta(weeks=52):%Y%m%d}", 1))

partitionmanager/table_append_partition.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -107,13 +107,13 @@ def _parse_partition_map(rows):
107107

108108
options = rows[0]
109109

110-
for l in options["Create Table"].split("\n"):
111-
range_match = partition_range.match(l)
110+
for line in options["Create Table"].split("\n"):
111+
range_match = partition_range.match(line)
112112
if range_match:
113113
range_cols = [x.strip("` ") for x in range_match.group("cols").split(",")]
114114
log.debug(f"Partition range columns: {range_cols}")
115115

116-
member_match = partition_member.match(l)
116+
member_match = partition_member.match(line)
117117
if member_match:
118118
part_name = member_match.group("name")
119119
part_vals_str = member_match.group("cols")
@@ -139,7 +139,7 @@ def _parse_partition_map(rows):
139139
)
140140
partitions.append(pos_part)
141141

142-
member_tail = partition_tail.match(l)
142+
member_tail = partition_tail.match(line)
143143
if member_tail:
144144
if range_cols is None:
145145
raise partitionmanager.types.TableInformationException(
@@ -200,7 +200,7 @@ def _split_partitions_around_position(partition_list, current_position):
200200
if not partitionmanager.types.is_partition_type(p):
201201
raise partitionmanager.types.UnexpectedPartitionException(p)
202202
if not isinstance(current_position, partitionmanager.types.Position):
203-
raise ValueError()
203+
raise ValueError
204204

205205
less_than_partitions = list()
206206
greater_or_equal_partitions = list()
@@ -481,7 +481,7 @@ def _plan_partition_changes(
481481
"as without an empty partition to manipulate, you'll need to "
482482
"perform an expensive copy operation. See the bootstrap mode."
483483
)
484-
raise partitionmanager.types.NoEmptyPartitionsAvailableException()
484+
raise partitionmanager.types.NoEmptyPartitionsAvailableException
485485
if not active_partition:
486486
raise Exception("Active Partition can't be None")
487487

@@ -626,8 +626,7 @@ def _should_run_changes(table, altered_partitions):
626626
log.debug(f"{p} is new")
627627
return True
628628

629-
if isinstance(p, partitionmanager.types.ChangePlannedPartition):
630-
if p.important():
629+
if isinstance(p, partitionmanager.types.ChangePlannedPartition) and p.important():
631630
log.debug(f"{p} is marked important")
632631
return True
633632
return False

partitionmanager/table_append_partition_test.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# flake8: noqa: E501
1+
# ruff: noqa: E501
22

33
import unittest
44
import argparse
@@ -7,11 +7,8 @@
77
ChangePlannedPartition,
88
DatabaseCommand,
99
DuplicatePartitionException,
10-
MaxValuePartition,
11-
MismatchedIdException,
1210
NewPlannedPartition,
1311
NoEmptyPartitionsAvailableException,
14-
PositionPartition,
1512
InstantPartition,
1613
SqlInput,
1714
SqlQuery,
@@ -49,7 +46,7 @@ def __init__(self):
4946
self._response = []
5047
self._num_queries = 0
5148

52-
def run(self, cmd):
49+
def run(self, cmd): # noqa: ARG002
5350
self._num_queries += 1
5451
return self._response.pop()
5552

partitionmanager/types.py

+17-30
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,8 @@ def timedelta_from_dict(r):
1818
for k, v in r.items():
1919
if k == "days":
2020
return timedelta(days=v)
21-
raise argparse.ArgumentTypeError(
22-
f"Unknown retention period definition: {k}={v}"
23-
)
21+
raise argparse.ArgumentTypeError(f"Unknown retention period definition: {k}={v}")
22+
return None
2423

2524

2625
class Table:
@@ -96,32 +95,22 @@ def __new__(cls, *args):
9695
raise argparse.ArgumentTypeError(f"{args} is not a single argument")
9796
query_string = args[0].strip()
9897
if not query_string.endswith(";"):
99-
raise argparse.ArgumentTypeError(
100-
f"[{query_string}] does not end with a ';'"
101-
)
98+
raise argparse.ArgumentTypeError(f"[{query_string}] does not end with a ';'")
10299
if query_string.count(";") > 1:
103-
raise argparse.ArgumentTypeError(
104-
f"[{query_string}] has more than one statement"
105-
)
100+
raise argparse.ArgumentTypeError(f"[{query_string}] has more than one statement")
106101

107102
if "?" not in query_string:
108-
raise argparse.ArgumentTypeError(
109-
f"[{query_string}] has no substitution variable '?'"
110-
)
103+
raise argparse.ArgumentTypeError(f"[{query_string}] has no substitution variable '?'")
111104
if query_string.count("?") > 1:
112105
raise argparse.ArgumentTypeError(
113106
f"[{query_string}] has more than one substitution variable '?'"
114107
)
115108

116109
if not query_string.upper().startswith("SELECT "):
117-
raise argparse.ArgumentTypeError(
118-
f"[{query_string}] is not a SELECT statement"
119-
)
110+
raise argparse.ArgumentTypeError(f"[{query_string}] is not a SELECT statement")
120111
for term in SqlQuery.forbidden_terms:
121112
if term in query_string.upper():
122-
raise argparse.ArgumentTypeError(
123-
f"[{query_string}] has a forbidden term [{term}]"
124-
)
113+
raise argparse.ArgumentTypeError(f"[{query_string}] has a forbidden term [{term}]")
125114

126115
return super().__new__(cls, query_string)
127116

@@ -142,7 +131,7 @@ def to_sql_url(urlstring):
142131
urltuple = urlparse(urlstring)
143132
if urltuple.scheme.lower() != "sql":
144133
raise argparse.ArgumentTypeError(f"{urlstring} is not a valid sql://")
145-
if urltuple.path == "/" or urltuple.path == "":
134+
if urltuple.path in {"/", ""}:
146135
raise argparse.ArgumentTypeError(f"{urlstring} should include a db path")
147136
return urltuple
148137
except ValueError as ve:
@@ -259,7 +248,7 @@ def set_position(self, position_in):
259248
"""Set the list of identifiers for this position."""
260249
if isinstance(position_in, Position):
261250
self._position = position_in.as_list()
262-
elif isinstance(position_in, list) or isinstance(position_in, tuple):
251+
elif isinstance(position_in, (list, tuple)):
263252
self._position = [int(p) for p in position_in]
264253
else:
265254
raise ValueError(f"Unexpected position input: {position_in}")
@@ -345,10 +334,10 @@ def __lt__(self, other):
345334

346335
# If ALL of v_mine >= v_other, then self is greater than other
347336
# If ANY of v_mine < v_other, then self is less than other
348-
for v_mine, v_other in zip(self._position.as_list(), other_position_list):
349-
if v_mine < v_other:
350-
return True
351-
return False
337+
return any(
338+
v_mine < v_other
339+
for v_mine, v_other in zip(self._position.as_list(), other_position_list)
340+
)
352341

353342
def __ge__(self, other):
354343
return not self < other
@@ -388,7 +377,7 @@ def values(self):
388377

389378
def __lt__(self, other):
390379
"""MaxValuePartitions are always greater than every other partition."""
391-
if isinstance(other, list) or isinstance(other, Position):
380+
if isinstance(other, (Position, list)):
392381
if self._count != len(other):
393382
raise UnexpectedPartitionException(
394383
f"Expected {self._count} columns but list has {len(other)}."
@@ -506,11 +495,9 @@ def set_as_max_value(self):
506495
def as_partition(self):
507496
"""Return a concrete Partition that can be rendered into a SQL ALTER."""
508497
if not self._timestamp:
509-
raise ValueError()
498+
raise ValueError
510499
if self._position:
511-
return PositionPartition(f"p_{self._timestamp:%Y%m%d}").set_position(
512-
self._position
513-
)
500+
return PositionPartition(f"p_{self._timestamp:%Y%m%d}").set_position(self._position)
514501
return MaxValuePartition(f"p_{self._timestamp:%Y%m%d}", count=self._num_columns)
515502

516503
def __repr__(self):
@@ -535,7 +522,7 @@ class ChangePlannedPartition(_PlannedPartition):
535522

536523
def __init__(self, old_part):
537524
if not is_partition_type(old_part):
538-
raise ValueError()
525+
raise ValueError
539526
super().__init__()
540527
self._old = old_part
541528
self._num_columns = self._old.num_columns

0 commit comments

Comments
 (0)