You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Codegen enables you to create reusable code transformations using Python functions decorated with `@codegen.function`. These codemods can be shared, versioned, and run by your team.
9
+
10
+
## Creating Codemods
11
+
12
+
The easiest way to create a new codemod is using the CLI [create](/cli/create) command:
13
+
14
+
```bash
15
+
codegen create rename-function
16
+
```
17
+
18
+
This creates a new codemod in your `.codegen/codemods` directory:
19
+
20
+
```python
21
+
import codegen
22
+
from codegen import Codebase
23
+
24
+
@codegen.function("rename-function")
25
+
defrun(codebase: Codebase):
26
+
"""Add a description of what this codemod does."""
27
+
# Add your code here
28
+
pass
29
+
```
30
+
31
+
<Note>
32
+
Codemods are stored in `.codegen/codemods/name/name.py` and are tracked in Git for easy sharing.
33
+
</Note>
34
+
35
+
### AI-Powered Generation with `-d`
36
+
37
+
You can use AI to generate an initial implementation by providing a description:
38
+
39
+
```bash
40
+
codegen create rename-function -d "Rename the getUserData function to fetchUserProfile"
41
+
```
42
+
43
+
This will:
44
+
1. Generate an implementation based on your description
45
+
2. Create a custom system prompt that you can provide to an IDE chat assistant (learn more about [working with AI](/introduction/work-with-ai))
46
+
3. Place both files in the codemod directory
47
+
48
+
## Running Codemods
49
+
50
+
Once created, run your codemod using:
51
+
52
+
```bash
53
+
codegen run rename-function
54
+
```
55
+
56
+
The execution flow:
57
+
1. Codegen parses your codebase into a graph representation
58
+
2. Your codemod function is executed against this graph
59
+
3. Changes are tracked and applied to your filesystem
60
+
4. A diff preview shows what changed
61
+
62
+
63
+
## Codemod Structure
64
+
65
+
A codemod consists of three main parts:
66
+
67
+
1. The `@codegen.function` decorator that names your codemod
68
+
2. A `run` function that takes a `Codebase` parameter
69
+
3. Your transformation logic using the Codebase API
70
+
71
+
```python
72
+
import codegen
73
+
from codegen import Codebase
74
+
75
+
@codegen.function("update-imports")
76
+
defrun(codebase: Codebase):
77
+
"""Update import statements to use new package names."""
78
+
forfilein codebase.files:
79
+
for imp infile.imports:
80
+
if imp.module =="old_package":
81
+
imp.rename("new_package")
82
+
codebase.commit()
83
+
```
84
+
85
+
## Arguments
86
+
87
+
Codemods can accept arguments using Pydantic models:
0 commit comments