Skip to content

Commit be7d54e

Browse files
committed
Change linter to Ruff (#106)
1 parent ed1daf2 commit be7d54e

39 files changed

+387
-249
lines changed

dissect/cstruct/__init__.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -46,46 +46,46 @@
4646
)
4747

4848
__all__ = [
49-
"cstruct",
50-
"ctypes",
51-
"ctypes_type",
5249
"LEB128",
5350
"Array",
5451
"BaseType",
52+
"BitBuffer",
5553
"Char",
5654
"CharArray",
5755
"Enum",
56+
"Error",
5857
"Expression",
5958
"Field",
6059
"Flag",
6160
"Int",
6261
"MetaType",
62+
"NullPointerDereference",
6363
"Packed",
64+
"ParserError",
6465
"Pointer",
66+
"ResolveError",
6567
"Structure",
6668
"Union",
6769
"Void",
6870
"Wchar",
6971
"WcharArray",
70-
"BitBuffer",
72+
"cstruct",
73+
"ctypes",
74+
"ctypes_type",
7175
"dumpstruct",
7276
"hexdump",
73-
"pack",
7477
"p8",
7578
"p16",
7679
"p32",
7780
"p64",
81+
"pack",
7882
"swap",
7983
"swap16",
8084
"swap32",
8185
"swap64",
82-
"unpack",
8386
"u8",
8487
"u16",
8588
"u32",
8689
"u64",
87-
"Error",
88-
"ParserError",
89-
"ResolveError",
90-
"NullPointerDereference",
90+
"unpack",
9191
]

dissect/cstruct/compiler.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@
66
import logging
77
from enum import Enum
88
from textwrap import dedent, indent
9-
from types import MethodType
10-
from typing import TYPE_CHECKING, Iterator
9+
from typing import TYPE_CHECKING
1110

1211
from dissect.cstruct.bitbuffer import BitBuffer
1312
from dissect.cstruct.types import (
@@ -30,6 +29,9 @@
3029
from dissect.cstruct.types.packed import _struct
3130

3231
if TYPE_CHECKING:
32+
from collections.abc import Iterator
33+
from types import MethodType
34+
3335
from dissect.cstruct.cstruct import cstruct
3436
from dissect.cstruct.types.structure import Field
3537

@@ -127,8 +129,7 @@ def generate_source(self) -> str:
127129

128130
code = indent(dedent(preamble).lstrip() + read_code + dedent(outro), " ")
129131

130-
template = f"def _read(cls, stream, context=None):\n{code}"
131-
return template
132+
return f"def _read(cls, stream, context=None):\n{code}"
132133

133134
def _generate_fields(self) -> Iterator[str]:
134135
current_offset = 0
@@ -210,10 +211,9 @@ def align_to_field(field: Field) -> Iterator[str]:
210211
else:
211212
current_block.append(field)
212213

213-
if current_offset is not None and size is not None:
214-
if not field.bits or (field.bits and bits_rollover):
215-
current_offset += size
216-
bits_rollover = False
214+
if current_offset is not None and size is not None and (not field.bits or bits_rollover):
215+
current_offset += size
216+
bits_rollover = False
217217

218218
yield from flush()
219219

dissect/cstruct/cstruct.py

+11-9
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
import struct
55
import sys
66
import types
7-
from typing import Any, BinaryIO, Iterator
7+
from pathlib import Path
8+
from typing import TYPE_CHECKING, Any, BinaryIO
89

910
from dissect.cstruct.exceptions import ResolveError
1011
from dissect.cstruct.expression import Expression
@@ -27,6 +28,9 @@
2728
Wchar,
2829
)
2930

31+
if TYPE_CHECKING:
32+
from collections.abc import Iterator
33+
3034

3135
class cstruct:
3236
"""Main class of cstruct. All types are registered in here.
@@ -134,7 +138,6 @@ def __init__(self, endian: str = "<", pointer: str | None = None):
134138
"unsigned __int32": "uint32",
135139
"unsigned __int64": "uint64",
136140
"unsigned __int128": "uint128",
137-
"unsigned __int128": "uint128",
138141

139142
"wchar_t": "wchar",
140143

@@ -233,7 +236,7 @@ def add_custom_type(
233236
"""
234237
self.add_type(name, self._make_type(name, (type_,), size, alignment=alignment, attrs=kwargs))
235238

236-
def load(self, definition: str, deftype: int = None, **kwargs) -> cstruct:
239+
def load(self, definition: str, deftype: int | None = None, **kwargs) -> cstruct:
237240
"""Parse structures from the given definitions using the given definition type.
238241
239242
Definitions can be parsed using different parsers. Currently, there's
@@ -259,7 +262,7 @@ def load(self, definition: str, deftype: int = None, **kwargs) -> cstruct:
259262

260263
return self
261264

262-
def loadfile(self, path: str, deftype: int = None, **kwargs) -> None:
265+
def loadfile(self, path: str, deftype: int | None = None, **kwargs) -> None:
263266
"""Load structure definitions from a file.
264267
265268
The given path will be read and parsed using the .load() function.
@@ -269,7 +272,7 @@ def loadfile(self, path: str, deftype: int = None, **kwargs) -> None:
269272
deftype: The definition type to parse the definitions with.
270273
**kwargs: Keyword arguments for parsers.
271274
"""
272-
with open(path) as fh:
275+
with Path(path).open() as fh:
273276
self.load(fh.read(), deftype, **kwargs)
274277

275278
def read(self, name: str, stream: BinaryIO) -> Any:
@@ -354,10 +357,10 @@ def _make_array(self, type_: MetaType, num_entries: int | Expression | None) ->
354357

355358
return self._make_type(name, bases, size, alignment=type_.alignment, attrs=attrs)
356359

357-
def _make_int_type(self, name: str, size: int, signed: bool, *, alignment: int = None) -> type[Int]:
360+
def _make_int_type(self, name: str, size: int, signed: bool, *, alignment: int | None = None) -> type[Int]:
358361
return self._make_type(name, (Int,), size, alignment=alignment, attrs={"signed": signed})
359362

360-
def _make_packed_type(self, name: str, packchar: str, base: type, *, alignment: int = None) -> type[Packed]:
363+
def _make_packed_type(self, name: str, packchar: str, base: type, *, alignment: int | None = None) -> type[Packed]:
361364
return self._make_type(
362365
name,
363366
(base, Packed),
@@ -414,8 +417,7 @@ def ctypes(structure: Structure) -> _ctypes.Structure:
414417
t = ctypes_type(field.type)
415418
fields.append((field.name, t))
416419

417-
tt = type(structure.name, (_ctypes.Structure,), {"_fields_": fields})
418-
return tt
420+
return type(structure.name, (_ctypes.Structure,), {"_fields_": fields})
419421

420422

421423
def ctypes_type(type_: MetaType) -> Any:

dissect/cstruct/expression.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
import string
4-
from typing import TYPE_CHECKING, Callable
4+
from typing import TYPE_CHECKING, Callable, ClassVar
55

66
from dissect.cstruct.exceptions import ExpressionParserError, ExpressionTokenizerError
77

@@ -21,8 +21,7 @@ def __init__(self, expression: str):
2121
def equal(self, token: str, expected: str | set[str]) -> bool:
2222
if isinstance(expected, set):
2323
return token in expected
24-
else:
25-
return token == expected
24+
return token == expected
2625

2726
def alnum(self, token: str) -> bool:
2827
return token.isalnum()
@@ -88,7 +87,7 @@ def tokenize(self) -> list[str]:
8887
continue
8988

9089
# If token is a single digit, keep looping over expression and build the number
91-
elif self.match(self.digit, consume=False, append=False):
90+
if self.match(self.digit, consume=False, append=False):
9291
token += self.get_token()
9392
self.consume()
9493

@@ -154,7 +153,7 @@ def tokenize(self) -> list[str]:
154153
class Expression:
155154
"""Expression parser for calculations in definitions."""
156155

157-
binary_operators = {
156+
binary_operators: ClassVar[dict[str, Callable[[int, int], int]]] = {
158157
"|": lambda a, b: a | b,
159158
"^": lambda a, b: a ^ b,
160159
"&": lambda a, b: a & b,
@@ -167,12 +166,12 @@ class Expression:
167166
"%": lambda a, b: a % b,
168167
}
169168

170-
unary_operators = {
169+
unary_operators: ClassVar[dict[str, Callable[[int], int]]] = {
171170
"u": lambda a: -a,
172171
"~": lambda a: ~a,
173172
}
174173

175-
precedence_levels = {
174+
precedence_levels: ClassVar[dict[str, int]] = {
176175
"|": 0,
177176
"^": 1,
178177
"&": 2,

dissect/cstruct/parser.py

+16-24
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import ast
44
import re
5-
from typing import TYPE_CHECKING
5+
from typing import TYPE_CHECKING, Any
66

77
from dissect.cstruct import compiler
88
from dissect.cstruct.exceptions import (
@@ -33,7 +33,7 @@ def parse(self, data: str) -> None:
3333
Args:
3434
data: Data to parse definitions from, usually a string.
3535
"""
36-
raise NotImplementedError()
36+
raise NotImplementedError
3737

3838

3939
class TokenParser(Parser):
@@ -119,10 +119,8 @@ def _enum(self, tokens: TokenConsumer) -> None:
119119
val = val.strip()
120120
if not key:
121121
continue
122-
if not val:
123-
val = nextval
124-
else:
125-
val = Expression(self.cstruct, val).evaluate(values)
122+
123+
val = nextval if not val else Expression(self.cstruct, val).evaluate(values)
126124

127125
if enumtype == "flag":
128126
high_bit = val.bit_length() - 1
@@ -243,7 +241,7 @@ def _lookup(self, tokens: TokenConsumer) -> None:
243241
# Dirty trick because the regex expects a ; but we don't want it to be part of the value
244242
m = pattern.match(ltok.value + ";")
245243
d = ast.literal_eval(m.group(2))
246-
self.cstruct.lookups[m.group(1)] = dict([(self.cstruct.consts[k], v) for k, v in d.items()])
244+
self.cstruct.lookups[m.group(1)] = {self.cstruct.consts[k]: v for k, v in d.items()}
247245

248246
def _parse_field(self, tokens: TokenConsumer) -> Field:
249247
type_ = None
@@ -279,10 +277,7 @@ def _parse_field_type(self, type_: MetaType, name: str) -> tuple[MetaType, str,
279277

280278
if count_expression is not None:
281279
# Poor mans multi-dimensional array by abusing the eager regex match of count
282-
if "][" in count_expression:
283-
counts = count_expression.split("][")
284-
else:
285-
counts = [count_expression]
280+
counts = count_expression.split("][") if "][" in count_expression else [count_expression]
286281

287282
for count in reversed(counts):
288283
if count == "":
@@ -315,8 +310,7 @@ def _names(self, tokens: TokenConsumer) -> list[str]:
315310
if ntoken == self.TOK.NAME:
316311
names.append(ntoken.value.strip())
317312
elif ntoken == self.TOK.DEFS:
318-
for name in ntoken.value.strip().split(","):
319-
names.append(name.strip())
313+
names.extend([name.strip() for name in ntoken.value.strip().split(",")])
320314

321315
return names
322316

@@ -333,8 +327,8 @@ def _replacer(match: re.Match) -> str:
333327
# it means we have captured a non-quoted (real) comment string.
334328
if comment := match.group(2):
335329
return "\n" * comment.count("\n") # so we will return empty to remove the comment
336-
else: # otherwise, we will return the 1st group
337-
return match.group(1) # captured quoted-string
330+
# otherwise, we will return the 1st group
331+
return match.group(1) # captured quoted-string
338332

339333
return regex.sub(_replacer, string)
340334

@@ -429,10 +423,8 @@ def _enums(self, data: str) -> None:
429423
val = val.strip()
430424
if not key:
431425
continue
432-
if not val:
433-
val = nextval
434-
else:
435-
val = Expression(self.cstruct, val).evaluate()
426+
427+
val = nextval if not val else Expression(self.cstruct, val).evaluate()
436428

437429
if enumtype == "flag":
438430
high_bit = val.bit_length() - 1
@@ -535,7 +527,7 @@ def _lookups(self, data: str, consts: dict[str, int]) -> None:
535527

536528
for t in r:
537529
d = ast.literal_eval(t.group(2))
538-
self.cstruct.lookups[t.group(1)] = dict([(self.cstruct.consts[k], v) for k, v in d.items()])
530+
self.cstruct.lookups[t.group(1)] = {self.cstruct.consts[k]: v for k, v in d.items()}
539531

540532
def parse(self, data: str) -> None:
541533
self._constants(data)
@@ -545,20 +537,20 @@ def parse(self, data: str) -> None:
545537

546538

547539
class Token:
548-
__slots__ = ("token", "value", "match")
540+
__slots__ = ("match", "token", "value")
549541

550542
def __init__(self, token: str, value: str, match: re.Match):
551543
self.token = token
552544
self.value = value
553545
self.match = match
554546

555-
def __eq__(self, other):
547+
def __eq__(self, other: object) -> bool:
556548
if isinstance(other, Token):
557549
other = other.token
558550

559551
return self.token == other
560552

561-
def __ne__(self, other):
553+
def __ne__(self, other: object) -> bool:
562554
return not self == other
563555

564556
def __repr__(self):
@@ -571,7 +563,7 @@ def __init__(self):
571563
self.lookup: dict[str, str] = {}
572564
self.patterns: dict[str, re.Pattern] = {}
573565

574-
def __getattr__(self, attr: str):
566+
def __getattr__(self, attr: str) -> str | Any:
575567
try:
576568
return self.lookup[attr]
577569
except AttributeError:

dissect/cstruct/types/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from dissect.cstruct.types.wchar import Wchar, WcharArray
1212

1313
__all__ = [
14+
"LEB128",
1415
"Array",
1516
"ArrayMetaType",
1617
"BaseType",
@@ -20,7 +21,6 @@
2021
"Field",
2122
"Flag",
2223
"Int",
23-
"LEB128",
2424
"MetaType",
2525
"Packed",
2626
"Pointer",

0 commit comments

Comments
 (0)