Template codemods allow you to create reusable code modifications that can be customized with different inputs each time they run. This is particularly useful when you want to share a codemod that others can run with their own parameters.

Creating Template Codemods

To create a template codemod, you can use the TEMPLATE_ARGS dictionary from the context object. This allows you to define parameters that users can customize when running the codemod.

# Access template arguments from context
flag_name = context.TEMPLATE_ARGS.get('FLAG_NAME').upper()
target_directory = context.TEMPLATE_ARGS.get('TARGET_DIR')

# Use the template arguments in your codemod
for file in codebase.files:
    if file.extension == '.py' and target_directory in file.filepath:
        flag = codebase.flag_instance(file)
        if codebase.should_fix(flag):
            file.insert_before(f'# Feature flag: {flag_name}')

Template Parameters

Template parameters are defined using the TEMPLATE_ARGS dictionary.

Currently the support types for parameter values are:

  • String
  • String List

Running Template Codemods

When running a template codemod, you’ll need to provide values for the template parameters. This can be done through the web interface:

  1. Select your template codemod
  2. Look for the “Template Arguments” section in the right panel
  3. Fill in the values for each parameter
  4. Click “Run Codemod” to execute with your custom inputs

Best Practices

When creating template codemods:

  • Provide clear documentation for each template parameter
  • Validate template inputs before using them
  • Use descriptive parameter names that indicate their purpose
  • Consider adding example values in the documentation

Template codemods make your modifications more flexible and reusable across different scenarios. By following these guidelines, you can create robust and user-friendly template codemods that others can easily customize for their needs.

Was this page helpful?