Metadata-Version: 2.4
Name: pipmaster
Version: 1.3.0
Summary: A versatile Python package manager utility for simplifying package installation, updates, checks, and environment management.
Author-email: ParisNeo <parisneoai@gmail.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/ParisNeo/pipmaster
Project-URL: Repository, https://github.com/ParisNeo/pipmaster
Project-URL: Issues, https://github.com/ParisNeo/pipmaster/issues
Keywords: pip,package manager,installer,dependency,venv,environment,offline,air-gap
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Build Tools
Classifier: Topic :: System :: Software Distribution
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: packaging>=21.0
Requires-Dist: ascii_colors>=0.11.11
Provides-Extra: audit
Requires-Dist: pip-audit>=2.5.0; extra == "audit"
Provides-Extra: airgap
Requires-Dist: cryptography>=3.4; extra == "airgap"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.20; extra == "dev"
Requires-Dist: pip-audit>=2.5.0; extra == "dev"
Requires-Dist: sphinx>=5.0; extra == "dev"
Requires-Dist: sphinx-rtd-theme>=1.0; extra == "dev"
Requires-Dist: myst-parser>=0.17; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: cowsay; extra == "dev"
Provides-Extra: all
Requires-Dist: pipmaster[audit]; extra == "all"
Requires-Dist: pipmaster[airgap]; extra == "all"
Requires-Dist: pipmaster[dev]; extra == "all"
Dynamic: license-file

# `pipmaster`: The Python Package Management Toolkit

<!-- Badges -->
[![PyPI version](https://badge.fury.io/py/pipmaster.svg)](https://badge.fury.io/py/pipmaster)
[![Python Versions](https://img.shields.io/pypi/pyversions/pipmaster.svg)](https://pypi.org/project/pipmaster/)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/ParisNeo/pipmaster/blob/main/LICENSE)
[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/ParisNeo/pipmaster/docs.yml?branch=main&label=docs)](https://github.com/ParisNeo/pipmaster/actions/workflows/docs.yml)
[![GitHub stars](https://img.shields.io/github/stars/ParisNeo/pipmaster.svg?style=social&label=Stars)](https://github.com/ParisNeo/pipmaster)
[![Documentation Status](https://readthedocs.org/projects/pipmaster/badge/?version=latest)](https://parisneo.github.io/pipmaster/) 
[![Code Coverage](https://img.shields.io/codecov/c/github/ParisNeo/pipmaster)](https://codecov.io/gh/ParisNeo/pipmaster)
[![Code Quality](https://img.shields.io/codacy/grade/your-project-id)](https://www.codacy.com/app/your-username/pipmaster)

<img width="1536" height="1024" alt="image" src="https://github.com/user-attachments/assets/82aab33c-785c-4539-a5de-a0dc9376b00d" />



**🎉 Now available on [PyPI](https://pypi.org/project/pipmaster/)! Install with: `pip install pipmaster`**

Stop telling your users to `pip install -r requirements.txt`. Start building professional, self‑sufficient Python applications that **just work**.

`pipmaster` is the ultimate toolkit for declarative and programmatic package management. It provides a robust, unified interface to backends like **`pip`** and **`uv`**, allowing you to automate installations, updates, and environment validation directly from your Python code. With both **synchronous and asynchronous APIs**, it's designed to guarantee that your applications work out‑of‑the‑box by programmatically ensuring all dependencies are correctly installed.

**View the full documentation at [parisneo.github.io/pipmaster/](https://parisneo.github.io/pipmaster/).**

## Why `pipmaster`? The Power to Build Better Software

`pipmaster` bridges the gap between development and deployment, solving the classic “it works on my machine” problem.

* **Automate Your Setup**: Your application can configure its own environment on first launch.
* **Self‑Healing Applications**: Detect missing or outdated packages at runtime and fix them automatically.
* **Eliminate “Dependency Hell”**: Manage dependencies for non‑technical users with zero manual steps.
* **Multi‑Environment Management**: Seamlessly work across multiple virtual environments, CI pipelines, or portable Python builds.
* **Dry‑Run & Verbose Modes**: Preview changes safely before they happen and get crystal‑clear debugging output.
* **Ultrafast Installs**: Automatically uses `uv` for uv-created environments, with safe pip fallback and an explicit `use_uv=True` override.
* **Future‑Proof**: A pluggable architecture for additional backends (`conda` planned).

## Key Use Cases

* **Desktop GUI Apps** – Ensure UI libraries are present on first run.
* **CLI Tools** – Auto‑install required plugins, making the tool instantly usable.
* **Data Science / ML Projects** – Keep notebooks, servers, and containers in sync with exact dependencies.
* **CI/CD Pipelines** – Prepare clean build environments programmatically.
* **Libraries & Frameworks** – Provide helper scripts that set up a correct environment for users.

## Quick Start

### Installation

```bash
pip install pipmaster
```

### Basic Usage

```python
import pipmaster as pm

# Ensure a single package is installed
pm.ensure_packages("rich")

# Ensure multiple packages with version requirements
pm.ensure_packages(["pandas", "numpy>=1.20"], verbose=True)

# Ensure packages from a requirements.txt file
pm.ensure_requirements("requirements.txt")
```

### Advanced Example

```python
import pipmaster as pm

# Conditional installation based on platform
required_packages = {
    "torch": {"index_url": "https://download.pytorch.org/whl/cu121", "specifier": ">=2.0.0"},
    "transformers": {"specifier": ">=4.30.0"},
}

# Check and install/update packages
pm.ensure_packages(required_packages, verbose=True)
```

### Progress Callbacks

Both `ensure_packages` and `async_ensure_packages` support an optional `progress_callback` parameter for real-time progress updates. This is useful for building progress UIs in frontend applications.

```python
import pipmaster as pm

def my_progress_callback(data):
    """
    Receives progress updates with the following keys:
    - status: "checking", "processing", "complete", or "failed"
    - message: Description of current operation
    - package/packages: Package(s) being processed
    - progress/total: Progress counters during checking phase
    - success: Boolean result (in final status)
    """
    print(f"[{data['status'].upper()}] {data['message']}")
    if 'progress' in data:
        print(f"  Progress: {data['progress']}/{data['total']}")

# Synchronous usage
pm.ensure_packages(["requests", "numpy", "pandas"], 
                   progress_callback=my_progress_callback,
                   verbose=True)
```

**Async usage with coroutine callback:**

```python
import pipmaster as pm
import asyncio

async def my_async_callback(data):
    print(f"[{data['status'].upper()}] {data['message']}")

async def main():
    await pm.async_ensure_packages(
        ["torch", "transformers", "datasets"],
        progress_callback=my_async_callback,
        verbose=True
    )

asyncio.run(main())
```

## Feature Overview

| Feature                                      | `pip` Backend | `uv` Backend (Experimental) | Async Support |
| -------------------------------------------- | :-----------: | :------------------------: | :-----------: |
| **Ensure Package State (`ensure_packages`)**| ✅            | ✅ (`use_uv=True`)          | ✅            |
| **Ensure from `requirements.txt`**          | ✅            | ✅ (`use_uv=True`)          | ✅            |
| **Progress Callbacks**                       | ✅            | ✅ (`use_uv=True`)          | ✅            |
| Install / Upgrade Packages                   | ✅            | ✅                         | ✅            |
| Uninstall Packages                           | ✅            | ✅                         | ✅            |
| Vulnerability Scanning (`pip-audit`)        | ✅            | N/A                        | ✅            |
| Check Installed Status (`is_installed`)      | ✅            | ✅ (`use_uv=True`)          | (Sync)        |
| Create Virtual Environments                  | ✅ (`venv`)    | ✅ (`UvPackageManager`)     | ✅            |
| Run Ephemeral Tools (`uvx`)                  | N/A            | ✅ (`UvPackageManager`)     | N/A           |
| Dry Run Mode                                 | ✅            | ✅ (`use_uv=True`)          | ✅            |
| Portable Python Management                   | ✅            | ✅ (`use_uv=True`)          | ✅            |
| Air-Gap Updates (`pipmaster-install`)        | ✅            | ❌                         | N/A           |

## Core Concept: Declarative & Idempotent Management

The `ensure_*` methods are **idempotent** – you can run them repeatedly, and they only act when the environment diverges from your declaration.

### `ensure_packages`

```python
import pipmaster as pm

# 1️⃣ Simple: ensure a single package is present
pm.ensure_packages("rich")

# 2️⃣ List: ensure multiple packages with version specifiers
pm.ensure_packages(["pandas", "numpy>=1.20"], verbose=True)

# 3️⃣ Dictionary: clean mapping of package → version specifier
requirements = {
    "requests": ">=2.25.0",
    "tqdm": None,                     # any version accepted
    "torch": {"index_url": "https://download.pytorch.org/whl/cu121", "specifier": ">=2.0.0"},
}
pm.ensure_packages(requirements, verbose=True)
```

### `ensure_requirements`

```python
import pipmaster as pm

# Assuming a requirements.txt exists
if pm.ensure_requirements("requirements.txt", verbose=True):
    print("Environment now matches requirements.txt!")
```

## Advanced Usage

### Conditional Installation from Git (VCS)

```python
import pipmaster as pm

# Install from Git only if the installed version is <0.25.0
conditional_req = {
    "name": "diffusers",
    "vcs": "git+https://github.com/huggingface/diffusers.git",
    "condition": ">=0.25.0"
}
pm.ensure_packages([conditional_req], verbose=True)
```

### Asynchronous API

All core functions have async equivalents prefixed with `async_`.  

```python
import pipmaster as pm
import asyncio

async def async_demo():
    await pm.async_install("httpx")
    await pm.async_ensure_requirements("requirements.txt", verbose=True)

# asyncio.run(async_demo())
```

### Async Factory for Portable Python

When you need a specific portable Python version in an async context:

```python
import pipmaster as pm
import asyncio

async def main():
    async_pm = pm.get_async_pip_manager_for_version("3.12", "./portable_venv")
    await async_pm.install("rich", verbose=True)

    loop = asyncio.get_running_loop()
    installed = await loop.run_in_executor(None, async_pm.is_installed, "rich")
    print(f"'rich' installed? {installed}")

# asyncio.run(main())
```

### Ultrafast Installs with `uv`

Pipmaster automatically uses `uv` when it is installed **and** the target
environment was created by uv (detected through `pyvenv.cfg`). Standard venv and
system environments continue using pip. If uv is unavailable, pipmaster safely
falls back to pip. All declarative requirements, dry runs, environment targeting,
and async operations work with either backend.

Install uv with the built-in helper if needed:

```python
pm.install_uv()
```

Use `use_uv=True` to require uv even for an environment not created by uv, or
`use_uv=False` to force pip:

```python
import pipmaster as pm

packages = pm.get_pip_manager(use_uv=True)
packages.ensure_packages(["numpy", "pandas>=2"], verbose=True)

# Target a specific environment; pipmaster passes its interpreter to uv.
venv_packages = pm.get_pip_manager(venv_path="./.venv", use_uv=True)
venv_packages.ensure_requirements("requirements.txt")
```

For uv-specific environment creation and ephemeral tools, use the lightweight
`UvPackageManager` backend:

```python
from pipmaster import get_uv_manager
import os, shutil

env_path = "./my_uv_env"

if os.path.exists(env_path):
    shutil.rmtree(env_path)

uv = get_uv_manager()
if uv.create_env(path=env_path):
    uv.install_multiple(["numpy", "pandas"], verbose=True)
    uv.run_with_uvx(["black", "--version"], verbose=True)
```

## Vulnerability Scanning

```python
import pipmaster as pm

found, report = pm.check_vulnerabilities()
if found:
    print("Vulnerabilities detected!")
    print(report)
else:
    print("No known vulnerabilities.")
```

## Quarantining Fresh Releases (Supply-Chain Defense)

When a project or one of its dependencies is compromised, the malicious release
usually lives on PyPI for only a few hours before being yanked. `pipmaster`
helps you wait out that window.

By default, `pipmaster` **never installs a release uploaded in the last 48
hours** unless you pin it explicitly. The window is controlled by the
`PIPMASTER_MIN_AGE_HOURS` environment variable:

```bash
# Wait three days before adopting a new release
export PIPMASTER_MIN_AGE_HOURS=72

# Disable the quarantine (install the newest release immediately)
export PIPMASTER_MIN_AGE_HOURS=0
```

The guard applies to plain `install(...)`, `ensure_packages(...)`, and any
open-ended specifier (`>=`, `>`). Explicit pins (`==`), upper bounds (`<`),
extras, and VCS/URL targets are never rewritten — pipmaster only adjusts its own
"latest" choice, never your explicit one. For every eligible target pipmaster
queries PyPI metadata, picks the newest **stable** release older than the
window, and rewrites the install target as a pin (e.g. `requests==2.32.0`). If
the environment already has an equal or newer version, the request is left
untouched — pipmaster never downgrades an installed package.

Set `PIPMASTER_MIN_AGE_HOURS=0` for CI or fully offline tooling. For air-gapped
machines the relay's `--min-age-days` option provides the same defense; the two
mechanisms are complementary.

## Updating Offline (Air-Gap) Machines

An **air-gapped** machine has no internet access, but its packages still need security updates and new dependencies. `pipmaster` ships a paired update link: an **online relay** fetches the right wheels, and an **offline client** installs them — with no open ports, no package index, and no manual `scp` of wheel files.

The link is **pair-once, verify-always**: a single one-time token binds the two machines, and every session is authenticated with a shared secret and a pinned TLS fingerprint. The relay only opens for the window you choose, serves one client, and closes.

### One-Time Setup

```bash
# On the ONLINE machine (needs cryptography for the relay's TLS identity)
pip install pipmaster[airgap]
pipmaster-pair create --host 192.168.1.10

# -> prints the fingerprint and a pairing token (a secret — carry it over just once)
```

```bash
# On the OFFLINE machine
pipmaster-pair accept <token>
```

`--host` is the address the offline machine will use to reach the relay; `--port` defaults to `8765`. Re-create the identity with `pipmaster-pair create --force` to rotate it (all existing pairings then stop working).

### Every Update Window

```bash
# ONLINE: open the link for 15 minutes, only for the offline machine's IP
pipmaster-relay --for 15m --allow-from 192.168.1.20 --audit
```

```bash
# OFFLINE: install or update from a requirements file / project dir
pipmaster-install ./myproject/requirements.txt

# ...or refresh everything currently installed
pipmaster-install --upgrade-installed

# Preview the plan without touching the environment
pipmaster-install ./requirements.txt --dry-run
```

You can also pass a project directory (it reads `requirements.txt` or `pyproject.toml`) or explicit specs with `-p`:

```bash
pipmaster-install -p "rich>=13" -p httpx
```

Before anything is installed, `pipmaster-install` prints a **plan** (`+` new, `^` upgrade, `v` downgrade, `=` unchanged), asks for confirmation (skip with `-y`), saves a **rollback snapshot** of the current environment, then verifies every wheel's SHA-256 hash before installing.

### Safety Features

- **Quarantine window** — releases younger than `--min-age-days` (default 7) are skipped in favor of the newest older version, giving the community time to react to a compromised release. Pass `--min-age-days 0` to disable.
- **`--audit`** — runs `pip-audit` on the resolved set at the relay; results appear in the plan before you install.
- **Pinned TLS + HMAC auth** — the client refuses any relay whose certificate fingerprint doesn't match the one it was paired with.
- **`--allow-from IP_OR_CIDR`** — restricts which peers the relay will accept (repeatable).
- **`--keep-open`** — keep the relay running after a successful session (default: it closes after one).
- **`--index-url`** — use a private mirror (requires `--min-age-days 0`, since age data comes from pypi.org).

### How It Works

The relay runs `pip download` targeting the **offline machine's** platform, Python version, ABI, and marker environment (Windows/macOS/Linux wheels are selected correctly even when the relay runs on a different OS). It re-walks dependencies using the client's markers, so Linux-only or Windows-only dependencies are handled correctly — something plain `pip download --platform` gets wrong. Wheels are streamed over the paired TLS channel, hash-checked on arrival, and installed with `pip install --no-index --find-links … --require-hashes --no-deps`.

### Rollback

Each install saves a `pip freeze` snapshot under `~/.pipmaster/airgap/snapshots/`. To roll back, run `pipmaster-install` with that snapshot file as the requirements input.

### Notes & Limitations

- Only **wheels** are served; dependencies with no wheel for the target are reported by pip's own error.
- **Direct references** (`git+…`, URL requirements) are skipped with a warning — they can't cross the link.
- Single package vulnerabilities scans aren't part of the link; use `--audit` for a full-set report.
- On Windows, updating `pipmaster` itself while its console script is running may fail; update it separately.

See the [usage guide](docs/usage.rst) for the full CLI reference.

## Why Choose `pipmaster`?

### Compared to Manual `pip install`

| Feature | Manual `pip install` | `pipmaster` |
|---------|----------------------|-------------|
| Automation | Manual process | Fully automated |
| Error Handling | User must handle errors | Built-in error handling |
| Cross-platform | Platform-specific commands | Unified API |
| Version Management | Manual version checking | Automatic version validation |
| Environment Isolation | Manual venv management | Built-in venv support |

### Compared to Other Package Managers

| Feature | `pip` | `conda` | `uv` | `pipmaster` |
|---------|-------|---------|------|-------------|
| Programmatic API | Limited | Limited | Limited | Full API support |
| Async Support | No | No | Limited | Full async support |
| Portable Python | No | No | No | Built-in support |
| Cross-backend | No | No | No | Supports pip, uv, planned conda |

## Contributing

Contributions are welcome! Please see the [Contributing guide](docs/contributing.rst) for details on reporting issues, submitting pull requests, and running tests.

### How to Contribute

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## Support

Need help? Join our community:

- **GitHub Discussions**: [Ask questions on GitHub](https://github.com/ParisNeo/pipmaster/discussions)

## License

This project is licensed under the Apache 2.0 License – see the [LICENSE](LICENSE) file for details.

## Acknowledgments

- Thanks to the Python community for creating such a powerful ecosystem
- Special thanks to the developers of `pip`, `uv`, and `pip-audit` for their excellent tools
- Inspired by the need for better package management in production applications
