Skip to main content

Import Surgeon

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

Build Status License: MIT Python 3.8+ Code Style: Black Maintenance


⚡ 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 LibCST for syntax-aware refactoring, avoiding regex pitfalls.
  • Dotted Rewrite: Updates direct usages like legacy.utils.MyClass() to core.models.MyClass() with --rewrite-dotted.
  • Batch Migrations: define complex moves in a migrations.yaml file.
  • Rollback: Automatic backup generation and one-command rollback (--rollback).

🚀 Performance & Workflow

  • Parallel Processing: Multi-core support with --jobs for large codebases.
  • Interactive Mode: TUI for selecting migrations via --interactive.
  • Git Integration: Optional clean-repo checks and auto-commit functionality.
  • Formatting: Integrated black and isort support 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

  1. Discovery: Scans target for .py files, respecting .gitignore and exclusions.
  2. Analysis: Parses each file into a CST (Concrete Syntax Tree) using LibCST.
  3. Transformation: Visits the CST to identify and rewrite imports and usages based on provided rules.
  4. Verification: Formats code (optional) and checks for syntax validity.
  5. Execution: Writes changes to disk (atomic write) or displays a diff (dry-run).
  6. 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:

  1. Fork & Clone: Clone your fork locally.
  2. Setup: Install dev dependencies:
    pip install -e ".[dev]"
    
  3. Test: Run the test suite:
    python -m pytest
    
  4. Lint: Ensure code style compliance:
    ruff check .
    black .
    
  5. 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)

Source distribution for import-surgeon 4.0.1
File Size Uploaded
import_surgeon-4.0.1.tar.gz 35.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for import-surgeon 4.0.1
File Interpreter ABI Platform
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 log

Release 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

Release history Release notifications | RSS feed

This release

4.0.1 This release

2 release files

4.0.0

2 release files

3.0.2

2 release files

3.0.1

2 release files

3.0.0

2 release files

1.0.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page