Precision import refactoring tool — rewrite, migrate, and sanitize Python imports project-wide with safety and accuracy.
Project description
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.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file import_surgeon-4.0.1.tar.gz.
File metadata
- Download URL: import_surgeon-4.0.1.tar.gz
- Upload date:
- Size: 35.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
35548c90bbed0954048d770d66eeffbdf44069d525b69e98233a2017c15a840f
|
|
| MD5 |
f677326962dc573c66e78bd4f27a24e5
|
|
| BLAKE2b-256 |
b47ac6f091fae76311b3fd2d0bb8d4b8e852deb75a69d2c7a91cfdfcca8db6c3
|
Provenance
The following attestation bundles were made for import_surgeon-4.0.1.tar.gz:
Publisher:
publish.yml on dhruv13x/import-surgeon
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
import_surgeon-4.0.1.tar.gz -
Subject digest:
35548c90bbed0954048d770d66eeffbdf44069d525b69e98233a2017c15a840f - Sigstore transparency entry: 764297055
- Sigstore integration time:
-
Permalink:
dhruv13x/import-surgeon@7bb983874dfeffded425f842cb6afb673416f094 -
Branch / Tag:
refs/tags/v4.0.1 - Owner: https://github.com/dhruv13x
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@7bb983874dfeffded425f842cb6afb673416f094 -
Trigger Event:
push
-
Statement type:
File details
Details for the file import_surgeon-4.0.1-py3-none-any.whl.
File metadata
- Download URL: import_surgeon-4.0.1-py3-none-any.whl
- Upload date:
- Size: 22.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0f961b8bf3bdfc5b1f3bd995892aa32e34523cf052f0501d738f3f47d8721ecd
|
|
| MD5 |
fdf4aa77f632697bc85beb49e2f1aeb0
|
|
| BLAKE2b-256 |
6fa070026d37d24900d00f3aa0df0573e066bc70a65dae54342a64d6983b81bd
|
Provenance
The following attestation bundles were made for import_surgeon-4.0.1-py3-none-any.whl:
Publisher:
publish.yml on dhruv13x/import-surgeon
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
import_surgeon-4.0.1-py3-none-any.whl -
Subject digest:
0f961b8bf3bdfc5b1f3bd995892aa32e34523cf052f0501d738f3f47d8721ecd - Sigstore transparency entry: 764297058
- Sigstore integration time:
-
Permalink:
dhruv13x/import-surgeon@7bb983874dfeffded425f842cb6afb673416f094 -
Branch / Tag:
refs/tags/v4.0.1 - Owner: https://github.com/dhruv13x
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@7bb983874dfeffded425f842cb6afb673416f094 -
Trigger Event:
push
-
Statement type: