Skip to content

Instantly share code, notes, and snippets.

@dnwe
Created August 22, 2024 16:39
Show Gist options
  • Save dnwe/a2ec176d0893e5c31a0ba25735389a59 to your computer and use it in GitHub Desktop.
Save dnwe/a2ec176d0893e5c31a0ba25735389a59 to your computer and use it in GitHub Desktop.
pip3 shim to uv pip
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.9"
# dependencies = []
# ///
import sys
import configparser
import os
from pathlib import Path
# Note: this isn't exhaustive, but mostly tries to follow
# https://pip.pypa.io/en/stable/topics/configuration/ although we ignore XDG and only support the
# '[global]' section rather than per-command options for now
config = configparser.ConfigParser()
globalconf = Path("/etc/pip/pip.conf").expanduser()
userconf = Path("~/.pip/pip.conf").expanduser()
if "VIRTUAL_ENV" in os.environ:
venvconf = Path(os.environ["VIRTUAL_ENV"]) / "pip.conf"
else:
venvconf = ""
if "PIP_CONFIG_FILE" in os.environ:
pipconf = Path(os.environ["PIP_CONFIG_FILE"])
else:
pipconf = ""
env = {k: v for k, v in os.environ.items()}
# initialise uv env from pip.conf files
if pipconf != os.devnull and config.read(
filenames=[globalconf, userconf, venvconf, pipconf]
):
env["UV_INDEX_URL"] = config.get("global", "index-url", fallback="")
env["UV_EXTRA_INDEX_URL"] = " ".join(
config.get("global", "extra-index-url", fallback="").split("\n")
)
# override uv env from uv or pip envvars if those are set
env["UV_INDEX_URL"] = (
os.getenv("UV_INDEX_URL") or os.getenv("PIP_INDEX_URL") or env["UV_INDEX_URL"]
)
env["UV_EXTRA_INDEX_URL"] = (
os.getenv("UV_EXTRA_INDEX_URL")
or os.getenv("PIP_EXTRA_INDEX_URL")
or env["UV_EXTRA_INDEX_URL"]
)
args = ["uv", "pip"] + sys.argv[1:]
os.execvpe("uv", args, env)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment