Organize your Codebase
Safely and systematically move symbols with Codegen
Codegen’s GraphSitter library provides a powerful set of tools for deterministically moving code safely and efficiently. This guide will walk you through the basics of moving code with GraphSitter.
Common use cases include:
Basic Symbol Movement
To move a symbol from one file to another, you can use the move_to_file method.
This will move my_function
to path/to/dst/location.py
, safely updating all references to it in the process.
Updating Imports
After moving a symbol, you may need to update imports throughout your codebase. GraphSitter offers two strategies for this:
- Update All Imports: This strategy updates all imports across the codebase to reflect the new location of the symbol.
- Add Back Edge: This strategy adds an import in the original file that re-imports (and exports) the moved symbol, maintaining backwards compatibility. This will result in fewer total modifications, as existing imports will not need to be updated.
Handling Dependencies
By default, Codegen will move all of a symbols dependencies along with it. This ensures that your codebase remains consistent and functional.
If you set include_dependencies=False
, only the symbol itself will be moved, and any dependencies will remain in the original file.
Moving Multiple Symbols
If you need to move multiple symbols, you can do so in a loop:
Best Practices
-
Commit After Major Changes: If you’re making multiple significant changes, use
codebase.commit()
between them to ensure the codebase graph is up-to-date. -
Re-fetch References: After a commit, re-fetch any file or symbol references you’re working with, as they may have become stale.
-
Handle Errors: Be prepared to handle cases where symbols or files might not exist, or where moves might fail due to naming conflicts.
By following these guidelines, you can effectively move symbols around your codebase while maintaining its integrity and functionality.
Was this page helpful?