mirror of
https://github.com/daylinmorgan/viv.git
synced 2024-11-12 20:23:15 -06:00
Compare commits
16 commits
6e940fc594
...
d4d304793c
Author | SHA1 | Date | |
---|---|---|---|
d4d304793c | |||
f27cdf85d3 | |||
72ae9e47e2 | |||
03b75ec2d3 | |||
43e5bde290 | |||
1cabd09cc4 | |||
70033732ff | |||
c5043ff3c3 | |||
8277a547bb | |||
4566e2ecbc | |||
f1a310aee3 | |||
79d7978a11 | |||
6d98e2a755 | |||
312ed47381 | |||
0939736304 | |||
4932d2b417 |
2 changed files with 157 additions and 80 deletions
|
@ -1 +1 @@
|
||||||
from .viv import use # noqa
|
from .viv import use, __version__ # noqa
|
||||||
|
|
235
src/viv/viv.py
235
src/viv/viv.py
|
@ -41,6 +41,7 @@ from types import TracebackType
|
||||||
from typing import (
|
from typing import (
|
||||||
Any,
|
Any,
|
||||||
Dict,
|
Dict,
|
||||||
|
Generator,
|
||||||
List,
|
List,
|
||||||
NoReturn,
|
NoReturn,
|
||||||
Optional,
|
Optional,
|
||||||
|
@ -48,10 +49,9 @@ from typing import (
|
||||||
TextIO,
|
TextIO,
|
||||||
Tuple,
|
Tuple,
|
||||||
Type,
|
Type,
|
||||||
Generator,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
__version__ = "22.12a3-48-g30cb4b5-dev"
|
__version__ = "22.12a3-64-gf27cdf8-dev"
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
@ -64,6 +64,11 @@ class Config:
|
||||||
srccache: Path = (
|
srccache: Path = (
|
||||||
Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache")) / "viv" / "src"
|
Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache")) / "viv" / "src"
|
||||||
)
|
)
|
||||||
|
srcdefault: Path = (
|
||||||
|
Path(os.getenv("XDG_DATA_HOME", Path.home() / ".local" / "share"))
|
||||||
|
/ "viv"
|
||||||
|
/ "viv.py"
|
||||||
|
)
|
||||||
|
|
||||||
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)
|
||||||
|
@ -71,6 +76,7 @@ class Config:
|
||||||
parents=True,
|
parents=True,
|
||||||
exist_ok=True,
|
exist_ok=True,
|
||||||
)
|
)
|
||||||
|
self.srcdefault.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
c = Config()
|
c = Config()
|
||||||
|
@ -244,6 +250,9 @@ class Ansi:
|
||||||
else:
|
else:
|
||||||
return (row,)
|
return (row,)
|
||||||
|
|
||||||
|
def viv_preamble(self, style: str = "magenta", sep: str = "::") -> str:
|
||||||
|
return f"{self.cyan}Viv{self.end}{self.__dict__[style]}{sep}{self.end}"
|
||||||
|
|
||||||
def table(
|
def table(
|
||||||
self, rows: Tuple[Tuple[str, Sequence[str]], ...], header_style: str = "cyan"
|
self, rows: Tuple[Tuple[str, Sequence[str]], ...], header_style: str = "cyan"
|
||||||
) -> None:
|
) -> None:
|
||||||
|
@ -308,20 +317,25 @@ def echo(
|
||||||
msg: str, style: str = "magenta", newline: bool = True, fd: TextIO = sys.stderr
|
msg: str, style: str = "magenta", newline: bool = True, fd: TextIO = sys.stderr
|
||||||
) -> None:
|
) -> None:
|
||||||
"""output general message to stdout"""
|
"""output general message to stdout"""
|
||||||
output = f"{a.cyan}Viv{a.end}{a.__dict__[style]}::{a.end} {msg}"
|
output = f"{a.viv_preamble(style)} {msg}"
|
||||||
if newline:
|
if newline:
|
||||||
output += "\n"
|
output += "\n"
|
||||||
fd.write(output)
|
fd.write(output)
|
||||||
|
|
||||||
|
|
||||||
def confirm(question: str) -> bool:
|
def confirm(question: str, context: str = "") -> bool:
|
||||||
|
sys.stderr.write(context)
|
||||||
|
sys.stderr.write(
|
||||||
|
a.viv_preamble(sep="?? ") + question + a.style(" (Y)es/(n)o: ", "yellow")
|
||||||
|
)
|
||||||
while True:
|
while True:
|
||||||
ans = input(question + a.style(" (Y)es/(n)o: ", "yellow")).strip().lower()
|
ans = input().strip().lower()
|
||||||
if ans in ("y", "yes"):
|
if ans in ("y", "yes"):
|
||||||
return True
|
return True
|
||||||
elif ans in ("n", "no"):
|
elif ans in ("n", "no"):
|
||||||
return False
|
return False
|
||||||
sys.stdout.write("\nPlease select (Y)es or (n)o.")
|
sys.stdout.write("Please select (Y)es or (n)o. ")
|
||||||
|
sys.stdout.write("\n")
|
||||||
|
|
||||||
|
|
||||||
def run(
|
def run(
|
||||||
|
@ -559,16 +573,23 @@ _viv_use({spec})
|
||||||
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('Current Source', 'bold')}: {{src}}
|
{a.style('Running Source', 'bold')}: {{running_src}}
|
||||||
|
{a.style('Local Source', 'bold')}: {{local_src}}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
INSTALL_TEMPLATE = f"""
|
INSTALL_TEMPLATE = f"""
|
||||||
|
Install viv.py to {a.green}{{src_location}}{a.end}
|
||||||
Install viv.py to {a.bold}{{src_location}}{a.end}
|
|
||||||
Symlink {a.bold}{{src_location}}{a.end} to {a.bold}{{cli_location}}{a.end}
|
Symlink {a.bold}{{src_location}}{a.end} to {a.bold}{{cli_location}}{a.end}
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
UPDATE_TEMPLATE = f"""
|
||||||
|
Update source at {a.green}{{src_location}}{a.end}
|
||||||
|
Symlink {a.bold}{{src_location}}{a.end} to {a.bold}{{cli_location}}{a.end}
|
||||||
|
Version {a.bold}{{local_version}}{a.end} -> {a.bold}{{next_version}}{a.end}
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
def noqa(txt: str) -> str:
|
def noqa(txt: str) -> str:
|
||||||
max_length = max(map(len, txt.splitlines()))
|
max_length = max(map(len, txt.splitlines()))
|
||||||
|
@ -807,12 +828,9 @@ class ArgumentParser(StdArgParser):
|
||||||
description = f"""
|
description = f"""
|
||||||
|
|
||||||
{a.tagline()}
|
{a.tagline()}
|
||||||
|
to create/activate a vivenv:
|
||||||
{a.style('create/activate a vivenv','underline')}
|
- from command line: `{a.style("viv -h","bold")}`
|
||||||
from command line:
|
- within python script: {a.style('__import__("viv").use("typer", "rich-click")','bold')}
|
||||||
`{a.style("viv -h","bold")}`
|
|
||||||
within python script:
|
|
||||||
{a.style('__import__("viv").use("typer", "rich-click")','bold')}
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@ -845,13 +863,40 @@ def fetch_source(reference: str) -> str:
|
||||||
return sha256
|
return sha256
|
||||||
|
|
||||||
|
|
||||||
|
def make_executable(path: Path) -> None:
|
||||||
|
"""apply an executable bit for all users with read access"""
|
||||||
|
mode = os.stat(path).st_mode
|
||||||
|
mode |= (mode & 0o444) >> 2 # copy R bits to X
|
||||||
|
os.chmod(path, mode)
|
||||||
|
|
||||||
|
|
||||||
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._get_sources()
|
||||||
self.local = not str(self.current_source).startswith("/proc/")
|
|
||||||
self.name = (
|
self.name = (
|
||||||
"python3 <(curl -fsSL gh.dayl.in/viv/viv.py)" if self.local else "viv"
|
"viv" if self.local else "python3 <(curl -fsSL gh.dayl.in/viv/viv.py)"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _get_sources(self) -> None:
|
||||||
|
self.local_source: Path | str
|
||||||
|
self.running_source = Path(__file__).resolve()
|
||||||
|
self.local = not str(self.running_source).startswith("/proc/")
|
||||||
|
if self.local:
|
||||||
|
self.local_source = self.running_source
|
||||||
|
self.local_version = __version__
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
_local_viv = __import__("viv")
|
||||||
|
self.local_source = (
|
||||||
|
_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"
|
||||||
|
|
||||||
|
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]
|
def _match_vivenv(self, name_id: str) -> ViVenv: # type: ignore[return]
|
||||||
|
@ -960,8 +1005,26 @@ class Viv:
|
||||||
|
|
||||||
vivenv.dump_info()
|
vivenv.dump_info()
|
||||||
|
|
||||||
|
def _install_local_src(self, sha256: str, src: Path, cli: Path) -> None:
|
||||||
|
echo("updating local source copy of viv")
|
||||||
|
shutil.copy(c.srccache / f"{sha256}.py", src)
|
||||||
|
make_executable(src)
|
||||||
|
echo("symlinking cli")
|
||||||
|
|
||||||
|
if not cli.is_file():
|
||||||
|
cli.symlink_to(src)
|
||||||
|
else:
|
||||||
|
cli.unlink()
|
||||||
|
cli.symlink_to(src)
|
||||||
|
|
||||||
|
echo("Remember to include the following line in your shell rc file:")
|
||||||
|
sys.stderr.write(
|
||||||
|
' export PYTHONPATH="$PYTHONPATH:$HOME/'
|
||||||
|
f'{src.relative_to(Path.home())}"\n'
|
||||||
|
)
|
||||||
|
|
||||||
def manage(self, args: Namespace) -> None:
|
def manage(self, args: Namespace) -> None:
|
||||||
"""manage viv installation"""
|
"""manage viv itself"""
|
||||||
|
|
||||||
if args.cmd == "show":
|
if args.cmd == "show":
|
||||||
echo("Current:")
|
echo("Current:")
|
||||||
|
@ -969,53 +1032,55 @@ class Viv:
|
||||||
SHOW_TEMPLATE.format(
|
SHOW_TEMPLATE.format(
|
||||||
version=__version__,
|
version=__version__,
|
||||||
cli=shutil.which("viv"),
|
cli=shutil.which("viv"),
|
||||||
src=Path(__file__).resolve(),
|
running_src=self.running_source,
|
||||||
|
local_src=self.local_source,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
elif args.cmd == "update":
|
elif args.cmd == "update":
|
||||||
if not self.local:
|
if self.local_source == "Not Found":
|
||||||
error(
|
error(
|
||||||
a.style("viv manage update", "bold")
|
a.style("viv manage update", "bold")
|
||||||
+ " should only be used with a locally installed viv",
|
+ " 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,
|
1,
|
||||||
)
|
)
|
||||||
#
|
|
||||||
# viv_src = fetch_source(args.reference)
|
|
||||||
#
|
|
||||||
# (hash := hashlib.sha256()).update(viv_src)
|
|
||||||
# sha256 = hash.hexdigest()
|
|
||||||
#
|
|
||||||
# (
|
|
||||||
# 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())
|
|
||||||
#
|
|
||||||
sha256 = fetch_source(args.reference)
|
sha256 = fetch_source(args.reference)
|
||||||
sys.path.append(str(c.srccache))
|
sys.path.append(str(c.srccache))
|
||||||
next_version = __import__(sha256).__version__
|
next_version = __import__(sha256).__version__
|
||||||
|
|
||||||
q = (
|
if self.local_version == next_version:
|
||||||
"Update source at: "
|
echo(f"no change between {args.reference} and local version")
|
||||||
+ a.style(self.current_source, "bold")
|
sys.exit(0)
|
||||||
+ f" \n from version {__version__} to {next_version}?"
|
|
||||||
)
|
|
||||||
|
|
||||||
if confirm(q):
|
if confirm(
|
||||||
print("Holding off on the additions of this piece")
|
"Would you like to perform the above installation steps?",
|
||||||
|
UPDATE_TEMPLATE.format(
|
||||||
|
src_location=self.local_source,
|
||||||
|
local_version=self.local_version,
|
||||||
|
cli_location=args.cli,
|
||||||
|
next_version=next_version,
|
||||||
|
),
|
||||||
|
):
|
||||||
|
self._install_local_src(
|
||||||
|
sha256,
|
||||||
|
Path(
|
||||||
|
args.src
|
||||||
|
if self.local_source == "Not Found"
|
||||||
|
else self.local_source,
|
||||||
|
),
|
||||||
|
args.cli,
|
||||||
|
)
|
||||||
|
|
||||||
elif args.cmd == "install":
|
elif args.cmd == "install":
|
||||||
if self.local:
|
if not self.local_source == "Not Found":
|
||||||
error(
|
error(f"found existing viv installation at {self.local_source}")
|
||||||
a.style("viv manage install", "bold")
|
|
||||||
+ " should only be used with a remote viv",
|
|
||||||
)
|
|
||||||
echo(
|
echo(
|
||||||
"use "
|
"use "
|
||||||
+ a.style("viv manage update", "bold")
|
+ a.style("viv manage update", "bold")
|
||||||
|
@ -1028,12 +1093,18 @@ class Viv:
|
||||||
sys.path.append(str(c.srccache))
|
sys.path.append(str(c.srccache))
|
||||||
downloaded_version = __import__(sha256).__version__
|
downloaded_version = __import__(sha256).__version__
|
||||||
echo(f"Downloaded version: {downloaded_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):
|
# TODO: see if file is actually where
|
||||||
print("AWAY MAN")
|
# we are about to install and give more instructions
|
||||||
|
|
||||||
|
if confirm(
|
||||||
|
"Would you like to perform the above installation steps?",
|
||||||
|
INSTALL_TEMPLATE.format(
|
||||||
|
src_location=args.src,
|
||||||
|
cli_location=args.cli,
|
||||||
|
),
|
||||||
|
):
|
||||||
|
self._install_local_src(sha256, args.src, args.cli)
|
||||||
|
|
||||||
def _get_subcmd_parser(
|
def _get_subcmd_parser(
|
||||||
self,
|
self,
|
||||||
|
@ -1148,37 +1219,43 @@ class Viv:
|
||||||
"info",
|
"info",
|
||||||
parents=[p_vivenv_arg],
|
parents=[p_vivenv_arg],
|
||||||
)
|
)
|
||||||
|
p_manage_shared = ArgumentParser(add_help=False)
|
||||||
|
p_manage_shared.add_argument(
|
||||||
|
"-r",
|
||||||
|
"--reference",
|
||||||
|
help="git reference (branch/tag/commit)",
|
||||||
|
default="main",
|
||||||
|
)
|
||||||
|
|
||||||
|
p_manage_shared.add_argument(
|
||||||
|
"-s",
|
||||||
|
"--src",
|
||||||
|
help="path/to/source_file",
|
||||||
|
default=c.srcdefault,
|
||||||
|
)
|
||||||
|
p_manage_shared.add_argument(
|
||||||
|
"-c",
|
||||||
|
"--cli",
|
||||||
|
help="path/to/cli (symlink to src)",
|
||||||
|
default=Path.home() / "bin" / "viv",
|
||||||
|
)
|
||||||
|
|
||||||
p_manage_sub = self._get_subcmd_parser(
|
p_manage_sub = self._get_subcmd_parser(
|
||||||
subparsers, name="manage"
|
subparsers,
|
||||||
|
name="manage",
|
||||||
).add_subparsers(title="subcommand", metavar="<sub-cmd>", required=True)
|
).add_subparsers(title="subcommand", metavar="<sub-cmd>", required=True)
|
||||||
|
|
||||||
# TODO: shared parser?
|
p_manage_sub.add_parser(
|
||||||
(
|
"install", help="install viv", aliases="i", parents=[p_manage_shared]
|
||||||
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_sub.add_parser(
|
||||||
p_manage_update := p_manage_sub.add_parser(
|
"update",
|
||||||
"update", help="update viv version", aliases="u"
|
help="update viv version",
|
||||||
)
|
aliases="u",
|
||||||
|
parents=[p_manage_shared],
|
||||||
).set_defaults(func=self.manage, cmd="update")
|
).set_defaults(func=self.manage, cmd="update")
|
||||||
|
|
||||||
p_manage_update.add_argument(
|
|
||||||
"-r",
|
|
||||||
"--reference",
|
|
||||||
help="git reference (branch/tag/commit)",
|
|
||||||
default="main",
|
|
||||||
)
|
|
||||||
|
|
||||||
p_manage_sub.add_parser(
|
p_manage_sub.add_parser(
|
||||||
"show", help="show current installation info", aliases="s"
|
"show", help="show current installation info", aliases="s"
|
||||||
).set_defaults(func=self.manage, cmd="show")
|
).set_defaults(func=self.manage, cmd="show")
|
||||||
|
|
Loading…
Reference in a new issue