@@ -41,60 +41,65 @@ def add_helpful_comment(filepath):
4141 with open (filepath , 'r' ) as f :
4242 lines = f .readlines ()
4343
44- if len (lines ) < 5 :
44+ if len (lines ) < 10 :
4545 return False
4646
47- # Find a good spot to add comment (not in docstrings)
48- indices = [i for i , line in enumerate (lines ) if line .strip ().startswith ('def ' ) and i > 0 ]
47+ # Find functions or classes
48+ indices = []
49+ for i , line in enumerate (lines ):
50+ if (line .strip ().startswith ('def ' ) or line .strip ().startswith ('class ' )) and i > 0 :
51+ # Check if there's already a comment above
52+ if i > 0 and not lines [i - 1 ].strip ().startswith ('#' ):
53+ indices .append (i )
54+
4955 if not indices :
5056 return False
5157
5258 idx = random .choice (indices )
5359
54- # Check if there's already a comment
55- if idx > 0 and lines [idx - 1 ].strip ().startswith ('#' ):
56- return False
57-
58- comment = "# " + random .choice ([
59- "Handle edge case" ,
60- "Validate input before processing" ,
61- "Clean up resources" ,
62- "Better error handling needed here" ,
63- ])
60+ comments = [
61+ "# Validate input before processing" ,
62+ "# Handle edge case" ,
63+ "# Clean up resources" ,
64+ "# Process result" ,
65+ ]
6466
65- lines .insert (idx , comment + '\n ' )
67+ comment = random .choice (comments ) + '\n '
68+ lines .insert (idx , comment )
6669
6770 with open (filepath , 'w' ) as f :
6871 f .writelines (lines )
6972
7073 return True
71- except Exception :
74+ except Exception as e :
7275 return False
7376
7477
7578def improve_error_message (filepath ):
7679 """Improve an error message to be more descriptive"""
7780 try :
7881 with open (filepath , 'r' ) as f :
79- content = f .read ()
80-
81- # Look for generic error messages
82- improvements = {
83- 'Error occurred' : 'Operation failed' ,
84- 'Failed' : 'Request processing failed' ,
85- 'Invalid' : 'Invalid request parameters' ,
86- }
82+ lines = f .readlines ()
8783
8884 changed = False
89- for old , new in improvements .items ():
90- if old in content and random .random () > 0.7 :
91- content = content .replace (old , new , 1 )
92- changed = True
85+ improvements = [
86+ ('message_data="Database Error"' , 'message_data="Database operation failed"' ),
87+ ('message_data="Error"' , 'message_data="An error occurred"' ),
88+ ('"Unknown error caused"' , '"An unexpected error occurred"' ),
89+ ]
90+
91+ for i , line in enumerate (lines ):
92+ for old , new in improvements :
93+ if old in line :
94+ lines [i ] = line .replace (old , new , 1 )
95+ changed = True
96+ break
97+ if changed :
9398 break
9499
95100 if changed :
96101 with open (filepath , 'w' ) as f :
97- f .write ( content )
102+ f .writelines ( lines )
98103 return True
99104 return False
100105 except Exception :
@@ -105,24 +110,23 @@ def update_docstring(filepath):
105110 """Add or update a docstring"""
106111 try :
107112 with open (filepath , 'r' ) as f :
108- content = f .read ()
109-
110- # Find functions without docstrings
111- if 'def ' in content and '"""' not in content [:500 ]:
112- # Add a simple docstring to first function
113- lines = content .split ('\n ' )
114- for i , line in enumerate (lines ):
115- if line .strip ().startswith ('def ' ) and i + 1 < len (lines ):
116- if not lines [i + 1 ].strip ().startswith ('"""' ):
117- docstring = ' """' + random .choice ([
118- 'Process the request' ,
119- 'Handle user input' ,
120- 'Validate data' ,
121- ]) + '"""'
122- lines .insert (i + 1 , docstring )
123- with open (filepath , 'w' ) as f :
124- f .write ('\n ' .join (lines ))
125- return True
113+ lines = f .readlines ()
114+
115+ # Find first function without docstring
116+ for i , line in enumerate (lines ):
117+ if line .strip ().startswith ('def ' ):
118+ # Check if next line is docstring
119+ if i + 1 < len (lines ) and not lines [i + 1 ].strip ().startswith ('"""' ):
120+ indent = len (line ) - len (line .lstrip ())
121+ docstring = ' ' * indent + ' """' + random .choice ([
122+ 'Process request' ,
123+ 'Handle input' ,
124+ 'Validate data' ,
125+ ]) + '"""\n '
126+ lines .insert (i + 1 , docstring )
127+ with open (filepath , 'w' ) as f :
128+ f .writelines (lines )
129+ return True
126130 return False
127131 except Exception :
128132 return False
@@ -134,15 +138,23 @@ def improve_logging(filepath):
134138 with open (filepath , 'r' ) as f :
135139 lines = f .readlines ()
136140
137- # Find error handling blocks
141+ # Skip if this is a logger file
142+ if 'logger' in filepath .lower () or 'logging' in filepath .lower ():
143+ return False
144+
145+ # Check if logger is imported
146+ has_logger = any ('logger' in line .lower () for line in lines [:20 ])
147+ if not has_logger :
148+ return False
149+
150+ # Find exception handling without logging
138151 for i , line in enumerate (lines ):
139- if 'except' in line and i + 2 < len (lines ):
140- if 'logger' in filepath .lower () or 'logging' in filepath .lower ():
141- continue
142- # Add logging if not present
143- if 'logger.' not in lines [i + 1 ] and 'logger.' not in lines [i + 2 ]:
152+ if 'except' in line and 'Exception' in line and i + 3 < len (lines ):
153+ # Check if logging exists in next few lines
154+ has_log = any ('logger.' in lines [j ] for j in range (i + 1 , min (i + 5 , len (lines ))))
155+ if not has_log :
144156 indent = len (line ) - len (line .lstrip ())
145- log_line = ' ' * (indent + 4 ) + 'logger.error(f"Error: {str(e)}")\n '
157+ log_line = ' ' * (indent + 4 ) + 'logger.error(f"Error processing request : {str(e)}")\n '
146158 lines .insert (i + 1 , log_line )
147159 with open (filepath , 'w' ) as f :
148160 f .writelines (lines )
@@ -156,21 +168,27 @@ def make_change():
156168 """Make a small, realistic change"""
157169 filepath = get_random_file ()
158170 if not filepath :
159- return False , None
171+ return False , None , None
160172
161- activity = random . choice ( ACTIVITY_TYPES )
162- success = False
173+ # Try different activities until one works
174+ activities = random . sample ( ACTIVITY_TYPES , len ( ACTIVITY_TYPES ))
163175
164- if activity == "code_comment" :
165- success = add_helpful_comment (filepath )
166- elif activity == "error_handling" :
167- success = improve_error_message (filepath )
168- elif activity == "doc_update" :
169- success = update_docstring (filepath )
170- elif activity == "log_improvement" :
171- success = improve_logging (filepath )
176+ for activity in activities :
177+ if activity == "code_comment" :
178+ success = add_helpful_comment (filepath )
179+ elif activity == "error_handling" :
180+ success = improve_error_message (filepath )
181+ elif activity == "doc_update" :
182+ success = update_docstring (filepath )
183+ elif activity == "log_improvement" :
184+ success = improve_logging (filepath )
185+ else :
186+ continue
187+
188+ if success :
189+ return True , filepath , activity
172190
173- return success , filepath
191+ return False , None , None
174192
175193
176194def generate_commit_message (filepath , activity_type ):
@@ -226,14 +244,13 @@ def main():
226244 print ("Making a small improvement..." )
227245
228246 # Make a change
229- success , filepath = make_change ()
247+ success , filepath , activity = make_change ()
230248
231249 if not success or not filepath :
232250 print ("No changes made this time" )
233251 return 0
234252
235253 # Generate commit message
236- activity = random .choice (ACTIVITY_TYPES )
237254 message = generate_commit_message (filepath , activity )
238255
239256 print (f"Modified: { filepath } " )
0 commit comments