-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23-code-modernization.py
More file actions
178 lines (141 loc) · 5.13 KB
/
23-code-modernization.py
File metadata and controls
178 lines (141 loc) · 5.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""23 Code Modernization - Modernize legacy Python code.
A real-world example of an agent that modernizes legacy Python code by:
- Identifying outdated patterns (e.g., old string formatting, deprecated imports)
- Suggesting modern alternatives
- Creating updated versions of files
- Generating migration guides
Usage:
export AUTOHAND_PROVIDER=openrouter
export AUTOHAND_API_KEY=your-key-here
python 23-code-modernization.py
"""
import os
import tempfile
from pathlib import Path
from autohand_agents import Agent, Runner, Tool
def create_legacy_project(tmpdir: Path) -> None:
"""Create a sample legacy Python project with outdated patterns."""
# Legacy module with outdated patterns
(tmpdir / "legacy_utils.py").write_text("""\
# Legacy utility functions - needs modernization
import sys
import os
from typing import List, Dict
def process_data(data_list):
# Old string formatting
result = "Processing %d items: %s" % (len(data_list), str(data_list))
# Using os.path instead of pathlib
config_path = os.path.join(os.getcwd(), "config.txt")
# Old exception handling
try:
with open(config_path, 'r') as f:
config = f.read()
except IOError as e:
print("Error reading config: %s" % e.message)
config = ""
# Using list comprehension where map would be better
numbers = [1, 2, 3, 4, 5]
doubled = [x * 2 for x in numbers]
# Deprecated type hints
def format_output(items: List[str]) -> Dict[str, str]:
output = {}
for i, item in enumerate(items):
output["item_%d" % i] = item.upper()
return output
return result, config, doubled, format_output(data_list)
class OldStyleClass:
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
""")
# Legacy test file
(tmpdir / "test_legacy.py").write_text("""\
import unittest
import legacy_utils
class TestLegacyUtils(unittest.TestCase):
def test_process_data(self):
data = ["a", "b", "c"]
result = legacy_utils.process_data(data)
self.assertIsNotNone(result)
def test_old_class(self):
obj = legacy_utils.OldStyleClass("test")
self.assertEqual(obj.get_name(), "test")
if __name__ == "__main__":
unittest.main()
""")
# Requirements file with old versions
(tmpdir / "requirements.txt").write_text("""\
Django==2.2.0
requests==2.20.0
numpy==1.18.0
""")
def main():
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir = Path(tmpdir)
# Create legacy project
create_legacy_project(tmpdir)
print(f"Created legacy project in: {tmpdir}")
# Code modernization agent
modernizer = Agent(
name="Code Modernizer",
instructions="""You are a Python code modernization expert. Your task:
1. Analyze legacy Python code for outdated patterns:
- Old string formatting (% operator) -> f-strings
- os.path -> pathlib
- Old exception handling patterns
- Verbose code that can be simplified
- Deprecated type hints
- Old-style classes without proper properties
2. Create modernized versions with:
- f-string formatting
- pathlib for file operations
- Modern exception handling
- Type hints with proper generics
- Dataclasses where appropriate
- Context managers
3. Generate a migration guide explaining changes
4. Update requirements.txt with modern versions
Use read_file to examine code, write_file to create modernized versions,
and edit_file to make targeted improvements. Be thorough but practical.""",
tools=[
Tool.READ_FILE,
Tool.WRITE_FILE,
Tool.EDIT_FILE,
Tool.GLOB,
Tool.BASH
],
max_turns=20,
)
# Run modernization
old_cwd = os.getcwd()
os.chdir(tmpdir)
try:
result = Runner.run_sync(
modernizer,
"""Modernize this legacy Python project:
1. First, glob for all Python files and read each one
2. Identify outdated patterns and create modernized versions
3. Create a MIGRATION.md file explaining all changes made
4. Update requirements.txt with current package versions
5. Test that the modernized code still works with python -m pytest
Focus on practical improvements that maintain functionality while modernizing style."""
)
print("\n" + "="*60)
print("CODE MODERNIZATION RESULTS")
print("="*60)
print(result.final_output)
# Show created files
print("\n" + "="*60)
print("FILES CREATED/MODIFIED")
print("="*60)
for file in sorted(tmpdir.rglob("*")):
if file.is_file() and file.suffix in ['.py', '.md', '.txt']:
rel_path = file.relative_to(tmpdir)
print(f" {rel_path}")
finally:
os.chdir(old_cwd)
if __name__ == "__main__":
main()