PK!RpѮdotenver/__init__.py__version__ = '0.2.0' PK!ha dotenver/cli.py"""Define CLI interface for Dotenver.""" import argparse import glob import sys from os.path import basename import colorama from . import __version__, dotenver def check_file_path(file_path): """Validate that the given file_path exists and can read.""" colorama.init() dotenv_path = dotenver.get_dotenv_path(file_path) if basename(dotenv_path) == basename(file_path): print(colorama.Fore.RED, file=sys.stderr) raise argparse.ArgumentTypeError( "'%s'. Template file can not be named .env" % file_path ) try: open(file_path, "r") except FileNotFoundError: print(colorama.Fore.RED, file=sys.stderr) raise argparse.ArgumentTypeError("'%s' could not be found" % file_path) except PermissionError: print(colorama.Fore.RED, file=sys.stderr) raise argparse.ArgumentTypeError("'%s' is not readable" % file_path) try: open(dotenv_path, "a") except PermissionError: print(colorama.Fore.RED, file=sys.stderr) raise argparse.ArgumentTypeError("'%s' is not writable" % dotenv_path) try: open(dotenv_path, "r") except FileNotFoundError: pass except PermissionError: print(colorama.Fore.RED, file=sys.stderr) raise argparse.ArgumentTypeError("'%s' is not readable" % dotenv_path) return file_path def cli(): """Parse DotEnver templates and save to .env files.""" parser = argparse.ArgumentParser( description="""Render DotEnver templates as .env files. By default values in existing in .env files are respected, and missing variables are added. """ ) parser.add_argument( "-o", "--override", action="store_true", help="override current .env files." ) group = parser.add_mutually_exclusive_group(required=True) group.add_argument( "-r", "--recursive", action="store_true", help="process all .env.example files recursively", ) group.add_argument( "--version", action="store_true", help="print current DotEnver version" ) group.add_argument( "files", metavar="file", type=check_file_path, nargs="*", default=False, help="path to file to process", ) args = parser.parse_args() if args.version: print(__version__) return files = args.files if args.recursive: files = glob.glob("**/.env.example", recursive=True) if not files: print(colorama.Fore.RED, file=sys.stderr) print('No ".env.example" files found', file=sys.stderr) dotenver.parse_files(files, override=args.override) return if __name__ == "__main__": cli() PK!vDHdotenver/dotenver.py"""Generate .env files from .env.example templates.""" import io import re import sys from os.path import dirname import colorama from faker import Faker from jinja2 import Environment VARIABLES = {} VARIABLE_REGEX = r""" ^\s* ( (?:export\s)? # Optional export command \s* ([^\s=]+) # Variable name ) \s*=\s* # Equal sign """ VALUES_REGEX = re.compile( r""" {0} (.*) # Verbatim value, no parsing done $ """.format( VARIABLE_REGEX ), re.VERBOSE, ) TEMPLATE_REGEX = re.compile( r""" {0} .* # Anything until a dotenver comment (?: \#\#\ +dotenver: # Start of the dotenver comment ([^\(\s]+) # Faker generator to use (?:\(( .* # Arguments to pass to the generator )\))? ) \s*$ """.format( VARIABLE_REGEX ), re.VERBOSE, ) FAKE = Faker() def dotenver(generator, name=None, quotes=None, escape_with="\\", **kwargs): r""" Generate fake data from the given `generator`. If a `name` is given, the value from the given `generator` and `name` will be saved and used for subsequent calls. In those cases only the quotes argument is honored for each call. The returned value will be optionally surrounded with single or double quotes as specified by `quotes`, and escaped with `escape_with`, which is a backslash `\` by default. """ if quotes not in [None, "'", '"']: raise ValueError("quotes must be a single `'` or double `\"` quote") key = None if name is not None: key = f"{generator}+{name}" data = str(VARIABLES.get(key, getattr(FAKE, generator)(**kwargs))) if key and key not in VARIABLES: VARIABLES[key] = data if quotes: data = data.replace(quotes, f"{escape_with}{quotes}") data = f"{quotes}{data}{quotes}" return data def parse_stream(template_stream, current_dotenv): """Parse a dotenver template.""" jinja2_template = io.StringIO() env = Environment(keep_trailing_newline=True) env.globals["dotenver"] = dotenver missing_variables = current_dotenv.copy() for line in template_stream: match = TEMPLATE_REGEX.match(line) if match: assignment, variable, faker, arguments = match.groups() if variable in current_dotenv: del missing_variables[variable] line = f"{assignment}={current_dotenv[variable][1]}" else: dotenver_args = f"'{faker}'" if arguments: dotenver_args = f"{dotenver_args}, {arguments}" line = f"{assignment}={{{{ dotenver({dotenver_args}) }}}}" jinja2_template.write(f"{line.strip()}\n") if missing_variables: jinja2_template.write( """ ###################################### # Variables not in Dotenver template # ###################################### """ ) for data in missing_variables.values(): jinja2_template.write(f"{data[0]}={data[1]}\n") template = env.from_string(jinja2_template.getvalue()) return template.render() def get_dotenv_path(template_path): """Return the .env path for the given template path.""" dotenv_dir = dirname(template_path) if dotenv_dir: dotenv_dir += "/" return f"{dotenv_dir}.env" def get_dotenv_dict(dotenv_path): """ Read a .env file and return a dictionary of the parsed data. Each item has the VARIABLE as the key, and the value is a tuple: (assignment, value) If the file does not exist, return an empty dict. """ values = dict() try: with open(dotenv_path, "r") as dotenv_file: for line in dotenv_file: match = VALUES_REGEX.match(line) if match: assignment, variable, value = match.groups() values[variable] = (assignment, value) except FileNotFoundError: pass except Exception: print( f"{colorama.Fore.RED}\n", f"The following exception ocurred while reading '{dotenv_path}'", f"\n{colorama.Fore.YELLOW}", file=sys.stderr, ) raise return values def parse_files(templates_paths, override=False): """Parse multiple dotenver templates and generate or update a .env for each.""" colorama.init() rendered_templates = {} for template_path in templates_paths: current_env = ( get_dotenv_dict(get_dotenv_path(template_path)) if not override else {} ) try: with open(template_path, "r") as template_file: rendered_templates[template_path] = parse_stream( template_file, current_env ) except Exception: print( f"{colorama.Fore.RED}\n", f"The following exception ocurred while processing template '{template_path}'", f"\n{colorama.Fore.YELLOW}", file=sys.stderr, ) raise for template_path, rendered_template in rendered_templates.items(): dotenv_path = get_dotenv_path(template_path) try: with open(dotenv_path, "w") as dotenv_file: dotenv_file.write(rendered_template) except Exception: print( f"{colorama.Fore.RED}\n", f"The following exception ocurred while writing to '{dotenv_path}'", f"\n{colorama.Fore.YELLOW}", file=sys.stderr, ) raise print( f"{colorama.Fore.GREEN}", f"'{template_path}' rendered to '{dotenv_path}'", f"{colorama.Fore.RESET}", file=sys.stderr, ) PK!H('-)dotenver-0.2.0.dist-info/entry_points.txtN+I/N.,()J/I+K-1s2 PK!(# dotenver-0.2.0.dist-info/LICENSEBSD 3-Clause License Copyright (c) 2018, Federico Jaramillo Martínez All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK!HnHTUdotenver-0.2.0.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!HDS]/ !dotenver-0.2.0.dist-info/METADATAVr6}Wш, 'J+[rTDI+ 6 0([~E ^$;q|Hݳp"JBv!2 ! ۜuywٴ2a! 3d$t *4!pL^dy7a/m$-9tֹlex: T︾& ͶCOZji #2΅q`&dBAf$sbTH6Z UMj~I 2ʅD7:P9: aGq9*aTvgS9c*BoV;?ֵ euG&ĈB%cG*I]>ɄϤJaWmӶCi]N5 ˏxEQ~{q#Սy8a=H`8 Jͺ}s[:_yXPQ`9v"N/ Rw=&A '8#V$OynLXG~ MGOYRb[϶މt?֭S 橈nnwZ)SZ16h&P98{{P1v~в~kmq_/uNE m s#?1^{qQޖ<ax1~P%Ra9K1+DZ<@2T%p$zj}6V?@.s5pۿ|j;-q J)LHapk`SY֬4'嫋B]d)^Nax<>v2:E%M6bF̙GscZu+Ƴt39ؾW\X5ېR'ݲߣU}*`}"Rn<@}b^M 0E 5Q4?*C>伪:{w}~4}%tvTg>hgogCq,tA 9_6F^]Nəoz:CBA^ }{CYYvRQ,/»z /!8pJ˴tyP T%+%rVnVI9Qu䅲U"Q Wށ<ב^KV񟌱PK!H)Ɔjdotenver-0.2.0.dist-info/RECORD}л@|aD0y #[> pZ݄Iܬ[u"jxGo3\7Vbڮh`Kz>;C?8X( uVF{kidЙhNNfpN[9>TK"%t; ,2+Ryt&)A}uH;L/ |GaRaF7 ydKClvW !İ}l*mbDVn׾\'ST dz"5݁U)G`%Kpj}?%8}#R==9tSi\_f ʝzéX1A龍jdsfCu?GSPK!RpѮdotenver/__init__.pyPK!ha Hdotenver/cli.pyPK!vDH' dotenver/dotenver.pyPK!H('-)#dotenver-0.2.0.dist-info/entry_points.txtPK!(# #dotenver-0.2.0.dist-info/LICENSEPK!HnHTU)dotenver-0.2.0.dist-info/WHEELPK!HDS]/ !N*dotenver-0.2.0.dist-info/METADATAPK!H)Ɔj,/dotenver-0.2.0.dist-info/RECORDPKN0