1+ #!/usr/bin/env python3
2+
3+ """
4+ This script is used to add human-readable comments of hex strings in protoscope syntext.
5+ Before you start, make sure to install [protoscope](https://github.com/protocolbuffers/protoscope).
6+
7+ NO WARRANTY. Double check before commit.
8+
9+ Usage: hex_proto.py <path_to_kotlin_file>
10+ """
11+
12+ import re
13+ import subprocess
14+ import sys
15+
16+ # Check input args
17+ if len (sys .argv ) != 2 :
18+ print ("Usage: python hex_proto.py <path_to_kotlin_file>" )
19+ sys .exit (1 )
20+
21+ file_path = sys .argv [1 ]
22+
23+ # Regexp for hex string
24+ hex_string_pattern = re .compile (r'\"(0x)?([0-9a-fA-F]+)\"' )
25+
26+ # Regexp for existing comment
27+ existing_comment_pattern = re .compile (r'/\*\*.*?\*/' , re .DOTALL )
28+
29+ with open (file_path , 'r' ) as file :
30+ lines = file .readlines ()
31+
32+ # Lines to be written back
33+ updated_lines = []
34+
35+ inside_comment_block = False
36+ potential_comment_block = []
37+
38+ for i , line in enumerate (lines ):
39+ # Check if we are inside a comment block
40+ if line .strip ().startswith ("/*" ):
41+ inside_comment_block = True
42+ potential_comment_block = [line ]
43+ continue
44+ elif inside_comment_block :
45+ potential_comment_block .append (line )
46+ # Check if we are at the end of the comment block
47+ if line .strip ().endswith ("*/" ):
48+ inside_comment_block = False
49+ # Check if the next line is a hex string
50+ if i + 1 < len (lines ) and not hex_string_pattern .search (lines [i + 1 ]):
51+ updated_lines .extend (potential_comment_block )
52+ potential_comment_block = []
53+ continue
54+
55+ hex_match = hex_string_pattern .search (line )
56+ if hex_match :
57+ indent = len (line ) - len (line .lstrip ())
58+ indent_space = ' ' * indent
59+
60+ # Hex to protoscope
61+ hex_string = hex_match .group (2 )
62+ binary_data = bytes .fromhex (hex_string )
63+ result = subprocess .run (['protoscope' , '-explicit-wire-types' ], input = binary_data , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
64+ if result .returncode == 0 :
65+ # Build comment string
66+ comment = result .stdout .decode ('utf-8' ).strip ().replace ('\n ' , f'\n { indent_space } * ' )
67+ new_comment_block = f'{ indent_space } /**\n { indent_space } * { comment } \n { indent_space } */\n '
68+ updated_lines .append (new_comment_block )
69+ updated_lines .append (line )
70+ else :
71+ updated_lines .append (line )
72+
73+ with open (file_path , 'w' ) as file :
74+ file .writelines (updated_lines )
75+
76+ print ("Hex strings have been processed and comments have been added or replaced in the Kotlin file." )
0 commit comments