PK!uhdump_env/__init__.py# -*- coding: utf-8 -*- PK! dump_env/cli.py# -*- coding: utf-8 -*- import argparse import sys from typing import NoReturn from dump_env.dumper import dump from dump_env.exceptions import StrictEnvException def _create_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser() parser.add_argument( '-p', '--prefix', type=str, action='append', help='Adds prefix', ) parser.add_argument( '-t', '--template', default='', type=str, help='Adds template path', ) parser.add_argument( '--strict', type=str, action='append', help='Strict variables should exists in os envs', ) return parser def main() -> NoReturn: """ Runs dump-env script. Example: This example will dump all environ variables: .. code:: bash $ dump-env This example will dump all environ variables starting with ``PIP_``: .. code:: bash $ dump-env -p 'PIP_' This example will dump all environ variables starting with ``PIP_`` and update them with variables starting with ``SECRET_``: .. code:: bash $ dump-env -p 'PIP_' -p 'SECRET_' This example will dump everything from ``.env.template`` file and all env variables with ``SECRET_`` prefix into a ``.env`` file: .. code:: bash $ dump-env -p 'SECRET_' -t .env.template > .env This example will fail if ``REQUIRED`` does not exist in environ: .. code:: bash $ dump-env --strict=REQUIRED """ args = _create_parser().parse_args() strict_vars = set(args.strict) if args.strict else None try: variables = dump(args.template, args.prefix, strict_vars) except StrictEnvException as exc: sys.stderr.write('{0}\n'.format(str(exc))) sys.exit(1) else: for env_name, env_value in variables.items(): sys.stdout.write('{0}={1}\n'.format(env_name, env_value)) sys.exit(0) PK!d d dump_env/dumper.py# -*- coding: utf-8 -*- from collections import OrderedDict from os import environ from typing import Dict, List, Mapping, Optional, Set from dump_env.exceptions import StrictEnvException Store = Mapping[str, str] def _parse(source: str) -> Store: """ Reads the source ``.env`` file and load key-values. Args: source: ``.env`` template filepath Returns: Store with all keys and values. """ parsed_data = {} with open(source) as env_file: for line in env_file: line = line.strip() # noqa: WPS440 if not line or line.startswith('#') or '=' not in line: # Ignore comments and lines without assignment. continue # Remove whitespaces and quotes: env_name, env_value = line.split('=', 1) env_name = env_name.strip() env_value = env_value.strip().strip('\'"') parsed_data[env_name] = env_value return parsed_data def _preload_existing_vars(prefix: str) -> Store: """Preloads env vars from environ with the given prefix.""" if not prefix: # If prefix is empty just return all the env variables. return environ prefixed = {} # Prefix is not empty, do the search and replacement: for env_name, env_value in environ.items(): if not env_name.startswith(prefix): # Skip vars with no prefix. continue prefixed[env_name.replace(prefix, '', 1)] = env_value return prefixed def _assert_envs_exist(strict_keys: Set[str]) -> None: """Checks that all variables from strict keys do exists.""" missing_keys: List[str] = [ strict_key for strict_key in strict_keys if strict_key not in environ ] if missing_keys: raise StrictEnvException( 'Missing env vars: {0}'.format(', '.join(missing_keys)), ) def dump( template: str = '', prefixes: Optional[List[str]] = None, strict_keys: Optional[Set[str]] = None, ) -> Dict[str, str]: """ This function is used to dump .env files. As a source you can use both: 1. env.template file (``''`` by default) 2. env vars prefixed with some prefix (``''`` by default) Args: template: The path of the `.env` template file, use an empty string when there is no template file. prefixes: List of string prefixes to use only certain env variables, could be an empty string to use all available variables. Returns: Ordered key-value pairs of dumped env and template variables. Raises: StrictEnvException: when some variable from template is missing. """ if prefixes is None: prefixes = [''] if strict_keys: _assert_envs_exist(strict_keys) store: Dict[str, str] = {} if template: # Loading env values from template file: store.update(_parse(template)) # Loading env variables from `os.environ`: for prefix in prefixes: store.update(_preload_existing_vars(prefix)) # Sort keys and keep them ordered: return OrderedDict(sorted(store.items())) PK!Sڌdump_env/exceptions.py# -*- coding: utf-8 -*- class StrictEnvException(Exception): """We use this exception when some env vars are missing from environ.""" PK!Hr4,.)dump_env-1.1.1.dist-info/entry_points.txtN+I/N.,()J)-M+1 L<..PK!SE// dump_env-1.1.1.dist-info/LICENSEMIT License Copyright (c) 2017 Nikita Sobolev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HڽTUdump_env-1.1.1.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!H U!dump_env-1.1.1.dist-info/METADATAX{sH_bR>UHwZXvpl8M]A1F;3O# c="0ǯ[\3M}Ϥ"i}gј5Iũ͒s5e$HvŔi"V^oA< p x9/h XzA12\$ oȒ 9Nэӈa>($ xI,k!UՆ\O㋸^Ъ3|SjC!ھ[P˚=:,IJ^oK|<.*w[i CGM9!o7gv(K5O#:aQ hP\C$>hObLJ~Op7MQս?/sݫ{ohtO'LFh`~w"鬋g?Zӿݞ{ߞ7xwֻx磋^K/}zv.L]&͟ ~z{u=./jљ&cDr0:2 !6g]'Yw d((bM%se2tLn&&SQ˼Fk0@B\9"SK(%S6&7U4]1;^-trxdj#.+!tQv#dM\+iA)]{}BYRIFBHVjm[eŒ4!,ngW +]>EhB 88Ch< 4hDzl9'@% [ )R"I/$萞 Lr͑dE>O0ɂ|l* q|fQT\ Cdʢ!b v#N1do&$`#ԧ=X_o$sh0]]F>Ĥ~LOq`GG~q|8{6|!f8E~K`>9W3qu"]`̲'h}" m\fcNjJ N4Dfl8VO,P)]f^FhPؓJH^R-CA0x30`lMT[d2Tx hj<%<[/psfܟԖu1TGH%I3 0kcUSb2$Ƚo fέ5AbT=R 6qI(!JTRSa }M!C2Ua6R\PY:vBdQn(2leuy2@Eq@HAC"͡5 _pz)t :?Q^(Eyqŵh]m`'OyyqKñ$}9a8u*i)RXN1 yHuENYOgmEgtσ<(-sྍT$71