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.

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.1.tar.gz (35.6 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.1-py3-none-any.whl (22.9 kB view details)

Uploaded Python 3

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

Hashes for import_surgeon-4.0.1.tar.gz
Algorithm Hash digest
SHA256 35548c90bbed0954048d770d66eeffbdf44069d525b69e98233a2017c15a840f
MD5 f677326962dc573c66e78bd4f27a24e5
BLAKE2b-256 b47ac6f091fae76311b3fd2d0bb8d4b8e852deb75a69d2c7a91cfdfcca8db6c3

See more details on using hashes here.

Provenance

The following attestation bundles were made for import_surgeon-4.0.1.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.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

Hashes for import_surgeon-4.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 0f961b8bf3bdfc5b1f3bd995892aa32e34523cf052f0501d738f3f47d8721ecd
MD5 fdf4aa77f632697bc85beb49e2f1aeb0
BLAKE2b-256 6fa070026d37d24900d00f3aa0df0573e066bc70a65dae54342a64d6983b81bd

See more details on using hashes here.

Provenance

The following attestation bundles were made for import_surgeon-4.0.1-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.

Release history Release notifications | RSS feed

This release

4.0.1 This release

2 files

4.0.0

2 files

3.0.2

2 files

3.0.1

2 files

3.0.0

2 files

1.0.0

2 files

0.1.0

2 files

Supported by

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