File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Fix absolute imports in *_pb2_grpc.py files.
3+ Example:
4+ import a2a_pb2 as a2a__pb2
5+ from . import a2a_pb2 as a2a__pb2
6+ """
7+
8+ import re
9+ import sys
10+
11+ from pathlib import Path
12+
13+
14+ def process_generated_code (src_folder : str = 'src/a2a/grpc' ):
15+ """Post processor for the generated code."""
16+ dir_path = Path (src_folder )
17+ print (dir_path )
18+ if not dir_path .is_dir ():
19+ print ('Source folder not found' )
20+ sys .exit (1 )
21+
22+ grpc_pattern = '**/*_pb2_grpc.py'
23+ files = dir_path .glob (grpc_pattern )
24+
25+ for file in files :
26+ print (f'Processing { file } ' )
27+ try :
28+ with file .open ('r' , encoding = 'utf-8' ) as f :
29+ src_content = f .read ()
30+
31+ # Change import a2a_pb2 as a2a__pb2
32+ import_pattern = r'^import (\w+_pb2) as (\w+__pb2)$'
33+ # to from . import a2a_pb2 as a2a__pb2
34+ replacement_pattern = r'from . import \1 as \2'
35+
36+ fixed_src_content = re .sub (
37+ import_pattern ,
38+ replacement_pattern ,
39+ src_content ,
40+ flags = re .MULTILINE ,
41+ )
42+
43+ if fixed_src_content != src_content :
44+ with file .open ('w' , encoding = 'utf-8' ) as f :
45+ f .write (fixed_src_content )
46+ print ('Imports fixed' )
47+ else :
48+ print ('No changes needed' )
49+
50+ except Exception as e :
51+ print (f'Error processing file { file } : { e } ' )
52+ sys .exit (1 )
53+
54+
55+ if __name__ == '__main__' :
56+ process_generated_code ()
You can’t perform that action at this time.
0 commit comments