Skip to content

Commit 78f52e9

Browse files
Robert RoosRobertoRoos
authored andcommitted
Replaced all typing stuff by primitives (#49)
1 parent 169cd0e commit 78f52e9

File tree

9 files changed

+72
-77
lines changed

9 files changed

+72
-77
lines changed

src/tctools/common.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
import sys
33
from abc import ABC, abstractmethod
44
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, Namespace
5+
from collections.abc import Generator
56
from pathlib import Path
6-
from typing import Any, Dict, Generator, List, Optional
7+
from typing import Any
78

89
from lxml import etree
910

@@ -20,7 +21,7 @@
2021

2122

2223
# The result of a files argument - like: `provided_path: [files]`
23-
FileGroups = Dict[Path, List[Path]]
24+
FileGroups = dict[Path, list[Path]]
2425

2526

2627
# Path.glob() only allows symlink recursion from Python 3.13:
@@ -33,14 +34,14 @@ class Tool(ABC):
3334
``argparse`` is done in the constructor, CLI arguments should be passed there.
3435
"""
3536

36-
LOGGER_NAME: Optional[str] = None
37+
LOGGER_NAME: str | None = None
3738

3839
# Default value for file filter argument:
39-
FILTER_DEFAULT: List[str]
40+
FILTER_DEFAULT: list[str]
4041

41-
CONFIG_KEY: Optional[str] = None
42+
CONFIG_KEY: str | None = None
4243

43-
PATH_VARIABLES: List[str] = [] # Names of options that are considered file paths
44+
PATH_VARIABLES: list[str] = [] # Names of options that are considered file paths
4445

4546
def __init__(self, *args):
4647
"""Pass e.g. ``sys.args[1:]`` (skipping the script part of the arguments).
@@ -54,7 +55,7 @@ def __init__(self, *args):
5455
action.dest for action in parser._actions if action.dest != "help" # noqa
5556
}
5657

57-
self.config_file: Optional[Path] = None
58+
self.config_file: Path | None = None
5859

5960
config = self.make_config()
6061
if self.CONFIG_KEY:
@@ -114,7 +115,7 @@ def set_arguments(cls, parser):
114115
default="INFO",
115116
)
116117

117-
def make_config(self) -> Dict[str, Any]:
118+
def make_config(self) -> dict[str, Any]:
118119
"""Get configuration from possible files."""
119120
config = {}
120121
self.config_file = self._find_files_upwards(
@@ -131,9 +132,7 @@ def make_config(self) -> Dict[str, Any]:
131132
return config
132133

133134
@classmethod
134-
def _find_files_upwards(
135-
cls, directory: Path, filenames: List[str]
136-
) -> Optional[Path]:
135+
def _find_files_upwards(cls, directory: Path, filenames: list[str]) -> Path | None:
137136
"""Find a file with a given name in the directory or it's parents.
138137
139138
First hit on any of the filenames is returned.
@@ -194,7 +193,7 @@ def __init__(self, *args):
194193
# Preserve `CDATA` XML flags:
195194
self.xml_parser = etree.XMLParser(strip_cdata=False)
196195

197-
self.header_before: Optional[str] = None # Header of the last XML path
196+
self.header_before: str | None = None # Header of the last XML path
198197

199198
self.files_checked = 0 # Files read by parser
200199
self.files_to_alter = 0 # Files that seem to require changes
@@ -242,7 +241,7 @@ def set_main_argument(cls, parser):
242241
)
243242

244243
@staticmethod
245-
def get_xml_header(file: str) -> Optional[str]:
244+
def get_xml_header(file: str) -> str | None:
246245
"""Get raw XML header as string."""
247246
with open(file, "r") as fh:
248247
# Search only the start of the path, otherwise give up
@@ -264,8 +263,8 @@ def get_xml_tree(self, path: str | Path) -> ElementTree:
264263
@classmethod
265264
def find_files(
266265
cls,
267-
targets: str | List[str],
268-
filters: None | List[str] = None,
266+
targets: str | list[str],
267+
filters: None | list[str] = None,
269268
recursive: bool = True,
270269
skip_check: bool = False,
271270
) -> FileGroups:
@@ -292,7 +291,7 @@ def find_files(
292291
if isinstance(targets, (str, Path)):
293292
targets = [targets]
294293

295-
def add_file(g: List[Path], f: Path):
294+
def add_file(g: list[Path], f: Path):
296295
"""Little local method to prevent duplicate paths."""
297296
if f not in files_unique:
298297
files_unique.add(f)

src/tctools/format/format_class.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import re
22
from collections import OrderedDict
3-
from typing import List, Optional, Tuple, Type
43

54
from editorconfig import get_properties
65

@@ -16,8 +15,8 @@
1615
FormatVariablesAlign,
1716
)
1817

19-
RowCol = Tuple[int, int]
20-
Segment = Tuple[Kind, List[str], str]
18+
RowCol = tuple[int, int]
19+
Segment = tuple[Kind, list[str], str]
2120

2221

2322
class XmlMachine:
@@ -31,9 +30,9 @@ def __init__(self):
3130
self._row = 0 # Line number inside path
3231
self._col = 0 # Position inside line
3332

34-
self.regions: List[Tuple[RowCol, Kind, str]] = []
33+
self.regions: list[tuple[RowCol, Kind, str]] = []
3534

36-
def parse(self, content: List[str]):
35+
def parse(self, content: list[str]):
3736
"""Progress machine line by line."""
3837
self._kind = Kind.XML
3938
self._row = 0
@@ -97,7 +96,7 @@ class Formatter(TcTool):
9796

9897
CONFIG_KEY = "format"
9998

100-
_RULE_CLASSES: List[Type[FormattingRule]] = []
99+
_RULE_CLASSES: list[type[FormattingRule]] = []
101100

102101
def __init__(self, *args):
103102
super().__init__(*args)
@@ -106,7 +105,7 @@ def __init__(self, *args):
106105
# them between methods
107106
self._file = ""
108107
self._properties = OrderedDict()
109-
self._rules: List[FormattingRule] = []
108+
self._rules: list[FormattingRule] = []
110109

111110
self._number_corrections = 0 # Track number of changes for the current file
112111

@@ -119,7 +118,7 @@ def set_arguments(cls, parser):
119118
return parser
120119

121120
@classmethod
122-
def register_rule(cls, new_rule: Type[FormattingRule]):
121+
def register_rule(cls, new_rule: type[FormattingRule]):
123122
"""Incorporate a new formatting rule (accounting for its priority)."""
124123
cls._RULE_CLASSES.append(new_rule)
125124
sorted(cls._RULE_CLASSES, key=lambda item: item.PRIORITY)
@@ -170,7 +169,7 @@ def format_file(self, path: str):
170169
if rule.WHOLE_FILE:
171170
self.apply_rule(rule, content)
172171

173-
segments: List[Segment] = list(self.split_code_segments(content))
172+
segments: list[Segment] = list(self.split_code_segments(content))
174173

175174
for kind, segment, _ in segments:
176175
# Changes are done in-place
@@ -188,7 +187,7 @@ def format_file(self, path: str):
188187
self.files_resaved += 1
189188

190189
@staticmethod
191-
def split_code_segments(content: List[str]):
190+
def split_code_segments(content: list[str]):
192191
"""Copy content, split into XML and code sections.
193192
194193
Function is a generator, each pair is yielded.
@@ -197,7 +196,7 @@ def split_code_segments(content: List[str]):
197196
directly, without extra newlines.
198197
199198
:param: File content as list
200-
:return: List[Segment]
199+
:return: list[Segment]
201200
"""
202201
if not content:
203202
return # Nothing to yield
@@ -230,11 +229,11 @@ def split_code_segments(content: List[str]):
230229

231230
yield kind_prev, lines, name_prev
232231

233-
def format_segment(self, content: List[str], kind: Kind):
232+
def format_segment(self, content: list[str], kind: Kind):
234233
"""Format a specific segment of code.
235234
236235
:param content: Text to reformat (changed in place!)
237-
:param kind: Type of the content
236+
:param kind: type of the content
238237
"""
239238
if kind == Kind.XML:
240239
return # Do nothing
@@ -243,7 +242,7 @@ def format_segment(self, content: List[str], kind: Kind):
243242
if not rule.WHOLE_FILE: # Skip otherwise
244243
self.apply_rule(rule, content, kind)
245244

246-
def apply_rule(self, rule, content, kind: Optional[Kind] = None):
245+
def apply_rule(self, rule, content, kind: Kind | None = None):
247246
"""Run a rule over some content and handle results."""
248247
rule.format(content, kind)
249248
corrections = rule.consume_corrections()

src/tctools/format/format_rules.py

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import math
22
import re
33
from abc import ABC, abstractmethod
4-
from typing import Any, Dict, List, Optional, OrderedDict, Tuple, Type
4+
from collections import OrderedDict
5+
from typing import Any
56

67
from .format_extras import Kind
78

8-
Correction = Tuple[int, str]
9+
Correction = tuple[int, str]
910

1011

1112
class FormattingRule(ABC):
@@ -23,7 +24,7 @@ class FormattingRule(ABC):
2324

2425
def __init__(self, properties: OrderedDict):
2526
self._properties = properties
26-
self._corrections: List[Correction] = []
27+
self._corrections: list[Correction] = []
2728

2829
# Universal properties:
2930

@@ -34,13 +35,13 @@ def __init__(self, properties: OrderedDict):
3435
"tab_width", default=self._indent_size, value_type=int
3536
)
3637

37-
self._indent_style: Optional[str] = self._properties.get("indent_style", None)
38+
self._indent_style: str | None = self._properties.get("indent_style", None)
3839

3940
self._indent_str: str = " " * self._indent_size
4041
if self._indent_style and self._indent_style == "tab":
4142
self._indent_str = "\t"
4243

43-
self._end_of_line: Optional[str] = self._properties.get("end_of_line", None)
44+
self._end_of_line: str | None = self._properties.get("end_of_line", None)
4445
options = {"lf": "\n", "cr": "\r", "crlf": "\r\n"}
4546
self._line_ending: str = options.get(self._end_of_line, "\n")
4647

@@ -58,7 +59,7 @@ def get_property(
5859
self,
5960
name: str,
6061
default: Any = None,
61-
value_type: Optional[Type] = None,
62+
value_type: type | None = None,
6263
) -> Any:
6364
"""Get item from ``_properties``, parsing as needed.
6465
@@ -81,7 +82,7 @@ def get_property(
8182
return value_type(value)
8283

8384
@abstractmethod
84-
def format(self, content: List[str], kind: Optional[Kind] = None):
85+
def format(self, content: list[str], kind: Kind | None = None):
8586
"""Fun rule to format text.
8687
8788
:param content: Text to format (changed in place!)
@@ -96,7 +97,7 @@ def add_correction(self, message: str, line_nr: int):
9697
"""
9798
self._corrections.append((line_nr, message))
9899

99-
def consume_corrections(self) -> List[Correction]:
100+
def consume_corrections(self) -> list[Correction]:
100101
"""Return listed corrections and reset list."""
101102
corrections = self._corrections
102103
self._corrections = []
@@ -112,7 +113,7 @@ class FormatTabs(FormattingRule):
112113
def __init__(self, *args):
113114
super().__init__(*args)
114115

115-
def format(self, content: List[str], kind: Optional[Kind] = None):
116+
def format(self, content: list[str], kind: Kind | None = None):
116117
if self._indent_style == "tab":
117118
re_search = self._re_spaces
118119
elif self._indent_style == "space":
@@ -165,7 +166,7 @@ def __init__(self, *args):
165166
"trim_trailing_whitespace", False, value_type=bool
166167
)
167168

168-
def format(self, content: List[str], kind: Optional[Kind] = None):
169+
def format(self, content: list[str], kind: Kind | None = None):
169170
if not self._remove_tr_ws:
170171
return # Nothing to do
171172
for i, line in enumerate(content):
@@ -185,7 +186,7 @@ def __init__(self, *args):
185186
"insert_final_newline", False, value_type=bool
186187
)
187188

188-
def format(self, content: List[str], kind: Optional[Kind] = None):
189+
def format(self, content: list[str], kind: Kind | None = None):
189190
if not self._insert_final_newline:
190191
return
191192

@@ -232,7 +233,7 @@ def __init__(self, *args):
232233
else:
233234
raise ValueError(f"Unrecognized file ending `{self._line_ending}`")
234235

235-
def format(self, content: List[str], kind: Optional[Kind] = None):
236+
def format(self, content: list[str], kind: Kind | None = None):
236237
if self._end_of_line is None:
237238
return # Nothing specified
238239

@@ -279,7 +280,7 @@ def __init__(self, *args):
279280

280281
self._re_newlines = re.compile(r"[\r\n]+$")
281282

282-
def format(self, content: List[str], kind: Optional[Kind] = None):
283+
def format(self, content: list[str], kind: Kind | None = None):
283284
if not self._align:
284285
return # Disabled by config
285286

@@ -288,14 +289,14 @@ def format(self, content: List[str], kind: Optional[Kind] = None):
288289

289290
self.format_argument_list(content)
290291

291-
def format_argument_list(self, content: List[str]):
292+
def format_argument_list(self, content: list[str]):
292293
"""Format entire declaration section"""
293294

294295
# Get variable definitions, split up and keyed by content index:
295-
variable_definitions: Dict[int, List[Optional[str]]] = {}
296+
variable_definitions: dict[int, list[str]] | None = {}
296297

297298
# Biggest size of each chunk across all lines:
298-
max_chunk_sizes: List[Optional[int]] = [None] * 3
299+
max_chunk_sizes: list[int | None] = [None] * 3
299300

300301
for i, line in enumerate(content):
301302
match = self._re_variable.match(line)
@@ -414,7 +415,7 @@ def __init__(self, *args):
414415
re.VERBOSE | re.MULTILINE,
415416
)
416417

417-
def format(self, content: List[str], kind: Optional[Kind] = None):
418+
def format(self, content: list[str], kind: Kind | None = None):
418419
if self._parentheses is None:
419420
return # Nothing to do
420421

@@ -465,12 +466,12 @@ def format(self, content: List[str], kind: Optional[Kind] = None):
465466
@staticmethod
466467
def find_and_match_braces(
467468
text: str, brace_left: str = "(", brace_right: str = ")"
468-
) -> Tuple[int, int]:
469+
) -> tuple[int, int]:
469470
"""Step through braces in a string.
470471
471472
Note that levels can step into negative.
472473
473-
:return: Tuple of (strpos, level), where strpos is the zero-index position of
474+
:return: tuple of (strpos, level), where strpos is the zero-index position of
474475
the brace itself and level is the nested level it indicates
475476
"""
476477
level = 0

src/tctools/git_info/git_info_class.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
from datetime import datetime
33
from logging import Logger
44
from pathlib import Path
5-
from typing import Optional, Set
65

76
from git import GitCommandError, Repo
87

@@ -22,7 +21,7 @@ class GitSetter:
2221
_DATETIME_FORMAT = "%d-%m-%Y %H:%M:%S"
2322

2423
def __init__(
25-
self, repo: Repo, logger: Logger, tolerate_dirty: Optional[Set[Path]] = None
24+
self, repo: Repo, logger: Logger, tolerate_dirty: set[Path] | None = None
2625
):
2726
self._repo: Repo = repo
2827
self._logger = logger

0 commit comments

Comments
 (0)