|
| 1 | +import os |
| 2 | +import sys |
| 3 | +from subprocess import Popen |
| 4 | + |
| 5 | +try: |
| 6 | + import click |
| 7 | +except ImportError: |
| 8 | + sys.stderr.write('It seems python-dotenv is not installed with cli option. \n' |
| 9 | + 'Run pip install "python-dotenv[cli]" to fix this.') |
| 10 | + sys.exit(1) |
| 11 | + |
| 12 | +from .compat import IS_TYPE_CHECKING, to_env |
| 13 | +from .main import dotenv_values, get_key, set_key, unset_key |
| 14 | +from .version import __version__ |
| 15 | + |
| 16 | +if IS_TYPE_CHECKING: |
| 17 | + from typing import Any, List, Dict |
| 18 | + |
| 19 | + |
| 20 | +@click.group() |
| 21 | +@click.option('-f', '--file', default=os.path.join(os.getcwd(), '.env'), |
| 22 | + type=click.Path(file_okay=True), |
| 23 | + help="Location of the .env file, defaults to .env file in current working directory.") |
| 24 | +@click.option('-q', '--quote', default='always', |
| 25 | + type=click.Choice(['always', 'never', 'auto']), |
| 26 | + help="Whether to quote or not the variable values. Default mode is always. This does not affect parsing.") |
| 27 | +@click.option('-e', '--export', default=False, |
| 28 | + type=click.BOOL, |
| 29 | + help="Whether to write the dot file as an executable bash script.") |
| 30 | +@click.version_option(version=__version__) |
| 31 | +@click.pass_context |
| 32 | +def cli(ctx, file, quote, export): |
| 33 | + # type: (click.Context, Any, Any, Any) -> None |
| 34 | + '''This script is used to set, get or unset values from a .env file.''' |
| 35 | + ctx.obj = {} |
| 36 | + ctx.obj['QUOTE'] = quote |
| 37 | + ctx.obj['EXPORT'] = export |
| 38 | + ctx.obj['FILE'] = file |
| 39 | + |
| 40 | + |
| 41 | +@cli.command() |
| 42 | +@click.pass_context |
| 43 | +def list(ctx): |
| 44 | + # type: (click.Context) -> None |
| 45 | + '''Display all the stored key/value.''' |
| 46 | + file = ctx.obj['FILE'] |
| 47 | + if not os.path.isfile(file): |
| 48 | + raise click.BadParameter( |
| 49 | + 'Path "%s" does not exist.' % (file), |
| 50 | + ctx=ctx |
| 51 | + ) |
| 52 | + dotenv_as_dict = dotenv_values(file) |
| 53 | + for k, v in dotenv_as_dict.items(): |
| 54 | + click.echo('%s=%s' % (k, v)) |
| 55 | + |
| 56 | + |
| 57 | +@cli.command() |
| 58 | +@click.pass_context |
| 59 | +@click.argument('key', required=True) |
| 60 | +@click.argument('value', required=True) |
| 61 | +def set(ctx, key, value): |
| 62 | + # type: (click.Context, Any, Any) -> None |
| 63 | + '''Store the given key/value.''' |
| 64 | + file = ctx.obj['FILE'] |
| 65 | + quote = ctx.obj['QUOTE'] |
| 66 | + export = ctx.obj['EXPORT'] |
| 67 | + success, key, value = set_key(file, key, value, quote, export) |
| 68 | + if success: |
| 69 | + click.echo('%s=%s' % (key, value)) |
| 70 | + else: |
| 71 | + exit(1) |
| 72 | + |
| 73 | + |
| 74 | +@cli.command() |
| 75 | +@click.pass_context |
| 76 | +@click.argument('key', required=True) |
| 77 | +def get(ctx, key): |
| 78 | + # type: (click.Context, Any) -> None |
| 79 | + '''Retrieve the value for the given key.''' |
| 80 | + file = ctx.obj['FILE'] |
| 81 | + if not os.path.isfile(file): |
| 82 | + raise click.BadParameter( |
| 83 | + 'Path "%s" does not exist.' % (file), |
| 84 | + ctx=ctx |
| 85 | + ) |
| 86 | + stored_value = get_key(file, key) |
| 87 | + if stored_value: |
| 88 | + click.echo('%s=%s' % (key, stored_value)) |
| 89 | + else: |
| 90 | + exit(1) |
| 91 | + |
| 92 | + |
| 93 | +@cli.command() |
| 94 | +@click.pass_context |
| 95 | +@click.argument('key', required=True) |
| 96 | +def unset(ctx, key): |
| 97 | + # type: (click.Context, Any) -> None |
| 98 | + '''Removes the given key.''' |
| 99 | + file = ctx.obj['FILE'] |
| 100 | + quote = ctx.obj['QUOTE'] |
| 101 | + success, key = unset_key(file, key, quote) |
| 102 | + if success: |
| 103 | + click.echo("Successfully removed %s" % key) |
| 104 | + else: |
| 105 | + exit(1) |
| 106 | + |
| 107 | + |
| 108 | +@cli.command(context_settings={'ignore_unknown_options': True}) |
| 109 | +@click.pass_context |
| 110 | +@click.argument('commandline', nargs=-1, type=click.UNPROCESSED) |
| 111 | +def run(ctx, commandline): |
| 112 | + # type: (click.Context, List[str]) -> None |
| 113 | + """Run command with environment variables present.""" |
| 114 | + file = ctx.obj['FILE'] |
| 115 | + if not os.path.isfile(file): |
| 116 | + raise click.BadParameter( |
| 117 | + 'Invalid value for \'-f\' "%s" does not exist.' % (file), |
| 118 | + ctx=ctx |
| 119 | + ) |
| 120 | + dotenv_as_dict = {to_env(k): to_env(v) for (k, v) in dotenv_values(file).items() if v is not None} |
| 121 | + |
| 122 | + if not commandline: |
| 123 | + click.echo('No command given.') |
| 124 | + exit(1) |
| 125 | + ret = run_command(commandline, dotenv_as_dict) |
| 126 | + exit(ret) |
| 127 | + |
| 128 | + |
| 129 | +def run_command(command, env): |
| 130 | + # type: (List[str], Dict[str, str]) -> int |
| 131 | + """Run command in sub process. |
| 132 | +
|
| 133 | + Runs the command in a sub process with the variables from `env` |
| 134 | + added in the current environment variables. |
| 135 | +
|
| 136 | + Parameters |
| 137 | + ---------- |
| 138 | + command: List[str] |
| 139 | + The command and it's parameters |
| 140 | + env: Dict |
| 141 | + The additional environment variables |
| 142 | +
|
| 143 | + Returns |
| 144 | + ------- |
| 145 | + int |
| 146 | + The return code of the command |
| 147 | +
|
| 148 | + """ |
| 149 | + # copy the current environment variables and add the vales from |
| 150 | + # `env` |
| 151 | + cmd_env = os.environ.copy() |
| 152 | + cmd_env.update(env) |
| 153 | + |
| 154 | + p = Popen(command, |
| 155 | + universal_newlines=True, |
| 156 | + bufsize=0, |
| 157 | + shell=False, |
| 158 | + env=cmd_env) |
| 159 | + _, _ = p.communicate() |
| 160 | + |
| 161 | + return p.returncode |
| 162 | + |
| 163 | + |
| 164 | +if __name__ == "__main__": |
| 165 | + cli() |
0 commit comments