Precision import refactoring tool — rewrite, migrate, and sanitize Python imports project-wide with safety and accuracy.
Project description
import-surgeon 🩺⚙️
Precision Python import refactoring — safe, atomic, AST-exact, rollback-friendly.
🧠 Overview
import-surgeon is an Elite import refactoring engine for Python codebases.
It precisely updates imports and moves symbols across modules without breaking your code, using full LibCST AST guarantees, backup files, atomic writes, and optional auto-formatting.
Think of it as libcst + git-protection + atomic rollback-safe refactor surgery
Use it for:
✅ Package restructures ✅ Module renames ✅ Moving functions/classes between files ✅ Gradual API migrations ✅ Org-wide import cleanup ✅ CI-safe automated refactors
No regex. No AST guessing. No broken imports.
✨ Features
Capability Description
Accurate import rewrites LibCST powered symbol movement (AST-exact) Dotted name rewrites old.module.Foo → new.module.Foo if --rewrite-dotted Atomic file updates Guaranteed atomic writes + metadata restore Auto backup & rollback --no-backup optional; --rollback supported Supports aliases from A import Foo as Bar handled correctly Respects relative imports --force-relative + auto base-package detection Batch migrations YAML config for multi-module migrations Safe in CI --require-clean-git to prevent dirty changes Git auto-commit --auto-commit "msg" Optional format Black + isort applied after changes Warnings for risky spots Wildcards, dotted patterns, skipped rel imports Progress bar tqdm fallback built-in
📦 Installation
pip install import-surgeon
Optional but recommended for improved encoding detection:
pip install chardet
🛠 Usage
Basic dry-run (default)
import-surgeon --old-module utils --new-module core.utils --symbols load,save
Apply changes
import-surgeon --old-module old.pkg --new-module new.pkg --symbols Foo,Bar --apply
Rewrite dotted usages too
import-surgeon --apply --rewrite-dotted
--old-module old.mod --new-module new.mod --symbols Client
Use YAML migrations file
migrate.yml
migrations:
- old_module: old.auth new_module: services.auth symbols: [User, Token]
Run:
import-surgeon --config migrate.yml --apply
Rollback a refactor
import-surgeon --rollback --summary-json summary.json
🧪 Example Output
✔️ New imports inserted ✔️ Old imports removed ✔️ Diff preview in dry-run ✔️ JSON report with file list, change lines & risks
🔒 Safety Guarantees
Dry run by default
File backups by default
Atomic writes (no corruption)
Git-clean check option
Per-file encoding detection
Refuses unsafe wildcard rewrites unless configured
🧠 CLI Options
| Flag | Description | Default |
|---|---|---|
target |
The target file or directory to scan. | . |
--old-module |
The fully qualified module path to move symbols from. | Required¹ |
--new-module |
The fully qualified module path to move symbols to. | Required¹ |
--symbols |
A comma-separated list of symbols to move. | Required¹ |
--apply |
Apply changes to files instead of showing a dry-run. | False |
--config |
Path to a YAML file for batch migrations. | None |
--rewrite-dotted |
Rewrite direct module.symbol usages in code. |
False |
--format |
Apply black and isort formatting after changes. |
False |
--rollback |
Roll back a previous migration using a summary file. | False |
--summary-json |
Path to write a JSON summary of all changes. | None |
--auto-commit |
Git commit message to auto-commit changes. | None |
--require-clean-git |
Abort if the Git repository has uncommitted changes. | False |
--no-backup |
Disable creation of .bak files for changed modules. |
False |
--base-package |
Specify the base package for resolving relative imports. | Auto-detected from Git root |
--force-relative |
Force the use of relative imports where possible. | False |
--exclude |
Comma-separated glob patterns to exclude from scan. | None |
--max-files |
Maximum number of files to scan. | 10000 |
--strict-warnings |
Exit with a non-zero code if any warnings occur. | False |
--quiet |
Set the logging level (none, errors, all). |
none |
-v, --verbose |
Increase logging verbosity. | 0 (Warning) |
--version |
Show the program's version number and exit. | N/A |
--symbol |
Deprecated alias for --symbols. |
None |
¹ Required if not using a --config file.
🚦 Exit Codes
Code Meaning
0 Success 1 Changes had errors 2 CLI/config error
🏗️ Architecture
The core logic resides in the src/import_surgeon/ directory.
src/import_surgeon/
├── cli.py # Main CLI entry point and argument parsing
├── banner.py # ASCII art banner
└── modules/ # Core logic modules
├── __init__.py
├── analysis.py # AST analysis and symbol detection
├── config.py # YAML configuration loading
├── cst_utils.py # LibCST helper functions
├── encoding.py # File encoding detection
├── file_ops.py # File read/write operations
├── git_ops.py # Git repository interactions
└── process.py # Main file processing and orchestration
The tool works by parsing Python files into an Abstract Syntax Tree (AST) using LibCST, identifying import statements, and then surgically replacing them based on the migration rules. It ensures safety through backups, atomic writes, and optional Git integration.
🧩 Roadmap
Symbol dependency graph warnings
VSCode / PyCharm integration
Preview UI with selectable edits
Interactive TUI surgeon console
NeoVim LSP hooks
🤝 Contributing
PRs welcome, especially for:
Editor plugins
Safety analyzers
Batch migration assistants
Code mod multi-tool integration
📜 License
MIT — commercial and open use welcome.
⭐ Support
Star the repo — every ⭐ funds more time for DevTools research 🙏
https://github.com/dhruv13x/import-surgeon
🩺 Your imports deserve precision surgery — not blind search-replace. Run import-surgeon and refactor with confidence.
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-3.0.2.tar.gz.
File metadata
- Download URL: import_surgeon-3.0.2.tar.gz
- Upload date:
- Size: 31.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
262e6ed0c0d3b0b62d88a89226a247b3daaeaa688fe876ef89113e994c194500
|
|
| MD5 |
76d3e3ba4f74b06f450a8425b7f5adbc
|
|
| BLAKE2b-256 |
5fd9850e30739c86493e78210fef155181173fab649bb612e18c43e0140808bb
|
Provenance
The following attestation bundles were made for import_surgeon-3.0.2.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-3.0.2.tar.gz -
Subject digest:
262e6ed0c0d3b0b62d88a89226a247b3daaeaa688fe876ef89113e994c194500 - Sigstore transparency entry: 725332421
- Sigstore integration time:
-
Permalink:
dhruv13x/import-surgeon@86dcaafdb6ea88cace6fcb7f5e537c94e5738dd3 -
Branch / Tag:
refs/tags/v3.0.2 - Owner: https://github.com/dhruv13x
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@86dcaafdb6ea88cace6fcb7f5e537c94e5738dd3 -
Trigger Event:
push
-
Statement type:
File details
Details for the file import_surgeon-3.0.2-py3-none-any.whl.
File metadata
- Download URL: import_surgeon-3.0.2-py3-none-any.whl
- Upload date:
- Size: 20.1 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 |
d57491dabac1d75ede0dcd7a08e43191fcdb0ac40b9409268dedb0d35a59c3e2
|
|
| MD5 |
528c8794b8a269d549d817d8a9c6b943
|
|
| BLAKE2b-256 |
7a94d9fe757670bf92c40f2ac3dbbf8def3413154b2442a3db873d8ff6f4a963
|
Provenance
The following attestation bundles were made for import_surgeon-3.0.2-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-3.0.2-py3-none-any.whl -
Subject digest:
d57491dabac1d75ede0dcd7a08e43191fcdb0ac40b9409268dedb0d35a59c3e2 - Sigstore transparency entry: 725332430
- Sigstore integration time:
-
Permalink:
dhruv13x/import-surgeon@86dcaafdb6ea88cace6fcb7f5e537c94e5738dd3 -
Branch / Tag:
refs/tags/v3.0.2 - Owner: https://github.com/dhruv13x
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@86dcaafdb6ea88cace6fcb7f5e537c94e5738dd3 -
Trigger Event:
push
-
Statement type: