mirror of
https://github.com/daylinmorgan/viv.git
synced 2024-11-09 19:13:14 -06:00
53 lines
2.3 KiB
Python
Executable file
53 lines
2.3 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
def _viv_use(*pkgs, track_exe=False, name=""):
|
|
import hashlib, json, os, site, shutil, sys, venv # noqa
|
|
from pathlib import Path # noqa
|
|
from datetime import datetime # noqa
|
|
from subprocess import run # noqa
|
|
|
|
if not {*map(type, pkgs)} == {str}:
|
|
raise ValueError(f"spec: {pkgs} is invalid")
|
|
|
|
meta = dict.fromkeys(("created", "accessed"), (t := str(datetime.today())))
|
|
runner = str(Path(__file__).absolute().resolve())
|
|
force, verbose, xdg = map(os.getenv, ("VIV_FORCE", "VIV_VERBOSE", "XDG_CACHE_HOME"))
|
|
cache = (Path(xdg) if xdg else Path.home() / ".cache") / "viv" / "venvs"
|
|
cache.mkdir(parents=True, exist_ok=True)
|
|
exe = str(Path(sys.executable).resolve()) if track_exe else "N/A"
|
|
(sha256 := hashlib.sha256()).update((str(spec := [*pkgs]) + exe).encode())
|
|
_id = sha256.hexdigest()
|
|
if (env := cache / (name if name else _id)) not in cache.glob("*/") or force:
|
|
sys.stderr.write(f"generating new vivenv -> {env.name}\n")
|
|
venv.create(env, symlinks=True, with_pip=True, clear=True).create(env)
|
|
(env / "pip.conf").write_text("[global]\ndisable-pip-version-check=true")
|
|
run_kw = dict(zip(("stdout", "stderr"), ((None,) * 2 if verbose else (-1, 2))))
|
|
p = run([env / "bin" / "pip", "install", "--force-reinstall", *spec], **run_kw)
|
|
if (rc := p.returncode) != 0:
|
|
if env.is_dir():
|
|
shutil.rmtree(env)
|
|
sys.stderr.write(f"pip had non zero exit ({rc})\n{p.stdout.decode()}\n")
|
|
sys.exit(rc)
|
|
meta.update(dict(id=_id, spec=spec, exe=exe, name=name, files=[runner]))
|
|
else:
|
|
meta = json.loads((env / "vivmeta.json").read_text())
|
|
meta.update(dict(accessed=t, files=sorted({*meta["files"], runner})))
|
|
|
|
(env / "vivmeta.json").write_text(json.dumps(meta))
|
|
sys.path = [p for p in sys.path if not p != site.USER_SITE]
|
|
site.addsitedir(str(*(env / "lib").glob("py*/si*")))
|
|
return env
|
|
|
|
|
|
import subprocess
|
|
import sys
|
|
|
|
if __name__ == "__main__":
|
|
vivenv = _viv_use(
|
|
"black==23.3.0",
|
|
"click==8.1.3",
|
|
"mypy-extensions==1.0.0",
|
|
"packaging==23.1", # noqa
|
|
"pathspec==0.11.1",
|
|
"platformdirs==3.5.1",
|
|
) # noqa
|
|
sys.exit(subprocess.run([vivenv / "bin" / "black", *sys.argv[1:]]).returncode)
|