Coverage for pysource_minimize/__main__.py: 0%
44 statements
« prev ^ index » next coverage.py v6.5.0, created at 2024-02-21 22:00 +0100
« prev ^ index » next coverage.py v6.5.0, created at 2024-02-21 22:00 +0100
1import pathlib
2import subprocess as sp
3import sys
5import click
6from rich.console import Console
7from rich.progress import Progress
8from rich.syntax import Syntax
10from ._minimize import minimize
13@click.command()
14@click.option(
15 "--file", required=True, type=click.Path(exists=True), help="file to minimize"
16)
17@click.option(
18 "--track",
19 required=True,
20 help="string which should be in the stdout/stderr of the command during minimization",
21)
22@click.option(
23 "write_back", "-w", "--write", is_flag=True, help="write minimized output to file"
24)
25@click.argument("cmd", nargs=-1)
26def main(cmd, file, track, write_back):
27 file = pathlib.Path(file)
29 first_result = sp.run(cmd, capture_output=True)
31 if track not in (first_result.stdout.decode() + first_result.stderr.decode()):
32 print("I dont know what you want to minimize for.")
33 print(
34 f"'{track}' is not a string which in the stdout/stderr of '{' '.join(cmd)}'"
35 )
36 sys.exit(1)
38 def checker(source):
39 file.write_text(source)
41 result = sp.run(cmd, capture_output=True)
43 if track not in (result.stdout.decode() + result.stderr.decode()):
44 return False
46 return True
48 original_source = file.read_text()
50 with Progress() as progress:
51 task = progress.add_task("minimize")
53 def update(current, total):
54 progress.update(task, completed=total - current, total=total)
56 new_source = minimize(original_source, checker, progress_callback=update)
58 if write_back:
59 file.write_text(new_source)
60 else:
61 file.write_text(original_source)
63 console = Console()
65 console.print()
66 console.print("The minimized code is:")
67 console.print(Syntax(new_source, "python", line_numbers=True))
68 console.print()
70 if not write_back:
71 console.print(
72 "The file is not changed. Use -w to write the minimized version back to the file."
73 )
76if __name__ == "__main__":
77 main()