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

1import pathlib 

2import subprocess as sp 

3import sys 

4 

5import click 

6from rich.console import Console 

7from rich.progress import Progress 

8from rich.syntax import Syntax 

9 

10from ._minimize import minimize 

11 

12 

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) 

28 

29 first_result = sp.run(cmd, capture_output=True) 

30 

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) 

37 

38 def checker(source): 

39 file.write_text(source) 

40 

41 result = sp.run(cmd, capture_output=True) 

42 

43 if track not in (result.stdout.decode() + result.stderr.decode()): 

44 return False 

45 

46 return True 

47 

48 original_source = file.read_text() 

49 

50 with Progress() as progress: 

51 task = progress.add_task("minimize") 

52 

53 def update(current, total): 

54 progress.update(task, completed=total - current, total=total) 

55 

56 new_source = minimize(original_source, checker, progress_callback=update) 

57 

58 if write_back: 

59 file.write_text(new_source) 

60 else: 

61 file.write_text(original_source) 

62 

63 console = Console() 

64 

65 console.print() 

66 console.print("The minimized code is:") 

67 console.print(Syntax(new_source, "python", line_numbers=True)) 

68 console.print() 

69 

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 ) 

74 

75 

76if __name__ == "__main__": 

77 main()