Skip to main content

Precision import refactoring tool — rewrite, migrate, and sanitize Python imports project-wide with safety and accuracy.

Project description

import-surgeon logo

PyPI version Python Wheel Release

Build status Codecov Test Coverage Code style: black Ruff Security

Downloads OS Python Versions

License: MIT


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.


🚀 Quick Start

Prerequisites

  • Python 3.8+
  • Dependencies (installed automatically): rich, tqdm, pyyaml, regex, black, isort, libcst.

Installation

pip install import-surgeon

Usage Examples

1. Interactive Wizard (New! 🌟) launch the TUI to guide you through the refactor:

import-surgeon --interactive

2. Basic dry-run Preview changes without modifying files:

import-surgeon --old-module utils --new-module core.utils --symbols load,save

3. Apply changes with Formatting Apply the refactor and run black/isort immediately:

import-surgeon --apply --format \
  --old-module old.pkg --new-module new.pkg --symbols Foo,Bar

4. Rewrite dotted usages Also update old.mod.Client to new.mod.Client in code:

import-surgeon --apply --rewrite-dotted \
  --old-module old.mod --new-module new.mod --symbols Client

✨ Key Features

  • Accurate import rewrites: LibCST powered symbol movement (AST-exact).
  • Interactive TUI: Wizard-style guide for safe refactoring (--interactive).
  • Dotted name rewrites: old.module.Foonew.module.Foo if --rewrite-dotted.
  • Advanced Alias Handling: Updates usages like import old.pkg as o; o.Symbol()new.pkg.Symbol().
  • Dependency Analysis: Warns if moving a symbol breaks internal module dependencies.
  • 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 (--format).
  • Progress bar: tqdm fallback built-in.
  • Parallel Processing: Multiprocessing support via --jobs N.

⚙️ Configuration & Advanced Usage

YAML Migration File (migrate.yml)

Define complex moves in a file for reproducible migrations:

migrations:
  - old_module: old.auth
    new_module: services.auth
    symbols: [User, Token]
  - old_module: utils.db
    new_module: core.database
    symbols: [connect, disconnect]

Run with config:

import-surgeon --config migrate.yml --apply

Rollback a Refactor

Made a mistake? Undo strictly the last operation using the summary file:

import-surgeon --rollback --summary-json summary.json

CLI Arguments

Flag Description Default
target The target file or directory to scan. .
--interactive, -i Launch the interactive TUI wizard. False
--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
--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
--version Show the program's version number and exit. N/A
--jobs, -j Number of parallel jobs for processing files. 1
--symbol Deprecated alias for --symbols. None

¹ Required if not using a --config file or --interactive mode.

Exit Codes

  • 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
    ├── interactive.py # TUI Wizard logic
    ├── process.py     # Main file processing and orchestration
    └── rollback.py    # Rollback logic

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

Phase 1: Foundation (Current)

  • ✅ AST-Based Refactoring
  • ✅ Robust CLI & Configuration Files
  • ✅ File Backups & Git Integration
  • ✅ Atomic Rollback Capability

Phase 2: The Standard (Current)

  • ✅ Interactive TUI for selecting symbols.
  • ✅ Symbol Dependency Analysis warning system.
  • ✅ Parallel Processing support.
  • ⬜ Enhanced Dry-Run with side-by-side diffs.
  • ⬜ "Unused Import" Cleanup.

Phase 3: The Ecosystem

  • ⬜ IDE Integration (VSCode / PyCharm plugins).
  • ⬜ Pre-Commit Hook automation.
  • ⬜ Public API for programmatic use.

Phase 4: The Vision

  • ⬜ AI-Powered Refactoring Suggestions.
  • ⬜ Automated Code Modernization.

See ROADMAP.md for detailed timeline and "God Level" goals.


🤝 Contributing & License

PRs welcome! We are looking for help with:

  • Editor plugins
  • Safety analyzers
  • Batch migration assistants

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

import_surgeon-4.0.0.tar.gz (37.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

import_surgeon-4.0.0-py3-none-any.whl (24.0 kB view details)

Uploaded Python 3

File details

Details for the file import_surgeon-4.0.0.tar.gz.

File metadata

  • Download URL: import_surgeon-4.0.0.tar.gz
  • Upload date:
  • Size: 37.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for import_surgeon-4.0.0.tar.gz
Algorithm Hash digest
SHA256 7181805753ee27acf1771020b664cd9b5897ee6b18dcde5dbb9b7e22a680aa68
MD5 2eb8199aec3d089508cf65562f319e63
BLAKE2b-256 671bd07cd6f532a4444db119ff125a20361a6952d6db1edb7acb37404610b766

See more details on using hashes here.

Provenance

The following attestation bundles were made for import_surgeon-4.0.0.tar.gz:

Publisher: publish.yml on dhruv13x/import-surgeon

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file import_surgeon-4.0.0-py3-none-any.whl.

File metadata

  • Download URL: import_surgeon-4.0.0-py3-none-any.whl
  • Upload date:
  • Size: 24.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for import_surgeon-4.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4f76499ce5cb6c4db82b7cb89c1c66f2b5abc1777748aff02de4c9a81f60b3c9
MD5 469433d5ba321208b27071a5caf83e79
BLAKE2b-256 06a5af0ee61cde2f722ad64b1b1d45c944facf8f93821ece2b5f534ef7f32e4f

See more details on using hashes here.

Provenance

The following attestation bundles were made for import_surgeon-4.0.0-py3-none-any.whl:

Publisher: publish.yml on dhruv13x/import-surgeon

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page