Skip to content

Commit

Permalink
Adapt code to ruff's T20 rules
Browse files Browse the repository at this point in the history
  • Loading branch information
treiher committed Aug 15, 2023
1 parent 7e8e69c commit 5f9ff4b
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 49 deletions.
8 changes: 4 additions & 4 deletions examples/apps/ping/ping.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def icmp_checksum(message: bytes, **kwargs: object) -> int:
def ping(target: str) -> None:
target_ip = socket.gethostbyname(target)

print(f"PING {target} ({target_ip})")
print(f"PING {target} ({target_ip})") # noqa: T201

sock_out = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
sock_in = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
Expand Down Expand Up @@ -79,13 +79,13 @@ def ping(target: str) -> None:
continue

reply_seq = str(reply.get("Sequence_Number"))
print(
print( # noqa: T201
f"{int(reply.size) // 8} bytes from {packet_src}: icmp_seq={reply_seq}",
flush=True,
)

if reply.get("Data") != ICMP_DATA:
print("mismatch between sent and received data")
print("mismatch between sent and received data") # noqa: T201

time.sleep(1)
receiving = False
Expand All @@ -94,7 +94,7 @@ def ping(target: str) -> None:
time.sleep(1)
receiving = False
else:
print(e)
print(e) # noqa: T201
sys.exit(1)


Expand Down
4 changes: 2 additions & 2 deletions rflx/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def main( # noqa: PLR0915
args = parser.parse_args(argv[1:])

if args.version:
print(version())
print(version()) # noqa: T201
return 0

if not args.subcommand:
Expand Down Expand Up @@ -517,7 +517,7 @@ def setup(args: argparse.Namespace) -> None:
plugins_dir = args.gnat_studio_dir / "plug-ins"
if not plugins_dir.exists():
plugins_dir.mkdir(parents=True, exist_ok=True)
print(f'Installing RecordFlux plugin into "{plugins_dir}"')
print(f'Installing RecordFlux plugin into "{plugins_dir}"') # noqa: T201
shutil.copy(Path(gnatstudio_dir) / "recordflux.py", plugins_dir)


Expand Down
6 changes: 3 additions & 3 deletions rflx/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def propagate(self) -> None:
if self.errors:
raise self
if self._messages:
print(self)
print(self) # noqa: T201
self._messages = deque()

def fail(
Expand Down Expand Up @@ -241,12 +241,12 @@ def warn(
subsystem: Subsystem,
location: Optional[Location] = None,
) -> None:
print(RecordFluxError([(message, subsystem, Severity.WARNING, location)]))
print(RecordFluxError([(message, subsystem, Severity.WARNING, location)])) # noqa: T201


def info(
message: str,
subsystem: Subsystem,
location: Optional[Location] = None,
) -> None:
print(RecordFluxError([(message, subsystem, Severity.INFO, location)]))
print(RecordFluxError([(message, subsystem, Severity.INFO, location)])) # noqa: T201
42 changes: 21 additions & 21 deletions rflx/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,39 +375,39 @@ def print_coverage(self) -> None:
self._print_link_coverage()

def _print_coverage_overview(self) -> None:
print("\n")
print("-" * 80)
print(f"{'RecordFlux Validation Coverage Report' : ^80}".rstrip())
print(f"Directory: {Path.cwd()}")
print("-" * 80)
print(f"{'File' : <40} {'Links' : >10} {'Used' : >10} {'Coverage' : >15}")
print("\n") # noqa: T201
print("-" * 80) # noqa: T201
print(f"{'RecordFlux Validation Coverage Report' : ^80}".rstrip()) # noqa: T201
print(f"Directory: {Path.cwd()}") # noqa: T201
print("-" * 80) # noqa: T201
print(f"{'File' : <40} {'Links' : >10} {'Used' : >10} {'Coverage' : >15}") # noqa: T201
for file in self._spec_files:
file_links = self.file_total_links(file)
file_covered_links = self.file_covered_links(file)
print(
print( # noqa: T201
f"{file : <40} {file_links : >10} {file_covered_links : >10} "
f"{file_covered_links / file_links :>15.2%}",
)
print("-" * 80)
print(
print("-" * 80) # noqa: T201
print( # noqa: T201
f"{'TOTAL' : <40} {self.total_links: >10} {self.total_covered_links : >10} "
f"{self.total_covered_links / self.total_links :15.2%}",
)
print("-" * 80)
print("-" * 80) # noqa: T201

def _print_link_coverage(self) -> None:
print("\n")
print("=" * 80)
print(f"{'Uncovered Links' : ^80}".rstrip())
print("=" * 80)
print("\n") # noqa: T201
print("=" * 80) # noqa: T201
print(f"{'Uncovered Links' : ^80}".rstrip()) # noqa: T201
print("=" * 80) # noqa: T201
for file in self._spec_files:
uncovered_links = self.file_uncovered_links(file)
if len(uncovered_links) != 0:
print("\n")
print(f"{file : ^80}".rstrip())
print("-" * 80)
print("\n") # noqa: T201
print(f"{file : ^80}".rstrip()) # noqa: T201
print("-" * 80) # noqa: T201
for link in sorted(uncovered_links, key=lambda x: str(x.location)):
print(
print( # noqa: T201
f"{link.location!s:<17}"
f": missing link {link.source.name:^25} -> {link.target.name:^20}".rstrip(),
)
Expand Down Expand Up @@ -440,15 +440,15 @@ def as_json(self) -> dict[str, object]:

def print_console_output(self) -> None:
if self.validation_success:
print(f"{self.message_path!s:<80} PASSED")
print(f"{self.message_path!s:<80} PASSED") # noqa: T201
else:
print(
print( # noqa: T201
f"{self.message_path!s:<80} FAILED\n"
f"provided as: {self.valid_original_message}\t "
f"recognized as: {self.valid_parser_result}",
)
if self.parser_error is not None:
print(self.parser_error)
print(self.parser_error) # noqa: T201


class OutputWriter:
Expand Down
8 changes: 4 additions & 4 deletions tools/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

class Benchmark:
def __init__(self, specdir: Path) -> None:
print("Loading...")
print("Loading...") # noqa: T201
start = perf_counter()
self.__pyrflx = PyRFLX.from_specs(
[str(specdir / "ipv4.rflx"), str(specdir / "icmp.rflx")],
Expand All @@ -23,7 +23,7 @@ def __init__(self, specdir: Path) -> None:
)
self.__ipv4 = self.__pyrflx.package("IPv4")
self.__icmp = self.__pyrflx.package("ICMP")
print(f"Loaded in {perf_counter() - start} seconds")
print(f"Loaded in {perf_counter() - start} seconds") # noqa: T201

def generate(self, count: int = 2**16) -> Generator[bytes, None, None]:
if count > 2**16:
Expand Down Expand Up @@ -63,7 +63,7 @@ def run(self) -> None:
for _ in tqdm(self.generate()):
if i % 500 == 0:
if perf_counter() - start > 1:
print("Performance < 500it/s, stopping")
print("Performance < 500it/s, stopping") # noqa: T201
sys.exit(1)
start = perf_counter()
i += 1
Expand All @@ -77,7 +77,7 @@ def run(self) -> None:
args = parser.parse_args(sys.argv[1:])
benchmark = Benchmark(args.specdir)
if args.profile:
print("Profiling...")
print("Profiling...") # noqa: T201

def run() -> None:
for _ in benchmark.generate(20):
Expand Down
6 changes: 4 additions & 2 deletions tools/check_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ def check_dependencies() -> bool:
try:
installed_version = version(r.name)
if installed_version not in r.specifier:
print(f"{r.name} has version {installed_version}, should be {r.specifier}")
print( # noqa: T201
f"{r.name} has version {installed_version}, should be {r.specifier}",
)
result = False
except PackageNotFoundError:
print(f"{r.name} not found")
print(f"{r.name} not found") # noqa: T201
result = False

return result
Expand Down
22 changes: 12 additions & 10 deletions tools/check_requirements.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def parse_requirements(requirements_file: Path) -> tuple[list[Requirement], bool
if req.identifier in requirements or any(
identifier == req.identifier for identifier in requirements
):
print(f'duplicate requirement "{req.identifier}"')
print(f'duplicate requirement "{req.identifier}"') # noqa: T201
error = True
requirements[req.identifier] = req

Expand All @@ -125,10 +125,12 @@ def parse_requirements(requirements_file: Path) -> tuple[list[Requirement], bool
if parent in requirements:
requirements[parent].requirements.append(req)
else:
print(f'missing requirement "{parent}" for "{req.identifier}"')
print( # noqa: T201
f'missing requirement "{parent}" for "{req.identifier}"',
)
error = True
else:
print(f'ignored "{l}"')
print(f'ignored "{l}"') # noqa: T201

return (list(requirements.values()), error)

Expand All @@ -153,7 +155,7 @@ def check_references(requirements: Sequence[Requirement], references: Sequence[s
if not req.requirements:
req.referenced = True
else:
print(f'meta requirement "{req.identifier}" must not be referenced')
print(f'meta requirement "{req.identifier}" must not be referenced') # noqa: T201
error = True

undefined = [
Expand All @@ -163,29 +165,29 @@ def check_references(requirements: Sequence[Requirement], references: Sequence[s
]
if undefined:
for ref in undefined:
print(f'reference to undefined requirement "{ref}"')
print(f'reference to undefined requirement "{ref}"') # noqa: T201
error = True

for r in [r for r in requirements if not r.referenced and not r.requirements]:
print(f'unreferenced requirement "{r.identifier}"')
print(f'unreferenced requirement "{r.identifier}"') # noqa: T201
error = True

return error


def print_checkbox_list(requirements: Sequence[Requirement]) -> None:
print()
print() # noqa: T201
for r in sorted(requirements):
indentation = " " * r.identifier.count(ID_SEPARATOR)
status = "x" if r.referenced else " "
print(f"{indentation}- [{status}] {r.description} ({r.identifier})")
print()
print(f"{indentation}- [{status}] {r.description} ({r.identifier})") # noqa: T201
print() # noqa: T201


def print_statistics(requirements: Sequence[Requirement]) -> None:
total = len(requirements)
referenced = len({r for r in requirements if r.referenced})
print(f"{referenced} / {total} ({referenced / total * 100:.2f} %)")
print(f"{referenced} / {total} ({referenced / total * 100:.2f} %)") # noqa: T201


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion tools/extract_packets.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def main(argv: Sequence[str]) -> Union[bool, str]:
prefix = args.pcap.stem.replace(" ", "_")
number = str(i).zfill(ceil(log(len(pkts)) / log(10)))
filename = args.output / f"{prefix}_{number}.raw"
print(f"Creating {filename}")
print(f"Creating {filename}") # noqa: T201
Path(filename).write_bytes(bytes(p))
hexdump(bytes(p))

Expand Down
2 changes: 1 addition & 1 deletion tools/generate_spark_test_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def generate(feature_test: Path) -> None:

def remove_ada_files(directory: Path) -> None:
for f in directory.glob("*.ad?"):
print(f"Removing {f}")
print(f"Removing {f}") # noqa: T201
f.unlink()


Expand Down
2 changes: 1 addition & 1 deletion tools/generate_spark_test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def create_test_runner(tests: Sequence[str], directory: pathlib.Path) -> None:
procedure_name = f"Test_{test}" if test else "Test"
test_cases = "\n".join(f" Result.all.Add_Test (new RFLX.{t}_Tests.Test);" for t in tests)

print(f"Create {filename}")
print(f"Create {filename}") # noqa: T201

filename.write_text(
f"""
Expand Down

0 comments on commit 5f9ff4b

Please sign in to comment.