mirror of
https://github.com/daylinmorgan/viv.git
synced 2024-11-13 20:47:53 -06:00
Compare commits
3 commits
a350fa30b7
...
954a7b556e
Author | SHA1 | Date | |
---|---|---|---|
954a7b556e | |||
9a76c5e672 | |||
baad1783a2 |
1 changed files with 63 additions and 102 deletions
165
src/viv/viv.py
165
src/viv/viv.py
|
@ -52,40 +52,46 @@ from typing import (
|
|||
from urllib.error import HTTPError
|
||||
from urllib.request import urlopen
|
||||
|
||||
__version__ = "23.5a1-18-g187f070"
|
||||
__version__ = "23.5a1-14-g9a76c5e"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Config:
|
||||
"""viv config manager"""
|
||||
|
||||
def __init__(self):
|
||||
self._cache = Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache")) / "viv"
|
||||
|
||||
def _ensure(self, p: Path) -> Path:
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
_venvcache: Path = (
|
||||
Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache")) / "viv" / "venvs"
|
||||
)
|
||||
_srccache: Path = (
|
||||
Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache")) / "viv" / "src"
|
||||
)
|
||||
_share: Path = (
|
||||
Path(os.getenv("XDG_DATA_HOME", Path.home() / ".local" / "share")) / "viv"
|
||||
)
|
||||
_binparent: Path = Path(os.getenv("VIV_BIN_DIR", Path.home() / ".local" / "bin"))
|
||||
|
||||
@property
|
||||
def venvcache(self):
|
||||
return self._ensure(self._cache / "venvs")
|
||||
self._venvcache.mkdir(parents=True, exist_ok=True)
|
||||
return self._venvcache
|
||||
|
||||
@property
|
||||
def srccache(self):
|
||||
return self._ensure(self._cache / "src")
|
||||
self._srccache.mkdir(parents=True, exist_ok=True)
|
||||
return self._srccache
|
||||
|
||||
@property
|
||||
def share(self):
|
||||
self._share.mkdir(parents=True, exist_ok=True)
|
||||
return self._share
|
||||
|
||||
@property
|
||||
def binparent(self):
|
||||
return self._ensure(
|
||||
Path(os.getenv("VIV_BIN_DIR", Path.home() / ".local" / "bin"))
|
||||
)
|
||||
self._binparent.mkdir(parents=True, exist_ok=True)
|
||||
return self._binparent
|
||||
|
||||
@property
|
||||
def srcdefault(self) -> None:
|
||||
parent = (
|
||||
Path(os.getenv("XDG_DATA_HOME", Path.home() / ".local" / "share")) / "viv"
|
||||
)
|
||||
return self._ensure(parent) / "viv.py"
|
||||
|
||||
return self.share / "viv.py"
|
||||
|
||||
c = Config()
|
||||
|
||||
|
@ -491,7 +497,7 @@ class ViVenv:
|
|||
a.table((("key", "value"), *((k, v) for k, v in info.items())))
|
||||
|
||||
|
||||
def use(*packages: str, track_exe: bool = False, name: str = "") -> Path:
|
||||
def use(*packages: str, track_exe: bool = False, name: str = "") -> ViVenv:
|
||||
"""create a vivenv and append to sys.path
|
||||
|
||||
Args:
|
||||
|
@ -510,7 +516,7 @@ def use(*packages: str, track_exe: bool = False, name: str = "") -> Path:
|
|||
vivenv.dump_info(write=True)
|
||||
|
||||
modify_sys_path(vivenv.path)
|
||||
return vivenv.path
|
||||
return vivenv
|
||||
|
||||
|
||||
def validate_spec(spec: Tuple[str, ...]) -> None:
|
||||
|
@ -560,27 +566,25 @@ STANDALONE_TEMPLATE = r"""
|
|||
# >>>>> code golfed with <3
|
||||
""" # noqa
|
||||
|
||||
STANDALONE_TEMPLATE_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]
|
||||
if not {*m(type,pkgs)}=={s}: raise ValueError(f"spec: {pkgs} is invalid")
|
||||
STANDALONE_TEMPLATE_FUNC = r"""def _viv_use(*pkgs: str, track_exe: bool = False, name: str = "") -> None:
|
||||
i,s,m,e,spec=__import__,str,map,lambda x: True if x else False,[*pkgs]
|
||||
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)
|
||||
(cache:=(P(ge("XDG_CACHE_HOME",P.home()/".cache"))/"viv"/"venvs")).mkdir(parents=True,exist_ok=True)
|
||||
((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"):
|
||||
v=e(ge("VIV_VERBOSE"));ew(f"generating new vivenv -> {env.name}\n")
|
||||
i("venv").EnvBuilder(with_pip=T,clear=T).create(env)
|
||||
if (env:=cache/(name if name else (_id:=sha256.hexdigest()))) not in cache.glob("*/") or ge("VIV_FORCE"):
|
||||
v=e(ge("VIV_VERBOSE"));ew(f"generating new vivenv -> {{env.name}}\n")
|
||||
i("venv").EnvBuilder(with_pip=True,clear=True).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:
|
||||
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)
|
||||
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)
|
||||
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]
|
||||
return env
|
||||
{use}
|
||||
""" # noqa
|
||||
|
||||
SHOW_TEMPLATE = f"""
|
||||
|
@ -605,14 +609,12 @@ UPDATE_TEMPLATE = f"""
|
|||
|
||||
SHIM_TEMPLATE = """\
|
||||
#!/usr/bin/env python3
|
||||
|
||||
{imports}
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
vivenv = {use}
|
||||
sys.exit(subprocess.run([vivenv / "bin" / "{bin}", *sys.argv[1:]]).returncode)
|
||||
sys.exit(subprocess.run([vivenv.path / "bin" / "{bin}", *sys.argv[1:]]).returncode)
|
||||
"""
|
||||
|
||||
|
||||
|
@ -685,14 +687,15 @@ def generate_import(
|
|||
STANDALONE_TEMPLATE.format(
|
||||
version=__version__,
|
||||
func=noqa(
|
||||
STANDALONE_TEMPLATE_FUNC
|
||||
+ "_viv_use("
|
||||
+ fill(
|
||||
", ".join(f'"{pkg}"' for pkg in resolved_spec.splitlines()),
|
||||
width=100,
|
||||
subsequent_indent=" ",
|
||||
STANDALONE_TEMPLATE_FUNC.format(
|
||||
use="_viv_use("
|
||||
+ fill(
|
||||
", ".join(f'"{pkg}"' for pkg in resolved_spec.splitlines()),
|
||||
width=100,
|
||||
subsequent_indent=" ",
|
||||
)
|
||||
+ ")"
|
||||
)
|
||||
+ ")"
|
||||
),
|
||||
)
|
||||
+ "\n"
|
||||
|
@ -919,24 +922,15 @@ class Viv:
|
|||
try:
|
||||
_local_viv = __import__("viv")
|
||||
self.local_source = (
|
||||
Path(_local_viv.__file__) if _local_viv.__file__ else "Not Found"
|
||||
_local_viv.__file__ if _local_viv.__file__ else "Not Found"
|
||||
)
|
||||
self.local_version = _local_viv.__version__
|
||||
except ImportError:
|
||||
self.local_source = self.local_version = "Not Found"
|
||||
|
||||
if self.local_source != "Not Found":
|
||||
self.git = (self.local_source.parent.parent.parent / ".git").is_dir()
|
||||
else:
|
||||
self.git = False
|
||||
|
||||
def _check_local_source(self, args: Namespace) -> None:
|
||||
if self.local_source == "Not Found" 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"
|
||||
)
|
||||
self.git = self.local_source != "Not Found" and str(self.local_source).endswith(
|
||||
"src/viv/__init__.py"
|
||||
)
|
||||
|
||||
def _match_vivenv(self, name_id: str) -> ViVenv: # type: ignore[return]
|
||||
# TODO: improve matching algorithm to favor names over id's
|
||||
|
@ -978,8 +972,10 @@ class Viv:
|
|||
|
||||
def freeze(self, args: Namespace) -> None:
|
||||
"""create import statement from package spec"""
|
||||
|
||||
self._check_local_source(args)
|
||||
# TODO: warn user about using anything but standalone when
|
||||
# self.local_source is 'Not Found'
|
||||
if self.local_source == "Not Found" and not (args.standalone or args.path):
|
||||
warn("failed to find local copy of `viv` make sure to add it to your PYTHONPATH")
|
||||
|
||||
if not args.reqs:
|
||||
error("must specify a requirement", code=1)
|
||||
|
@ -1156,55 +1152,23 @@ class Viv:
|
|||
|
||||
def shim(self, args):
|
||||
"""generate viv-powered cli apps"""
|
||||
self._check_local_source(args)
|
||||
# TODO: robustness....
|
||||
|
||||
if not args.reqs:
|
||||
error("please specify at lease one dependency", code=1)
|
||||
|
||||
# TODO: generalize freeze and this spec generator
|
||||
spec = ", ".join(f'"{req}"' for req in args.reqs)
|
||||
|
||||
# TODO: split first req on version specifier characters... use re?
|
||||
|
||||
bin = args.reqs[0] if not args.bin else args.bin
|
||||
output = (
|
||||
c.binparent / args.reqs[0] if not args.output else args.output.absolute()
|
||||
)
|
||||
if len(args.reqs) == 1:
|
||||
bin = args.reqs[0]
|
||||
output = Path.cwd() / args.reqs[0]
|
||||
else:
|
||||
error("please specify an explicit -b/--bin and -o/--output")
|
||||
|
||||
if output.is_file():
|
||||
error(f"{output} already exists...exiting", code=1)
|
||||
|
||||
if args.standalone:
|
||||
imports = STANDALONE_TEMPLATE.format(
|
||||
version=__version__, func=noqa(STANDALONE_TEMPLATE_FUNC)
|
||||
)
|
||||
use = f"_viv_use({spec})"
|
||||
elif args.path:
|
||||
if self.local_source == "Not Found":
|
||||
error("No local viv found to import from", code=1)
|
||||
imports = (
|
||||
REL_SYS_PATH_TEMPLATE.format(
|
||||
path_to_viv=str(
|
||||
self.local_source.resolve().absolute().parent.parent
|
||||
).replace(str(Path.home()), "~")
|
||||
)
|
||||
if args.path == "abs"
|
||||
else SYS_PATH_TEMPLATE.format(
|
||||
path_to_viv=self.local_source.resolve().absolute().parent.parent
|
||||
)
|
||||
)
|
||||
use = IMPORT_TEMPLATE.format(spec=spec)
|
||||
else:
|
||||
imports = ""
|
||||
use = IMPORT_TEMPLATE.format(spec=spec)
|
||||
with output.open("w") as f:
|
||||
f.write(SHIM_TEMPLATE.format(use=f'__import__("viv").use({spec})', bin=bin))
|
||||
|
||||
if confirm(
|
||||
f"Write shim for {a.style(bin,'bold')} to {a.style(output,'green')}?"
|
||||
):
|
||||
with output.open("w") as f:
|
||||
f.write(SHIM_TEMPLATE.format(imports=imports, use=use, bin=bin))
|
||||
|
||||
make_executable(output)
|
||||
make_executable(output)
|
||||
|
||||
def _get_subcmd_parser(
|
||||
self,
|
||||
|
@ -1374,10 +1338,7 @@ class Viv:
|
|||
)
|
||||
).set_defaults(func=self.shim, cmd="shim")
|
||||
p_manage_shim.add_argument(
|
||||
"-f",
|
||||
"--freeze",
|
||||
help="freeze/resolve all dependencies",
|
||||
action="store_true",
|
||||
'-f',"--freeze", help="freeze/resolve all dependencies", action="store_true"
|
||||
)
|
||||
p_manage_shim.add_argument(
|
||||
"-o",
|
||||
|
|
Loading…
Reference in a new issue