Compare commits

...

4 commits

2 changed files with 91 additions and 106 deletions

View file

@ -1,33 +1,26 @@
#!/usr/bin/env python3
# <<<<< auto-generated by viv (v23.5a2-2-gebb657c-dev)
# see `python3 <(curl -fsSL gh.dayl.in/viv/viv.py) --help`
# fmt: off
def _viv_use(*pkgs, track_exe=False, name=""): # noqa
T,F=True,False;i,s,m,e,spec=__import__,str,map,lambda x: T if x else F,[*pkgs] # noqa
if not {*m(type,pkgs)}=={s}: raise ValueError(f"spec: {pkgs} is invalid") # noqa
ge,sys,P,ew=i("os").getenv,i("sys"),i("pathlib").Path,i("sys").stderr.write # noqa
(cache:=(P(ge("XDG_CACHE_HOME",P.home()/".cache"))/"viv"/"venvs")).mkdir(parents=T,exist_ok=T) # noqa
((sha256:=i("hashlib").sha256()).update((s(spec)+ # noqa
(((exe:=("N/A",s(P(i("sys").executable).resolve()))[e(track_exe)])))).encode())) # noqa
if ((env:=cache/(name if name else (_id:=sha256.hexdigest()))) # noqa
not in cache.glob("*/")) or ge("VIV_FORCE"): # noqa
v=e(ge("VIV_VERBOSE"));ew(f"generating new vivenv -> {env.name}\n") # noqa
i("venv").EnvBuilder(with_pip=T,clear=T).create(env) # noqa
with (env/"pip.conf").open("w") as f:f.write("[global]\ndisable-pip-version-check=true") # noqa
if (p:=i("subprocess").run([env/"bin"/"pip","install","--force-reinstall",*spec],text=True, # noqa
stdout=(-1,None)[v],stderr=(-2,None)[v])).returncode!=0: # noqa
if env.is_dir():i("shutil").rmtree(env) # noqa
ew(f"pip had non zero exit ({p.returncode})\n{p.stdout}\n");sys.exit(p.returncode) # noqa
with (env/"viv-info.json").open("w") as f: # noqa
i("json").dump({"created":s(i("datetime").datetime.today()), # noqa
"id":_id,"spec":spec,"exe":exe},f) # noqa
sys.path = [p for p in (*sys.path,s(*(env/"lib").glob("py*/si*"))) if p!=i("site").USER_SITE] # noqa
return env # noqa
def _viv_use(*pkgs, track_exe=False, name=""): # noqa
T,F,N=True,False,None;i,s,m,spec=__import__,str,map,[*pkgs] # noqa
e,w=lambda x: T if x else F,lambda p,t: p.write_text(t) # noqa
if not {*m(type,pkgs)}=={s}: raise ValueError(f"spec: {pkgs} is invalid") # noqa
ge,sys,P,ew=i("os").getenv,i("sys"),i("pathlib").Path,i("sys").stderr.write # noqa
(cache:=(P(ge("XDG_CACHE_HOME",P.home()/".cache"))/"viv"/"venvs")).mkdir(parents=T,exist_ok=T) # noqa
((sha256:=i("hashlib").sha256()).update((s(spec)+ # noqa
(((exe:=("N/A",s(P(i("sys").executable).resolve()))[e(track_exe)])))).encode())) # noqa
if {env:=cache/(((_id:=sha256.hexdigest()),name)[e(name)])}-{*cache.glob("*/")} or ge("VIV_FORCE"): # noqa
v=e(ge("VIV_VERBOSE"));ew(f"generating new vivenv -> {env.name}\n") # noqa
i("venv").EnvBuilder(with_pip=T,clear=T).create(env) # noqa
w(env/"pip.conf","[global]\ndisable-pip-version-check=true") # noqa
if (rc:=(p:=i("subprocess").run([env/"bin"/"pip","install","--force-reinstall",*spec],text=T, # noqa
stdout=(-1,N)[v],stderr=(-2,N)[v])).returncode)!=0: # noqa
if env.is_dir():i("shutil").rmtree(env) # noqa
ew(f"pip had non zero exit ({rc})\n{p.stdout}\n");sys.exit(rc) # noqa
w(env/"viv-info.json",i("json").dumps( # noqa
{"created":s(i("datetime").datetime.today()),"id":_id,"spec":spec,"exe":exe})) # noqa
sys.path=[p for p in (*sys.path,s(*(env/"lib").glob("py*/si*")))if p!=i("site").USER_SITE] # noqa
return env # noqa
# fmt: on
# >>>>> code golfed with <3
import subprocess
import sys
@ -36,8 +29,8 @@ if __name__ == "__main__":
"black==23.3.0",
"click==8.1.3",
"mypy-extensions==1.0.0",
"packaging==23.1",
"packaging==23.1", # noqa
"pathspec==0.11.1",
"platformdirs==3.5.1",
)
) # noqa
sys.exit(subprocess.run([vivenv / "bin" / "black", *sys.argv[1:]]).returncode)

View file

@ -51,7 +51,7 @@ from typing import (
from urllib.error import HTTPError
from urllib.request import urlopen
__version__ = "23.5a4-9-g0a12065-dev"
__version__ = "23.5a4-14-ge257b2a-dev"
class Config:
@ -339,27 +339,25 @@ to create/activate a vivenv:
- from command line: `{a.style("viv -h","bold")}`
- within python script: {a.style('__import__("viv").use("typer", "rich-click")','bold')}
"""
_standalone_func = r"""def _viv_use(*pkgs, track_exe=False, name=""):
T,F=True,False;i,s,m,e,spec=__import__,str,map,lambda x: T if x else F,[*pkgs]
T,F,N=True,False,None;i,s,m,spec=__import__,str,map,[*pkgs]
e,w=lambda x: T if x else F,lambda p,t: p.write_text(t)
if not {*m(type,pkgs)}=={s}: raise ValueError(f"spec: {pkgs} is invalid")
ge,sys,P,ew=i("os").getenv,i("sys"),i("pathlib").Path,i("sys").stderr.write
(cache:=(P(ge("XDG_CACHE_HOME",P.home()/".cache"))/"viv"/"venvs")).mkdir(parents=T,exist_ok=T)
((sha256:=i("hashlib").sha256()).update((s(spec)+
(((exe:=("N/A",s(P(i("sys").executable).resolve()))[e(track_exe)])))).encode()))
if ((env:=cache/(name if name else (_id:=sha256.hexdigest())))
not in cache.glob("*/")) or ge("VIV_FORCE"):
if {env:=cache/(((_id:=sha256.hexdigest()),name)[e(name)])}-{*cache.glob("*/")} or ge("VIV_FORCE"):
v=e(ge("VIV_VERBOSE"));ew(f"generating new vivenv -> {env.name}\n")
i("venv").EnvBuilder(with_pip=T,clear=T).create(env)
with (env/"pip.conf").open("w") as f:f.write("[global]\ndisable-pip-version-check=true")
if (p:=i("subprocess").run([env/"bin"/"pip","install","--force-reinstall",*spec],text=True,
stdout=(-1,None)[v],stderr=(-2,None)[v])).returncode!=0:
w(env/"pip.conf","[global]\ndisable-pip-version-check=true")
if (rc:=(p:=i("subprocess").run([env/"bin"/"pip","install","--force-reinstall",*spec],text=T,
stdout=(-1,N)[v],stderr=(-2,N)[v])).returncode)!=0:
if env.is_dir():i("shutil").rmtree(env)
ew(f"pip had non zero exit ({p.returncode})\n{p.stdout}\n");sys.exit(p.returncode)
with (env/"viv-info.json").open("w") as f:
i("json").dump({"created":s(i("datetime").datetime.today()),
"id":_id,"spec":spec,"exe":exe},f)
sys.path = [p for p in (*sys.path,s(*(env/"lib").glob("py*/si*"))) if p!=i("site").USER_SITE]
ew(f"pip had non zero exit ({rc})\n{p.stdout}\n");sys.exit(rc)
w(env/"viv-info.json",i("json").dumps(
{"created":s(i("datetime").datetime.today()),"id":_id,"spec":spec,"exe":exe}))
sys.path=[p for p in (*sys.path,s(*(env/"lib").glob("py*/si*")))if p!=i("site").USER_SITE]
return env""" # noqa
def noqa(self, txt: str) -> str:
@ -371,7 +369,7 @@ to create/activate a vivenv:
if standalone:
return f"""_viv_use({fill(spec_str,width=90,subsequent_indent=" ",)})"""
else:
return f"""__import("viv").use({spec_str})"""
return f"""__import__("viv").use({spec_str})"""
def standalone(self, spec: List[str]) -> str:
func_use = self.noqa(
@ -428,7 +426,9 @@ to create/activate a vivenv:
bin: str,
) -> str:
if standalone:
imports = self._standalone_func
imports = "\n".join(
("# fmt: off", self.noqa(self._standalone_func), "# fmt: on")
)
elif path == "abs":
imports = self._absolute_import(local_source)
elif path == "rel":
@ -442,7 +442,7 @@ import subprocess
import sys
if __name__ == "__main__":
vivenv = {self._use_str(spec, standalone)}
vivenv = {self.noqa(self._use_str(spec, standalone))}
sys.exit(subprocess.run([vivenv / "bin" / "{bin}", *sys.argv[1:]]).returncode)
"""
@ -835,14 +835,8 @@ def use(*packages: str, track_exe: bool = False, name: str = "") -> Path:
def modify_sys_path(new_path: Path) -> None:
# remove user-site
for i, path in enumerate(sys.path):
if path == site.USER_SITE:
sys.path.pop(i)
sys.path.append(
str([p for p in (new_path / "lib").glob("python*/site-packages")][0])
)
sys.path = [p for p in sys.path if p is not site.USER_SITE]
site.addsitedir([*(new_path / "lib").glob("python*/site-packages")][0])
def get_venvs() -> Dict[str, ViVenv]:
@ -949,14 +943,6 @@ class Viv:
else:
self.git = False
def _check_local_source(self, args: Namespace) -> None:
if not self.local_source and not (args.standalone or args.path):
warn(
"failed to find local copy of `viv` "
"make sure to add it to your PYTHONPATH "
"or consider using --path/--standalone"
)
def _match_vivenv(self, name_id: str) -> ViVenv: # type: ignore[return]
matches: List[ViVenv] = []
for k, v in self.vivenvs.items():
@ -997,13 +983,6 @@ class Viv:
def freeze(self, args: Namespace) -> None:
"""create import statement from package spec"""
self._check_local_source(args)
if not args.reqs:
error("must specify a requirement", code=1)
if args.path and args.standalone:
error("-p/--path and -s/--standalone are mutually exclusive", code=1)
spec = resolve_deps(args)
if args.keep:
# re-create env again since path's are hard-coded
@ -1101,6 +1080,10 @@ class Viv:
f'{src.relative_to(Path.home()).parent}"\n'
)
def _get_new_version(self, ref: str) -> Tuple[str, str]:
sys.path.append(str(c.srccache))
return (sha256 := fetch_source(ref)), __import__(sha256).__version__
def manage(self, args: Namespace) -> None:
"""manage viv itself"""
@ -1121,22 +1104,7 @@ class Viv:
)
elif args.cmd == "update":
if not self.local_source:
error(
a.style("viv manage update", "bold")
+ " should be used with an exisiting installation",
1,
)
if self.git:
error(
a.style("viv manage update", "bold")
+ " shouldn't be used with a git-based installation",
1,
)
sha256 = fetch_source(args.ref)
sys.path.append(str(c.srccache))
next_version = __import__(sha256).__version__
sha256, next_version = self._get_new_version(args.ref)
if self.local_version == next_version:
echo(f"no change between {args.ref} and local version")
@ -1155,19 +1123,8 @@ class Viv:
)
elif args.cmd == "install":
if self.local_source:
error(f"found existing viv installation at {self.local_source}")
echo(
"use "
+ a.style("viv manage update", "bold")
+ " to modify current installation.",
style="red",
)
sys.exit(1)
sha256, downloaded_version = self._get_new_version(args.ref)
sha256 = fetch_source(args.ref)
sys.path.append(str(c.srccache))
downloaded_version = __import__(sha256).__version__
echo(f"Downloaded version: {downloaded_version}")
# TODO: see if file is actually where
@ -1178,6 +1135,7 @@ class Viv:
t.install(args.src, args.cli),
):
self._install_local_src(sha256, args.src, args.cli)
elif args.cmd == "purge":
to_remove = []
if c._cache.is_dir():
@ -1223,11 +1181,6 @@ class Viv:
viv shim black
viv shim yartsu -o ~/bin/yartsu --standalone
"""
self._check_local_source(args)
if not args.reqs:
error("please specify at lease one dependency", code=1)
default_bin, bin = self._pick_bin(args)
output = (
c.binparent / default_bin if not args.output else args.output.absolute()
@ -1241,9 +1194,6 @@ class Viv:
else:
spec = combined_spec(args.reqs, args.requirements)
if args.path and not self.local_source:
error("No local viv found to import from", code=1)
if confirm(
f"Write shim for {a.style(bin,'bold')} to {a.style(output,'green')}?"
):
@ -1262,8 +1212,6 @@ class Viv:
viv r pycowsay -- "viv isn't venv\!"
viv r rich -b python -- -m rich
"""
if not args.reqs:
error("please specify at lease one dependency", code=1)
_, bin = self._pick_bin(args)
spec = combined_spec(args.reqs, args.requirements)
@ -1311,6 +1259,49 @@ class Viv:
return parser
def _validate_args(self, args):
if args.func.__name__ in ("freeze", "shim", "run"):
if not args.reqs:
error("must specify a requirement", code=1)
if args.func.__name__ in ("freeze", "shim"):
if not self.local_source and not (args.standalone or args.path):
warn(
"failed to find local copy of `viv` "
"make sure to add it to your PYTHONPATH "
"or consider using --path/--standalone"
)
if args.path and not self.local_source:
error("No local viv found to import from", code=1)
if args.path and args.standalone:
error("-p/--path and -s/--standalone are mutually exclusive", code=1)
if args.func.__name__ == "manage":
if args.cmd == "install" and self.local_source:
error(f"found existing viv installation at {self.local_source}")
echo(
"use "
+ a.style("viv manage update", "bold")
+ " to modify current installation.",
style="red",
)
sys.exit(1)
if args.cmd == "update":
if not self.local_source:
error(
a.style("viv manage update", "bold")
+ " should be used with an exisiting installation",
1,
)
if self.git:
error(
a.style("viv manage update", "bold")
+ " shouldn't be used with a git-based installation",
1,
)
def cli(self) -> None:
"""cli entrypoint"""
@ -1509,6 +1500,7 @@ class Viv:
args = parser.parse_args()
args.rest = []
self._validate_args(args)
args.func(
args,
)