Import Surgeon
Precision import refactoring tool — rewrite, migrate, and sanitize Python imports project-wide with safety and accuracy.
⚡ Quick Start
Prerequisites
- Python 3.8+
- Git initialized repository (recommended for safety)
Installation
# Install from source
pip install .
# Or for development
pip install -e ".[dev]"
Usage in 5 Seconds
Move MyClass from legacy.utils to core.models and apply changes immediately:
import-surgeon --old-module legacy.utils --new-module core.models --symbols MyClass --apply --rewrite-dotted
Before & After
Input (src/main.py):
from legacy.utils import MyClass
def main():
obj = MyClass()
Output:
from core.models import MyClass
def main():
obj = MyClass()
✨ Features
🛡️ Core Capabilities
- AST-Powered: Uses
LibCSTfor syntax-aware refactoring, avoiding regex pitfalls. - Dotted Rewrite: Updates direct usages like
legacy.utils.MyClass()tocore.models.MyClass()with--rewrite-dotted. - Batch Migrations: define complex moves in a
migrations.yamlfile. - Rollback: Automatic backup generation and one-command rollback (
--rollback).
🚀 Performance & Workflow
- Parallel Processing: Multi-core support with
--jobsfor large codebases. - Interactive Mode: TUI for selecting migrations via
--interactive. - Git Integration: Optional clean-repo checks and auto-commit functionality.
- Formatting: Integrated
blackandisortsupport via--format.
🛠️ Configuration
CLI Arguments
| Flag | Description | Default |
|---|---|---|
target |
File or directory to scan. | . |
--old-module |
Source module to move from. | None |
--new-module |
Destination module to move to. | None |
--symbols |
Comma-separated list of symbols to move. | None |
--apply |
Write changes to disk (default is dry-run). | False |
--config |
Path to YAML configuration file. | None |
--rewrite-dotted |
Rewrite dotted access (e.g., mod.Attr). |
False |
--format |
Run black and isort on changed files. |
False |
--jobs, -j |
Number of parallel workers. | 1 |
--interactive, -i |
Launch interactive TUI. | False |
--rollback |
Revert changes using summary JSON. | False |
--verbose, -v |
Increase logging verbosity. | 0 |
YAML Configuration (migrate.yaml)
For batch operations, use a configuration file:
migrations:
- old_module: "legacy.db"
new_module: "core.database"
symbols: ["Connection", "Cursor"]
- old_module: "utils.string"
new_module: "common.text"
symbols: ["slugify"]
Run with:
import-surgeon --config migrate.yaml --apply
🏗️ Architecture
Directory Structure
src/import_surgeon/
├── cli.py # Entry point and argument parsing
└── modules/
├── analysis.py # AST analysis logic
├── config.py # YAML config loader
├── cst_utils.py # LibCST transformers (The "Brain")
├── file_ops.py # File discovery and management
├── git_ops.py # Git integration (clean check, commit)
├── interactive.py # TUI implementation
├── process.py # Main processing orchestration
└── rollback.py # Backup restoration logic
How It Works
- Discovery: Scans
targetfor.pyfiles, respecting.gitignoreand exclusions. - Analysis: Parses each file into a CST (Concrete Syntax Tree) using
LibCST. - Transformation: Visits the CST to identify and rewrite imports and usages based on provided rules.
- Verification: Formats code (optional) and checks for syntax validity.
- Execution: Writes changes to disk (atomic write) or displays a diff (dry-run).
- Reporting: Generates a JSON summary for auditing or rollback.
🐞 Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| "Git not clean" | --require-clean-git is enabled but repo has changes. |
Commit/stash changes or remove the flag. |
| "Target not found" | The path specified does not exist. | Verify the target argument matches a real path. |
| Imports not updating | Symbols might be aliased or dynamically imported. | Use --verbose to see skipped files; verify symbol names. |
| Encoding Errors | File has non-UTF-8 encoding. | Ensure files are UTF-8 or compatible. Tool attempts auto-detection. |
Debug Mode
Enable verbose logging to trace execution:
import-surgeon --verbose --verbose ...
🤝 Contributing
We welcome contributions! Please follow these steps:
- Fork & Clone: Clone your fork locally.
- Setup: Install dev dependencies:
pip install -e ".[dev]"
- Test: Run the test suite:
python -m pytest
- Lint: Ensure code style compliance:
ruff check . black .
- Submit: Open a Pull Request with a clear description of changes.
🗺️ Roadmap
We are currently in Phase 2.
- Phase 1 (Completed): AST Engine, CLI, YAML Config, Git Integration, Rollback.
- Phase 2 (Current): Interactive TUI, Symbol Dependency Analysis.
- Phase 3 (Next): Public Python API, Pre-Commit Hooks, IDE Integration.
- Phase 4 (Future): AI-Driven Refactoring Advisor, Self-Healing Imports.
See ROADMAP.md for details.
Metadata
Release files for import-surgeon 4.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| import_surgeon-4.0.1.tar.gz | 35.6 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| import_surgeon-4.0.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 58.5 kB
Release files / import_surgeon-4.0.1.tar.gz
| Download URL | import_surgeon-4.0.1.tar.gz |
|---|---|
| Size | 35.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
35548c90bbed0954048d770d66eeffbdf44069d525b69e98233a2017c15a840f
|
|
BLAKE2b-256 checksum How to use checksums |
b47ac6f091fae76311b3fd2d0bb8d4b8e852deb75a69d2c7a91cfdfcca8db6c3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 15, 2025.
Transparency logRelease files / import_surgeon-4.0.1-py3-none-any.whl
| Download URL | import_surgeon-4.0.1-py3-none-any.whl |
|---|---|
| Size | 22.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0f961b8bf3bdfc5b1f3bd995892aa32e34523cf052f0501d738f3f47d8721ecd
|
|
BLAKE2b-256 checksum How to use checksums |
6fa070026d37d24900d00f3aa0df0573e066bc70a65dae54342a64d6983b81bd
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 15, 2025.
Transparency log