Really exclude __main__.py and cli.py from vendor

This commit is contained in:
Oz N Tiram
2023-08-21 00:36:44 +02:00
committed by Oz Tiram
parent ad6d353fe6
commit 5e109afce9
6 changed files with 0 additions and 349 deletions
-6
View File
@@ -1,6 +0,0 @@
"""Entry point for cli, enables execution with `python -m dotenv`"""
from .cli import cli
if __name__ == "__main__":
cli()
-199
View File
@@ -1,199 +0,0 @@
import json
import os
import shlex
import sys
from contextlib import contextmanager
from subprocess import Popen
from typing import Any, Dict, IO, Iterator, List
try:
import pipenv.vendor.click as click
except ImportError:
sys.stderr.write('It seems python-dotenv is not installed with cli option. \n'
'Run pip install "python-dotenv[cli]" to fix this.')
sys.exit(1)
from .main import dotenv_values, set_key, unset_key
from .version import __version__
def enumerate_env():
"""
Return a path for the ${pwd}/.env file.
If pwd does not exist, return None.
"""
try:
cwd = os.getcwd()
except FileNotFoundError:
return None
path = os.path.join(cwd, '.env')
return path
@click.group()
@click.option('-f', '--file', default=enumerate_env(),
type=click.Path(file_okay=True),
help="Location of the .env file, defaults to .env file in current working directory.")
@click.option('-q', '--quote', default='always',
type=click.Choice(['always', 'never', 'auto']),
help="Whether to quote or not the variable values. Default mode is always. This does not affect parsing.")
@click.option('-e', '--export', default=False,
type=click.BOOL,
help="Whether to write the dot file as an executable bash script.")
@click.version_option(version=__version__)
@click.pass_context
def cli(ctx: click.Context, file: Any, quote: Any, export: Any) -> None:
"""This script is used to set, get or unset values from a .env file."""
ctx.obj = {'QUOTE': quote, 'EXPORT': export, 'FILE': file}
@contextmanager
def stream_file(path: os.PathLike) -> Iterator[IO[str]]:
"""
Open a file and yield the corresponding (decoded) stream.
Exits with error code 2 if the file cannot be opened.
"""
try:
with open(path) as stream:
yield stream
except OSError as exc:
print(f"Error opening env file: {exc}", file=sys.stderr)
exit(2)
@cli.command()
@click.pass_context
@click.option('--format', default='simple',
type=click.Choice(['simple', 'json', 'shell', 'export']),
help="The format in which to display the list. Default format is simple, "
"which displays name=value without quotes.")
def list(ctx: click.Context, format: bool) -> None:
"""Display all the stored key/value."""
file = ctx.obj['FILE']
with stream_file(file) as stream:
values = dotenv_values(stream=stream)
if format == 'json':
click.echo(json.dumps(values, indent=2, sort_keys=True))
else:
prefix = 'export ' if format == 'export' else ''
for k in sorted(values):
v = values[k]
if v is not None:
if format in ('export', 'shell'):
v = shlex.quote(v)
click.echo(f'{prefix}{k}={v}')
@cli.command()
@click.pass_context
@click.argument('key', required=True)
@click.argument('value', required=True)
def set(ctx: click.Context, key: Any, value: Any) -> None:
"""Store the given key/value."""
file = ctx.obj['FILE']
quote = ctx.obj['QUOTE']
export = ctx.obj['EXPORT']
success, key, value = set_key(file, key, value, quote, export)
if success:
click.echo(f'{key}={value}')
else:
exit(1)
@cli.command()
@click.pass_context
@click.argument('key', required=True)
def get(ctx: click.Context, key: Any) -> None:
"""Retrieve the value for the given key."""
file = ctx.obj['FILE']
with stream_file(file) as stream:
values = dotenv_values(stream=stream)
stored_value = values.get(key)
if stored_value:
click.echo(stored_value)
else:
exit(1)
@cli.command()
@click.pass_context
@click.argument('key', required=True)
def unset(ctx: click.Context, key: Any) -> None:
"""Removes the given key."""
file = ctx.obj['FILE']
quote = ctx.obj['QUOTE']
success, key = unset_key(file, key, quote)
if success:
click.echo(f"Successfully removed {key}")
else:
exit(1)
@cli.command(context_settings={'ignore_unknown_options': True})
@click.pass_context
@click.option(
"--override/--no-override",
default=True,
help="Override variables from the environment file with those from the .env file.",
)
@click.argument('commandline', nargs=-1, type=click.UNPROCESSED)
def run(ctx: click.Context, override: bool, commandline: List[str]) -> None:
"""Run command with environment variables present."""
file = ctx.obj['FILE']
if not os.path.isfile(file):
raise click.BadParameter(
f'Invalid value for \'-f\' "{file}" does not exist.',
ctx=ctx
)
dotenv_as_dict = {
k: v
for (k, v) in dotenv_values(file).items()
if v is not None and (override or k not in os.environ)
}
if not commandline:
click.echo('No command given.')
exit(1)
ret = run_command(commandline, dotenv_as_dict)
exit(ret)
def run_command(command: List[str], env: Dict[str, str]) -> int:
"""Run command in sub process.
Runs the command in a sub process with the variables from `env`
added in the current environment variables.
Parameters
----------
command: List[str]
The command and it's parameters
env: Dict
The additional environment variables
Returns
-------
int
The return code of the command
"""
# copy the current environment variables and add the vales from
# `env`
cmd_env = os.environ.copy()
cmd_env.update(env)
p = Popen(command,
universal_newlines=True,
bufsize=0,
shell=False,
env=cmd_env)
_, _ = p.communicate()
return p.returncode
-14
View File
@@ -1,14 +0,0 @@
import os
import sys
pardir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# for finding pipdeptree itself
sys.path.append(pardir)
# for finding stuff in vendor and patched
sys.path.append(os.path.dirname(os.path.dirname(pardir)))
from pipenv.vendor.pipdeptree import main
if __name__ == "__main__":
sys.exit(main())
-24
View File
@@ -1,24 +0,0 @@
"""
A simple entry point which can be use to test Pipfiles
e.g.
python -m plette -f examples/Pipfile.valid.list
python -m plette -f examples/Pipfile.valid.editable
# throws exception
python -m plette -f examples/Pipfile.invalid.list
"""
from pipenv.vendor.plette import Pipfile
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="Input file")
args = parser.parse_args()
dest = args.file
with open(dest) as f:
pipfile = Pipfile.load(f)
-16
View File
@@ -1,16 +0,0 @@
#!env python
from __future__ import annotations
import os
import sys
from pipenv.vendor.pythonfinder.cli import cli
PYTHONFINDER_MAIN = os.path.dirname(os.path.abspath(__file__))
PYTHONFINDER_PACKAGE = os.path.dirname(PYTHONFINDER_MAIN)
if __name__ == "__main__":
sys.exit(cli())
-90
View File
@@ -1,90 +0,0 @@
from __future__ import annotations
import pipenv.vendor.click as click
from . import __version__
from .pythonfinder import Finder
@click.command()
@click.option("--find", nargs=1, help="Find a specific python version.")
@click.option("--which", nargs=1, help="Run the which command.")
@click.option("--findall", is_flag=True, default=False, help="Find all python versions.")
@click.option(
"--ignore-unsupported",
"--no-unsupported",
is_flag=True,
default=True,
envvar="PYTHONFINDER_IGNORE_UNSUPPORTED",
help="Ignore unsupported python versions.",
)
@click.version_option(
prog_name=click.style("PythonFinder", bold=True),
version=click.style(__version__, fg="yellow"),
)
@click.pass_context
def cli(
ctx, find=False, which=False, findall=False, version=False, ignore_unsupported=True
):
finder = Finder(ignore_unsupported=ignore_unsupported)
if findall:
versions = [v for v in finder.find_all_python_versions()]
if versions:
click.secho("Found python at the following locations:", fg="green")
for v in versions:
py = v.py_version
comes_from = getattr(py, "comes_from", None)
if comes_from is not None:
comes_from_path = getattr(comes_from, "path", v.path)
else:
comes_from_path = v.path
click.secho(
"{py.name!s}: {py.version!s} ({py.architecture!s}) @ {comes_from!s}".format(
py=py, comes_from=comes_from_path
),
fg="yellow",
)
ctx.exit()
else:
click.secho(
"ERROR: No valid python versions found! Check your path and try again.",
fg="red",
)
if find:
click.secho(f"Searching for python: {find.strip()!s}", fg="yellow")
found = finder.find_python_version(find.strip())
if found:
py = found.py_version
comes_from = getattr(py, "comes_from", None)
if comes_from is not None:
comes_from_path = getattr(comes_from, "path", found.path)
else:
comes_from_path = found.path
click.secho("Found python at the following locations:", fg="green")
click.secho(
"{py.name!s}: {py.version!s} ({py.architecture!s}) @ {comes_from!s}".format(
py=py, comes_from=comes_from_path
),
fg="yellow",
)
ctx.exit()
else:
click.secho("Failed to find matching executable...", fg="yellow")
ctx.exit(1)
elif which:
found = finder.system_path.which(which.strip())
if found:
click.secho(f"Found Executable: {found}", fg="white")
ctx.exit()
else:
click.secho("Failed to find matching executable...", fg="yellow")
ctx.exit(1)
else:
click.echo("Please provide a command", color="red")
ctx.exit(1)
ctx.exit()
if __name__ == "__main__":
cli()