1+ import ast
2+
3+
14def insert_code_after_tag (file_path , tag , code_to_insert , next_line = False ):
25 if next_line :
36 code_to_insert = ['\n ' ] + code_to_insert
@@ -16,3 +19,43 @@ def insert_code_after_tag(file_path, tag, code_to_insert, next_line=False):
1619
1720 with open (file_path , 'w' ) as file :
1821 file .writelines (lines )
22+
23+
24+ def insert_after_tasks (file_path , code_to_insert ):
25+ with open (file_path , 'r' ) as file :
26+ content = file .read ()
27+
28+ module = ast .parse (content )
29+
30+ # Track the last task function and its line number
31+ last_task_end = None
32+ last_task_start = None
33+ for node in ast .walk (module ):
34+ if isinstance (node , ast .FunctionDef ) and \
35+ any (isinstance (deco , ast .Name ) and deco .id == 'task' for deco in node .decorator_list ):
36+ last_task_end = node .end_lineno
37+ last_task_start = node .lineno
38+
39+ if last_task_end is not None :
40+ lines = content .split ('\n ' )
41+
42+ # Get the indentation of the task function
43+ task_line = lines [last_task_start - 1 ] # -1 for 0-based indexing
44+ indentation = ''
45+ for char in task_line :
46+ if char in [' ' , '\t ' ]:
47+ indentation += char
48+ else :
49+ break
50+
51+ # Add the same indentation to each line of the inserted code
52+ indented_code = '\n ' + '\n ' .join (indentation + line for line in code_to_insert )
53+
54+ lines .insert (last_task_end , indented_code )
55+ content = '\n ' .join (lines )
56+
57+ with open (file_path , 'w' ) as file :
58+ file .write (content )
59+ return True
60+ return False
61+
0 commit comments