mirror of
https://github.com/daylinmorgan/viv.git
synced 2024-09-20 03:57:18 -05:00
Compare commits
7 commits
ed109d65a4
...
6e940fc594
Author | SHA1 | Date | |
---|---|---|---|
6e940fc594 | |||
30cb4b5faf | |||
f069a26fdb | |||
39f7790e1c | |||
64d05e37de | |||
5e89d63b66 | |||
4b61cb9381 |
1 changed files with 119 additions and 62 deletions
181
src/viv/viv.py
181
src/viv/viv.py
|
@ -51,7 +51,7 @@ from typing import (
|
||||||
Generator,
|
Generator,
|
||||||
)
|
)
|
||||||
|
|
||||||
__version__ = "22.12a3-48-gf87aab9-dev"
|
__version__ = "22.12a3-48-g30cb4b5-dev"
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
@ -61,9 +61,16 @@ class Config:
|
||||||
venvcache: Path = (
|
venvcache: Path = (
|
||||||
Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache")) / "viv" / "venvs"
|
Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache")) / "viv" / "venvs"
|
||||||
)
|
)
|
||||||
|
srccache: Path = (
|
||||||
|
Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache")) / "viv" / "src"
|
||||||
|
)
|
||||||
|
|
||||||
def __post_init__(self) -> None:
|
def __post_init__(self) -> None:
|
||||||
self.venvcache.mkdir(parents=True, exist_ok=True)
|
self.venvcache.mkdir(parents=True, exist_ok=True)
|
||||||
|
self.srccache.mkdir(
|
||||||
|
parents=True,
|
||||||
|
exist_ok=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
c = Config()
|
c = Config()
|
||||||
|
@ -528,8 +535,7 @@ STANDALONE_TEMPLATE = r"""
|
||||||
# >>>>> code golfed with <3
|
# >>>>> code golfed with <3
|
||||||
""" # noqa
|
""" # noqa
|
||||||
|
|
||||||
STANDALONE_TEMPLATE_USE = r"""
|
STANDALONE_TEMPLATE_USE = r"""def _viv_use(*pkgs: str, track_exe: bool = False, name: str = "") -> None:
|
||||||
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]
|
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")
|
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
|
ge,sys,P,ew=i("os").getenv,i("sys"),i("pathlib").Path,i("sys").stderr.write
|
||||||
|
@ -548,14 +554,19 @@ def _viv_use(*pkgs: str, track_exe: bool = False, name: str = "") -> None:
|
||||||
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]
|
sys.path = [p for p in (*sys.path,s(*(env/"lib").glob("py*/si*"))) if p!=i("site").USER_SITE]
|
||||||
_viv_use({spec})
|
_viv_use({spec})
|
||||||
"""[ # noqa
|
""" # noqa
|
||||||
1:
|
|
||||||
]
|
|
||||||
|
|
||||||
SHOW_TEMPLATE = f"""\
|
SHOW_TEMPLATE = f"""
|
||||||
{a.style('Version', 'bold')}: {{version}}
|
{a.style('Version', 'bold')}: {{version}}
|
||||||
{a.style('CLI', 'bold')}: {{cli}}
|
{a.style('CLI', 'bold')}: {{cli}}
|
||||||
{a.style('Source File', 'bold')}: {{src}}
|
{a.style('Current Source', 'bold')}: {{src}}
|
||||||
|
"""
|
||||||
|
|
||||||
|
INSTALL_TEMPLATE = f"""
|
||||||
|
|
||||||
|
Install viv.py to {a.bold}{{src_location}}{a.end}
|
||||||
|
Symlink {a.bold}{{src_location}}{a.end} to {a.bold}{{cli_location}}{a.end}
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@ -710,7 +721,7 @@ class CustomHelpFormatter(RawDescriptionHelpFormatter, HelpFormatter):
|
||||||
# determine the required width and the entry label
|
# determine the required width and the entry label
|
||||||
help_position = min(self._action_max_length + 2, self._max_help_position)
|
help_position = min(self._action_max_length + 2, self._max_help_position)
|
||||||
help_width = max(self._width - help_position, 11)
|
help_width = max(self._width - help_position, 11)
|
||||||
action_width = help_position - self._current_indent - 2
|
action_width = help_position - self._current_indent
|
||||||
action_header = self._format_action_invocation(action)
|
action_header = self._format_action_invocation(action)
|
||||||
action_header_len = len(a.escape(action_header))
|
action_header_len = len(a.escape(action_header))
|
||||||
|
|
||||||
|
@ -782,7 +793,8 @@ class ArgumentParser(StdArgParser):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
self.formatter_class = lambda prog: CustomHelpFormatter(
|
self.formatter_class = lambda prog: CustomHelpFormatter(
|
||||||
prog, max_help_position=35
|
prog,
|
||||||
|
max_help_position=35,
|
||||||
)
|
)
|
||||||
|
|
||||||
def error(self, message: str) -> NoReturn:
|
def error(self, message: str) -> NoReturn:
|
||||||
|
@ -804,9 +816,43 @@ within python script:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_source(reference: str) -> str:
|
||||||
|
try:
|
||||||
|
r = urlopen(
|
||||||
|
"https://raw.githubusercontent.com/daylinmorgan/viv/"
|
||||||
|
+ reference
|
||||||
|
+ "/src/viv/viv.py"
|
||||||
|
)
|
||||||
|
except HTTPError as e:
|
||||||
|
error(
|
||||||
|
"Issue updating viv see below:"
|
||||||
|
+ a.style("-> ", "red").join(["\n"] + repr(e).splitlines())
|
||||||
|
)
|
||||||
|
if "404" in repr(e):
|
||||||
|
echo("Please check your reference is valid.", style="red")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
src = r.read()
|
||||||
|
(hash := hashlib.sha256()).update(src)
|
||||||
|
sha256 = hash.hexdigest()
|
||||||
|
|
||||||
|
cached_src_file = c.srccache / f"{sha256}.py"
|
||||||
|
|
||||||
|
if not cached_src_file.is_file():
|
||||||
|
with cached_src_file.open("w") as f:
|
||||||
|
f.write(src.decode())
|
||||||
|
|
||||||
|
return sha256
|
||||||
|
|
||||||
|
|
||||||
class Viv:
|
class Viv:
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.vivenvs = get_venvs()
|
self.vivenvs = get_venvs()
|
||||||
|
self.current_source = Path(__file__).resolve()
|
||||||
|
self.local = not str(self.current_source).startswith("/proc/")
|
||||||
|
self.name = (
|
||||||
|
"python3 <(curl -fsSL gh.dayl.in/viv/viv.py)" if self.local else "viv"
|
||||||
|
)
|
||||||
|
|
||||||
def _match_vivenv(self, name_id: str) -> ViVenv: # type: ignore[return]
|
def _match_vivenv(self, name_id: str) -> ViVenv: # type: ignore[return]
|
||||||
# TODO: improve matching algorithm to favor names over id's
|
# TODO: improve matching algorithm to favor names over id's
|
||||||
|
@ -918,8 +964,7 @@ class Viv:
|
||||||
"""manage viv installation"""
|
"""manage viv installation"""
|
||||||
|
|
||||||
if args.cmd == "show":
|
if args.cmd == "show":
|
||||||
# NOTE: could reuse the table output for this?
|
echo("Current:")
|
||||||
echo("Installation Info:")
|
|
||||||
sys.stdout.write(
|
sys.stdout.write(
|
||||||
SHOW_TEMPLATE.format(
|
SHOW_TEMPLATE.format(
|
||||||
version=__version__,
|
version=__version__,
|
||||||
|
@ -929,58 +974,66 @@ class Viv:
|
||||||
)
|
)
|
||||||
|
|
||||||
elif args.cmd == "update":
|
elif args.cmd == "update":
|
||||||
echo(__file__)
|
if not self.local:
|
||||||
echo(Path(__file__))
|
|
||||||
if str(Path(__file__).resolve()).startswith("/proc/"):
|
|
||||||
error(
|
error(
|
||||||
a.style("viv manage update", "bold")
|
a.style("viv manage update", "bold")
|
||||||
+ "should be used with a locally installed viv",
|
+ " should only be used with a locally installed viv",
|
||||||
1,
|
1,
|
||||||
)
|
)
|
||||||
try:
|
#
|
||||||
r = urlopen(
|
# viv_src = fetch_source(args.reference)
|
||||||
"https://raw.githubusercontent.com/daylinmorgan/viv/"
|
#
|
||||||
+ args.reference
|
# (hash := hashlib.sha256()).update(viv_src)
|
||||||
+ "/src/viv/viv.py"
|
# sha256 = hash.hexdigest()
|
||||||
)
|
#
|
||||||
except HTTPError as e:
|
# (
|
||||||
error(
|
# src_cache := Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache"))
|
||||||
"Issue updating viv see below:"
|
# / "viv"
|
||||||
+ a.style("-> ", "red").join(["\n"] + repr(e).splitlines())
|
# / "src"
|
||||||
)
|
# ).mkdir(exist_ok=True, parents=True)
|
||||||
if "404" in repr(e):
|
# cached_version = src_cache / f"{sha256}.py"
|
||||||
echo("Please check your reference is valid.", style="red")
|
#
|
||||||
sys.exit(1)
|
# if not cached_version.is_file():
|
||||||
|
# with cached_version.open("w") as f:
|
||||||
viv_src = r.read()
|
# f.write(viv_src.decode())
|
||||||
|
#
|
||||||
(hash := hashlib.sha256()).update(viv_src)
|
sha256 = fetch_source(args.reference)
|
||||||
sha256 = hash.hexdigest()
|
sys.path.append(str(c.srccache))
|
||||||
|
|
||||||
(
|
|
||||||
src_cache := Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache"))
|
|
||||||
/ "viv"
|
|
||||||
/ "src"
|
|
||||||
).mkdir(exist_ok=True, parents=True)
|
|
||||||
cached_version = src_cache / f"{sha256}.py"
|
|
||||||
|
|
||||||
if not cached_version.is_file():
|
|
||||||
with cached_version.open("w") as f:
|
|
||||||
f.write(viv_src.decode())
|
|
||||||
|
|
||||||
sys.path.append(str(src_cache))
|
|
||||||
next_version = __import__(sha256).__version__
|
next_version = __import__(sha256).__version__
|
||||||
|
|
||||||
q = (
|
q = (
|
||||||
"Update source at: "
|
"Update source at: "
|
||||||
+ a.style(Path(__file__).resolve(), "bold")
|
+ a.style(self.current_source, "bold")
|
||||||
+ f" \n from version {__version__} to {next_version}?"
|
+ f" \n from version {__version__} to {next_version}?"
|
||||||
)
|
)
|
||||||
|
|
||||||
if confirm(q):
|
if confirm(q):
|
||||||
print("AWAY THEN")
|
print("Holding off on the additions of this piece")
|
||||||
|
|
||||||
elif args.cmd == "install":
|
elif args.cmd == "install":
|
||||||
echo("not yet implemented. sorry")
|
if self.local:
|
||||||
|
error(
|
||||||
|
a.style("viv manage install", "bold")
|
||||||
|
+ " should only be used with a remote viv",
|
||||||
|
)
|
||||||
|
echo(
|
||||||
|
"use "
|
||||||
|
+ a.style("viv manage update", "bold")
|
||||||
|
+ " to modify current installation.",
|
||||||
|
style="red",
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
sha256 = fetch_source(args.reference)
|
||||||
|
sys.path.append(str(c.srccache))
|
||||||
|
downloaded_version = __import__(sha256).__version__
|
||||||
|
echo(f"Downloaded version: {downloaded_version}")
|
||||||
|
q = INSTALL_TEMPLATE.format(
|
||||||
|
src_location="~/.local/share/viv/viv.py", cli_location="~/bin/viv"
|
||||||
|
) + ("Would you like to perform the above " "installation steps?")
|
||||||
|
|
||||||
|
if confirm(q):
|
||||||
|
print("AWAY MAN")
|
||||||
|
|
||||||
def _get_subcmd_parser(
|
def _get_subcmd_parser(
|
||||||
self,
|
self,
|
||||||
|
@ -1005,7 +1058,7 @@ class Viv:
|
||||||
def cli(self) -> None:
|
def cli(self) -> None:
|
||||||
"""cli entrypoint"""
|
"""cli entrypoint"""
|
||||||
|
|
||||||
parser = ArgumentParser(description=description)
|
parser = ArgumentParser(prog=self.name, description=description)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"-V",
|
"-V",
|
||||||
"--version",
|
"--version",
|
||||||
|
@ -1018,10 +1071,7 @@ class Viv:
|
||||||
)
|
)
|
||||||
p_vivenv_arg = ArgumentParser(add_help=False)
|
p_vivenv_arg = ArgumentParser(add_help=False)
|
||||||
p_vivenv_arg.add_argument("vivenv", help="name/hash of vivenv")
|
p_vivenv_arg.add_argument("vivenv", help="name/hash of vivenv")
|
||||||
p_list = self._get_subcmd_parser(
|
p_list = self._get_subcmd_parser(subparsers, "list")
|
||||||
subparsers,
|
|
||||||
"list",
|
|
||||||
)
|
|
||||||
|
|
||||||
p_list.add_argument(
|
p_list.add_argument(
|
||||||
"-q",
|
"-q",
|
||||||
|
@ -1103,15 +1153,22 @@ class Viv:
|
||||||
subparsers, name="manage"
|
subparsers, name="manage"
|
||||||
).add_subparsers(title="subcommand", metavar="<sub-cmd>", required=True)
|
).add_subparsers(title="subcommand", metavar="<sub-cmd>", required=True)
|
||||||
|
|
||||||
p_manage_sub.add_parser(
|
# TODO: shared parser?
|
||||||
"install",
|
(
|
||||||
help="install viv",
|
p_manage_install := p_manage_sub.add_parser(
|
||||||
|
"install", help="install viv", aliases="i"
|
||||||
|
)
|
||||||
).set_defaults(func=self.manage, cmd="install")
|
).set_defaults(func=self.manage, cmd="install")
|
||||||
|
p_manage_install.add_argument(
|
||||||
|
"-r",
|
||||||
|
"--reference",
|
||||||
|
help="git reference (branch/tag/commit)",
|
||||||
|
default="main",
|
||||||
|
)
|
||||||
|
|
||||||
(
|
(
|
||||||
p_manage_update := p_manage_sub.add_parser(
|
p_manage_update := p_manage_sub.add_parser(
|
||||||
"update",
|
"update", help="update viv version", aliases="u"
|
||||||
help="update viv version",
|
|
||||||
)
|
)
|
||||||
).set_defaults(func=self.manage, cmd="update")
|
).set_defaults(func=self.manage, cmd="update")
|
||||||
|
|
||||||
|
@ -1123,7 +1180,7 @@ class Viv:
|
||||||
)
|
)
|
||||||
|
|
||||||
p_manage_sub.add_parser(
|
p_manage_sub.add_parser(
|
||||||
"show", help="show current installation info"
|
"show", help="show current installation info", aliases="s"
|
||||||
).set_defaults(func=self.manage, cmd="show")
|
).set_defaults(func=self.manage, cmd="show")
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
Loading…
Reference in a new issue