├── .bumpversion.cfg ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── LICENSE ├── Makefile ├── README.rst ├── bar.yml ├── dev_requirements.txt ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── foo.yml ├── setup.cfg ├── setup.py ├── test.xerc ├── tests ├── __init__.py ├── envs │ ├── alias.yml │ ├── empty.yml │ ├── foo │ │ └── default │ │ │ ├── a.yml │ │ │ ├── b.yaml │ │ │ └── c.yml │ └── with_json.yml ├── test_arg_parsing.py ├── test_cli.py ├── test_config.py ├── test_env.py ├── test_flatten.py └── test_yml_parsing.py ├── tox.ini └── withenv ├── __init__.py ├── args.py ├── cli.py ├── config.py ├── env.py └── flatten.py /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | files = setup.py withenv/__init__.py 3 | commit = True 4 | tag = True 5 | tag_name = {new_version} 6 | current_version = 0.7.0 7 | 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | htmlcov 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | 38 | # Complexity 39 | output/*.html 40 | output/*/index.html 41 | 42 | # Sphinx 43 | docs/_build 44 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | env: 4 | - TOXENV=py27 5 | - TOXENV=py34 6 | 7 | install: "pip install tox" 8 | 9 | script: tox 10 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Eric Larson 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/ionrock/withenv/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | `withenv` could always use more documentation, whether as part of the 40 | official withenv docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at 47 | https://github.com/ionrock/withenv/issues. 48 | 49 | If you are proposing a feature: 50 | 51 | * Explain in detail how it would work. 52 | * Keep the scope as narrow as possible, to make it easier to implement. 53 | * Remember that this is a volunteer-driven project, and that contributions 54 | are welcome :) 55 | 56 | Get Started! 57 | ------------ 58 | 59 | Ready to contribute? Here's how to set up `withenv` for local development. 60 | 61 | 1. Fork the `withenv` repo on GitHub. 62 | 2. Clone your fork locally:: 63 | 64 | $ git clone git@github.com:your_name_here/withenv.git 65 | 66 | 3. Install your local copy into a virtualenv. This is how you set up 67 | your fork for local development:: 68 | 69 | $ cd withenv/ 70 | $ make bootstrap 71 | 72 | 4. Create a branch for local development:: 73 | 74 | $ git checkout -b name-of-your-bugfix-or-feature 75 | 76 | Now you can make your changes locally. 77 | 78 | 5. When you're done making changes, check that your changes pass 79 | flake8 and the tests, including testing other Python versions with 80 | tox:: 81 | 82 | $ make test-all 83 | 84 | 6. Commit your changes and push your branch to GitHub:: 85 | 86 | $ git add . 87 | $ git commit -m "Your detailed description of your changes." 88 | $ git push origin name-of-your-bugfix-or-feature 89 | 90 | 7. Submit a pull request through the GitHub website. 91 | 92 | 93 | Pull Request Guidelines 94 | ----------------------- 95 | 96 | Before you submit a pull request, check that it meets these guidelines: 97 | 98 | 1. The pull request should include tests. 99 | 2. If the pull request adds functionality, the docs should be updated. Put 100 | your new functionality into a function with a docstring, and add the 101 | feature to the list in README.rst. 102 | 3. The pull request should work for Python 2.6, 2.7, 3.3, and 3.4, and for PyPy. Check 103 | https://travis-ci.org/ionrock/withenv/pull_requests 104 | and make sure that the tests pass for all supported Python versions. 105 | 106 | Tips 107 | ---- 108 | 109 | To run a subset of tests:: 110 | 111 | $ py.test tests/test_my_test.py::TestClass::test_func 112 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Eric Larson 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * 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. 9 | 10 | * Neither the name of withenv nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | 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. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs clean 2 | SHELL=bash 3 | VENV=.venv 4 | WITH_VENV=source $(VENV)/bin/activate 5 | CHEESE=https://pypi.python.org/pypi 6 | BUMPTYPE=patch 7 | 8 | help: 9 | @echo "bootstrap - create a virtualenv and install the necessary packages for development." 10 | @echo "clean - remove all build, test, coverage and Python artifacts" 11 | @echo "clean-build - remove build artifacts" 12 | @echo "clean-pyc - remove Python file artifacts" 13 | @echo "clean-test - remove test and coverage artifacts" 14 | @echo "lint - check style with flake8" 15 | @echo "test - run tests quickly with the default Python" 16 | @echo "test-all - run tests on every Python version with tox" 17 | @echo "docs - generate Sphinx HTML documentation, including API docs" 18 | @echo "release - package and upload a release." 19 | @echo ' use `-e CHEESE=http://localpypi` to release somewhere else.' 20 | @echo "dist - package" 21 | @echo "bump - bump the version number via bumpversion." 22 | @echo ' use `-e BUMPTYPE=minor` to specify `major` or `minor` (default is `patch`).' 23 | 24 | bootstrap: 25 | virtualenv $(VENV) 26 | $(VENV)/bin/pip install -r dev_requirements.txt 27 | 28 | clean: clean-build clean-pyc clean-test 29 | 30 | clean-build: 31 | rm -fr build/ 32 | rm -fr dist/ 33 | rm -fr *.egg-info 34 | 35 | clean-pyc: 36 | find . -name '*.pyc' -exec rm -f {} + 37 | find . -name '*.pyo' -exec rm -f {} + 38 | find . -name '*~' -exec rm -f {} + 39 | find . -name '__pycache__' -exec rm -fr {} + 40 | 41 | clean-test: 42 | rm -fr .tox/ 43 | rm -f .coverage 44 | rm -fr htmlcov/ 45 | 46 | lint: 47 | flake8 withenv tests 48 | 49 | test: 50 | $(VENV)/bin/py.test 51 | 52 | test-all: 53 | tox 54 | 55 | docs: 56 | rm -f docs/withenv.rst 57 | rm -f docs/modules.rst 58 | 59 | $(WITH_VENV) && sphinx-apidoc -o docs/ withenv 60 | $(WITH_VENV) && $(MAKE) -C docs clean 61 | $(WITH_VENV) && $(MAKE) -C docs html 62 | open docs/_build/html/index.html 63 | 64 | release: clean 65 | python setup.py sdist register -r $(CHEESE) upload -r $(CHEESE) 66 | 67 | dist: clean 68 | python setup.py sdist 69 | ls -l dist 70 | 71 | bump: 72 | $(VENV)/bin/bumpversion $(BUMPTYPE) 73 | git push origin master 74 | git push --tags 75 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | withenv 3 | ======= 4 | 5 | .. image:: https://travis-ci.org/ionrock/withenv.png?branch=master 6 | :target: https://travis-ci.org/ionrock/withenv 7 | 8 | .. image:: https://badge.fury.io/py/withenv.svg 9 | :target: https://pypi.python.org/pypi/withenv 10 | 11 | 12 | We use environment variables all the time, but they can be painful to 13 | maintain because a shell is sticky. It is too easy to set an 14 | environment variable in your shell, only to have that variable stick 15 | around when you change projects. 16 | 17 | `withenv` aims to help this problem by providing a simple way to 18 | prefix commands targeting YAML files that will be added to the 19 | environment prior to the command running. 20 | 21 | See the docs_ for more info. 22 | 23 | * Free software: BSD license 24 | * Documentation: https://withenv.readthedocs.org 25 | 26 | 27 | .. _docs: https://withenv.readthedocs.org 28 | -------------------------------------------------------------------------------- /bar.yml: -------------------------------------------------------------------------------- 1 | BAR: hello $FOO 2 | -------------------------------------------------------------------------------- /dev_requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | 3 | pytest 4 | mock 5 | bumpversion 6 | sphinx 7 | tox 8 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/withenv.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/withenv.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/withenv" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/withenv" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # withenv documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | 19 | # If extensions (or modules to document with autodoc) are in another 20 | # directory, add these directories to sys.path here. If the directory is 21 | # relative to the documentation root, use os.path.abspath to make it 22 | # absolute, like shown here. 23 | #sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # Get the project root dir, which is the parent dir of this 26 | cwd = os.getcwd() 27 | project_root = os.path.dirname(cwd) 28 | 29 | # Insert the project root dir as the first element in the PYTHONPATH. 30 | # This lets us ensure that the source package is imported, and that its 31 | # version is used. 32 | sys.path.insert(0, project_root) 33 | 34 | import withenv 35 | 36 | # -- General configuration --------------------------------------------- 37 | 38 | # If your documentation needs a minimal Sphinx version, state it here. 39 | #needs_sphinx = '1.0' 40 | 41 | # Add any Sphinx extension module names here, as strings. They can be 42 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 43 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 44 | 45 | # Add any paths that contain templates here, relative to this directory. 46 | templates_path = ['_templates'] 47 | 48 | # The suffix of source filenames. 49 | source_suffix = '.rst' 50 | 51 | # The encoding of source files. 52 | #source_encoding = 'utf-8-sig' 53 | 54 | # The master toctree document. 55 | master_doc = 'index' 56 | 57 | # General information about the project. 58 | project = u'withenv' 59 | copyright = u'2015, Eric Larson' 60 | 61 | # The version info for the project you're documenting, acts as replacement 62 | # for |version| and |release|, also used in various other places throughout 63 | # the built documents. 64 | # 65 | # The short X.Y version. 66 | version = withenv.__version__ 67 | # The full version, including alpha/beta/rc tags. 68 | release = withenv.__version__ 69 | 70 | # The language for content autogenerated by Sphinx. Refer to documentation 71 | # for a list of supported languages. 72 | #language = None 73 | 74 | # There are two options for replacing |today|: either, you set today to 75 | # some non-false value, then it is used: 76 | #today = '' 77 | # Else, today_fmt is used as the format for a strftime call. 78 | #today_fmt = '%B %d, %Y' 79 | 80 | # List of patterns, relative to source directory, that match files and 81 | # directories to ignore when looking for source files. 82 | exclude_patterns = ['_build'] 83 | 84 | # The reST default role (used for this markup: `text`) to use for all 85 | # documents. 86 | #default_role = None 87 | 88 | # If true, '()' will be appended to :func: etc. cross-reference text. 89 | #add_function_parentheses = True 90 | 91 | # If true, the current module name will be prepended to all description 92 | # unit titles (such as .. function::). 93 | #add_module_names = True 94 | 95 | # If true, sectionauthor and moduleauthor directives will be shown in the 96 | # output. They are ignored by default. 97 | #show_authors = False 98 | 99 | # The name of the Pygments (syntax highlighting) style to use. 100 | pygments_style = 'sphinx' 101 | 102 | # A list of ignored prefixes for module index sorting. 103 | #modindex_common_prefix = [] 104 | 105 | # If true, keep warnings as "system message" paragraphs in the built 106 | # documents. 107 | #keep_warnings = False 108 | 109 | 110 | # -- Options for HTML output ------------------------------------------- 111 | 112 | # The theme to use for HTML and HTML Help pages. See the documentation for 113 | # a list of builtin themes. 114 | html_theme = 'default' 115 | 116 | # Theme options are theme-specific and customize the look and feel of a 117 | # theme further. For a list of options available for each theme, see the 118 | # documentation. 119 | #html_theme_options = {} 120 | 121 | # Add any paths that contain custom themes here, relative to this directory. 122 | #html_theme_path = [] 123 | 124 | # The name for this set of Sphinx documents. If None, it defaults to 125 | # " v documentation". 126 | #html_title = None 127 | 128 | # A shorter title for the navigation bar. Default is the same as 129 | # html_title. 130 | #html_short_title = None 131 | 132 | # The name of an image file (relative to this directory) to place at the 133 | # top of the sidebar. 134 | #html_logo = None 135 | 136 | # The name of an image file (within the static path) to use as favicon 137 | # of the docs. This file should be a Windows icon file (.ico) being 138 | # 16x16 or 32x32 pixels large. 139 | #html_favicon = None 140 | 141 | # Add any paths that contain custom static files (such as style sheets) 142 | # here, relative to this directory. They are copied after the builtin 143 | # static files, so a file named "default.css" will overwrite the builtin 144 | # "default.css". 145 | html_static_path = ['_static'] 146 | 147 | # If not '', a 'Last updated on:' timestamp is inserted at every page 148 | # bottom, using the given strftime format. 149 | #html_last_updated_fmt = '%b %d, %Y' 150 | 151 | # If true, SmartyPants will be used to convert quotes and dashes to 152 | # typographically correct entities. 153 | #html_use_smartypants = True 154 | 155 | # Custom sidebar templates, maps document names to template names. 156 | #html_sidebars = {} 157 | 158 | # Additional templates that should be rendered to pages, maps page names 159 | # to template names. 160 | #html_additional_pages = {} 161 | 162 | # If false, no module index is generated. 163 | #html_domain_indices = True 164 | 165 | # If false, no index is generated. 166 | #html_use_index = True 167 | 168 | # If true, the index is split into individual pages for each letter. 169 | #html_split_index = False 170 | 171 | # If true, links to the reST sources are added to the pages. 172 | #html_show_sourcelink = True 173 | 174 | # If true, "Created using Sphinx" is shown in the HTML footer. 175 | # Default is True. 176 | #html_show_sphinx = True 177 | 178 | # If true, "(C) Copyright ..." is shown in the HTML footer. 179 | # Default is True. 180 | #html_show_copyright = True 181 | 182 | # If true, an OpenSearch description file will be output, and all pages 183 | # will contain a tag referring to it. The value of this option 184 | # must be the base URL from which the finished HTML is served. 185 | #html_use_opensearch = '' 186 | 187 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 188 | #html_file_suffix = None 189 | 190 | # Output file base name for HTML help builder. 191 | htmlhelp_basename = 'withenvdoc' 192 | 193 | 194 | # -- Options for LaTeX output ------------------------------------------ 195 | 196 | latex_elements = { 197 | # The paper size ('letterpaper' or 'a4paper'). 198 | #'papersize': 'letterpaper', 199 | 200 | # The font size ('10pt', '11pt' or '12pt'). 201 | #'pointsize': '10pt', 202 | 203 | # Additional stuff for the LaTeX preamble. 204 | #'preamble': '', 205 | } 206 | 207 | # Grouping the document tree into LaTeX files. List of tuples 208 | # (source start file, target name, title, author, documentclass 209 | # [howto/manual]). 210 | latex_documents = [ 211 | ('index', 'withenv.tex', 212 | u'withenv Documentation', 213 | u'Eric Larson', 'manual'), 214 | ] 215 | 216 | # The name of an image file (relative to this directory) to place at 217 | # the top of the title page. 218 | #latex_logo = None 219 | 220 | # For "manual" documents, if this is true, then toplevel headings 221 | # are parts, not chapters. 222 | #latex_use_parts = False 223 | 224 | # If true, show page references after internal links. 225 | #latex_show_pagerefs = False 226 | 227 | # If true, show URL addresses after external links. 228 | #latex_show_urls = False 229 | 230 | # Documents to append as an appendix to all manuals. 231 | #latex_appendices = [] 232 | 233 | # If false, no module index is generated. 234 | #latex_domain_indices = True 235 | 236 | 237 | # -- Options for manual page output ------------------------------------ 238 | 239 | # One entry per manual page. List of tuples 240 | # (source start file, name, description, authors, manual section). 241 | man_pages = [ 242 | ('index', 'withenv', 243 | u'withenv Documentation', 244 | [u'Eric Larson'], 1) 245 | ] 246 | 247 | # If true, show URL addresses after external links. 248 | #man_show_urls = False 249 | 250 | 251 | # -- Options for Texinfo output ---------------------------------------- 252 | 253 | # Grouping the document tree into Texinfo files. List of tuples 254 | # (source start file, target name, title, author, 255 | # dir menu entry, description, category) 256 | texinfo_documents = [ 257 | ('index', 'withenv', 258 | u'withenv Documentation', 259 | u'Eric Larson', 260 | 'withenv', 261 | 'One line description of project.', 262 | 'Miscellaneous'), 263 | ] 264 | 265 | # Documents to append as an appendix to all manuals. 266 | #texinfo_appendices = [] 267 | 268 | # If false, no module index is generated. 269 | #texinfo_domain_indices = True 270 | 271 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 272 | #texinfo_show_urls = 'footnote' 273 | 274 | # If true, do not generate a @detailmenu in the "Top" node's menu. 275 | #texinfo_no_detailmenu = False 276 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ionrock/withenv/1f5d698b55b3c6910bcf79237f6379dfa91a3778/docs/history.rst -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. withenv documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to withenv's documentation! 7 | ====================================== 8 | 9 | Withenv is a tool to help manage your environment variables 10 | consistently. 11 | 12 | The idea behind withenv is to have an easy way set environment 13 | variables prior to running some program that depends on them, leaving 14 | your shell in a sane state. 15 | 16 | 17 | Contents: 18 | 19 | .. toctree:: 20 | :maxdepth: 2 21 | 22 | readme 23 | installation 24 | usage 25 | contributing 26 | authors 27 | 28 | Indices and tables 29 | ================== 30 | 31 | * :ref:`genindex` 32 | * :ref:`modindex` 33 | * :ref:`search` 34 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ easy_install withenv 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv withenv 12 | $ pip install withenv 13 | 14 | 15 | This will install the `we` command line tool. 16 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\withenv.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\withenv.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Usage 3 | ======= 4 | 5 | The `withenv` package installs the `we` executable. Here is the basic 6 | usage. 7 | 8 | 9 | .. code-block:: bash 10 | 11 | $ we --env foo.yml printenv 12 | 13 | The YAML in `foo.yml` gets loaded and applied to the environment. If 14 | the value already exists in the environment, that value will be 15 | overwritten. 16 | 17 | You can also use a directory of YAML files. 18 | 19 | .. code-block:: bash 20 | 21 | $ we --dir myenv printenv 22 | 23 | The files will be applied to the environment in alphabetical order. 24 | 25 | You can shorten the flags as well as mixing files and directories. 26 | 27 | .. code-block:: bash 28 | 29 | $ we -e foo.yml -d bar -e baz.yml printenv 30 | 31 | Each flag will be applied in order from left to right. 32 | 33 | 34 | YAML Format 35 | =========== 36 | 37 | You can use a hash or list of hashes in your YAML file. For example: 38 | 39 | .. code-block:: yaml 40 | 41 | --- 42 | FOO: bar 43 | BAR: hello $FOO 44 | 45 | It is not recommended to use a hash in this format because the order 46 | cannot be gauranteed, although, it will probably work just fine. If 47 | you need explicit ordering within your file, use a list of hashes. 48 | 49 | .. code-block:: yaml 50 | 51 | --- 52 | - FOO: bar 53 | - BAR: hello $FOO 54 | 55 | Here we see the `$FOO` variable is used within the value of `$BAR`. 56 | 57 | 58 | Environment Files 59 | ----------------- 60 | 61 | Withenv also makes an effort to include environment 62 | files. Specifically, you can include a file that use the format: 63 | 64 | .. code-block:: bash 65 | 66 | export $VARNAME=$VALUE 67 | 68 | Each line is parsed as an entry. This can be a typical shell script as 69 | lines that don't start with `export` will be ignored. With that in 70 | mind, functions defined in the script will not be available. 71 | 72 | 73 | Command Substitutions 74 | ========================= 75 | 76 | Sometimes you want to replace a variable based on the result of a 77 | command. Say for example, you wanted to grab a value from a `chef 78 | environment `_. We can use the 79 | `knife `_ and `jq 80 | `_ to grab the value and inject into 81 | our environment value. 82 | 83 | .. code-block:: yaml 84 | 85 | --- 86 | - CHEF_ENV: dev 87 | - TOKEN: "`knife environment show $CHEF_ENV -Fj | jq --raw-output .default_attributes.token`" 88 | 89 | The knife command will go to our chef server and grab the 90 | environment's configuration and output it as JSON. This output is 91 | piped to the `jq` command where we are able to use `JSONPath `_ to grab the field value we need. The 92 | `--raw-output` will ensure we don't have any quotes around the value. 93 | 94 | We could then use this in a commmand. 95 | 96 | .. code-block:: bash 97 | 98 | $ we -e token.yml curl -H 'X-Auth-Token: $TOKEN' http://example.com/api/ 99 | 100 | Currently, `withenv` supports this dynamic substitution when the value 101 | starts and endswith a backtick. 102 | 103 | 104 | Creating an Alias 105 | ================= 106 | 107 | Sometimes you'll find that your environment is composed of a suite of 108 | details. Say for example, you were deploying an application via some 109 | script that uses environment variables to choose what region, cloud 110 | account and process to run. 111 | 112 | .. code-block:: bash 113 | 114 | $ we -d envs/apps/foo \ 115 | -e envs/acct/dev.yml \ 116 | -e envs/regions/us-east \ 117 | -E TAG=foo 118 | ./create-app-server 119 | 120 | We can create an alias for this by creating an alias YAML file. 121 | 122 | .. code-block:: yaml 123 | 124 | # myalias.yml 125 | --- 126 | - directory: envs/apps/foo 127 | - file: envs/acct/dev.yml 128 | - file: envs/regions/us-east 129 | - override: "TAG=foo" 130 | 131 | We can then run our command with a shortened `we` command. 132 | 133 | .. code-block:: bash 134 | 135 | $ we -a myalias create-app-server 136 | 137 | 138 | Loading Defaults 139 | ================ 140 | 141 | Withenv will look for a default alias file called `.werc`. The `we` 142 | command will look in the current directory and walk the filesystem 143 | until it finds a `.werc` file. If it finds a `.werc`, it will load it 144 | as an alias file prior to any command line arguments. If no `.werc` is 145 | found, `we` continues normally. 146 | 147 | For example, lets say that you had a some projects for different 148 | clients. Each client provided credentials to a cloud account and you 149 | want to use the specific client when running commands. 150 | 151 | The `.werc` might look like this: 152 | 153 | .. code-block:: yaml 154 | 155 | # .werc 156 | --- 157 | - file: client.yml 158 | - file: ~/projects/clients/$CLIENT/creds.yml 159 | 160 | 161 | The `client.yml` would add the `$CLIENT` env var. Now you could see 162 | what instances your client has running. 163 | 164 | .. code-block:: bash 165 | 166 | $ we ec2-describe-regions 167 | # or for rackspace 168 | $ we rack servers instance list 169 | -------------------------------------------------------------------------------- /foo.yml: -------------------------------------------------------------------------------- 1 | FOO: bar -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [tool:pytest] 2 | norecursedirs = venv .venv 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | try: 6 | from setuptools import setup 7 | except ImportError: 8 | from distutils.core import setup 9 | 10 | 11 | readme = open('README.rst').read() 12 | 13 | requirements = [ 14 | 'PyYAML', 15 | 'six', 16 | ] 17 | 18 | setup( 19 | name='withenv', 20 | version='0.7.0', 21 | description=('Prefix commands with specific environments specified ' 22 | 'in YAML files.'), 23 | long_description=readme, 24 | author='Eric Larson', 25 | author_email='eric@ionrock.org', 26 | url='https://github.com/ionrock/withenv', 27 | packages=[ 28 | 'withenv', 29 | ], 30 | package_dir={'withenv': 31 | 'withenv'}, 32 | include_package_data=True, 33 | install_requires=requirements, 34 | license="BSD", 35 | zip_safe=False, 36 | keywords='withenv', 37 | entry_points={ 38 | 'console_scripts': [ 39 | 'we = withenv.cli:main', 40 | ] 41 | }, 42 | classifiers=[ 43 | 'Development Status :: 2 - Pre-Alpha', 44 | 'Intended Audience :: Developers', 45 | 'License :: OSI Approved :: BSD License', 46 | 'Natural Language :: English', 47 | "Programming Language :: Python :: 2", 48 | 'Programming Language :: Python :: 2.6', 49 | 'Programming Language :: Python :: 2.7', 50 | 'Programming Language :: Python :: 3', 51 | 'Programming Language :: Python :: 3.3', 52 | 'Programming Language :: Python :: 3.4', 53 | ], 54 | ) 55 | -------------------------------------------------------------------------------- /test.xerc: -------------------------------------------------------------------------------- 1 | --- 2 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /tests/envs/alias.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - directory: foo -------------------------------------------------------------------------------- /tests/envs/empty.yml: -------------------------------------------------------------------------------- 1 | --- -------------------------------------------------------------------------------- /tests/envs/foo/default/a.yml: -------------------------------------------------------------------------------- 1 | A: True -------------------------------------------------------------------------------- /tests/envs/foo/default/b.yaml: -------------------------------------------------------------------------------- 1 | B: True -------------------------------------------------------------------------------- /tests/envs/foo/default/c.yml: -------------------------------------------------------------------------------- 1 | C: True -------------------------------------------------------------------------------- /tests/envs/with_json.yml: -------------------------------------------------------------------------------- 1 | 2 | - foo: > 3 | { 4 | "chef": { 5 | "attrs": { 6 | "allow_sshd": true, 7 | "allow_https": true, 8 | "allow_wildwest": true, 9 | "enabled": true, 10 | "wildwest": { 11 | "cloudnet": "eth2" 12 | } 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /tests/test_arg_parsing.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from withenv.args import parse_args 4 | 5 | 6 | class TestArgParsing(object): 7 | def test_defaults(self): 8 | args = parse_args([]) 9 | assert args.actions is None 10 | assert args.cmd == [] 11 | 12 | def test_mixed_long_with_cmd(self): 13 | actions = [ 14 | ('file', 'foo.yml'), 15 | ('file', 'bar.yml'), 16 | ('directory', 'baz'), 17 | ] 18 | cmd = 'ls -la'.split() 19 | 20 | result = parse_args([ 21 | '-e', 'foo.yml', 22 | '--env', 'bar.yml', 23 | '-d', 'baz', 24 | 'ls', '-la' 25 | ]) 26 | 27 | assert result.actions == actions 28 | assert result.cmd == cmd 29 | -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | import time 2 | import subprocess 3 | import tempfile 4 | import signal 5 | 6 | 7 | class TestMain(object): 8 | 9 | def test_we_return_code(self): 10 | assert subprocess.check_output('which we'.split()) != "" 11 | assert subprocess.check_output('which echo'.split()) != "" 12 | assert subprocess.call('we echo'.split()) == 0 13 | 14 | # We use the python errno as the exit code 15 | assert subprocess.call('we eccho'.split()) == 2 16 | 17 | def test_we_catches_ctrl_c(self): 18 | fd, path = tempfile.mkstemp() 19 | with open(path, 'wb+') as fh: 20 | proc = subprocess.Popen(['we', 'sleep', '10'], 21 | stdout=fh, 22 | stderr=subprocess.STDOUT) 23 | time.sleep(.5) 24 | proc.send_signal(signal.SIGINT) 25 | proc.wait() 26 | 27 | assert open(path).read() == '' 28 | -------------------------------------------------------------------------------- /tests/test_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from mock import patch, Mock 4 | from withenv import config 5 | 6 | 7 | class TestConfig(object): 8 | 9 | @patch.object(config, 'find_config_file', Mock(return_value='.werc')) 10 | def test_load_config_returns_actions(self): 11 | assert config.load_config_file() == [('alias', '.werc')] 12 | 13 | def test_find_config(self): 14 | config_path = config.find_config_file( 15 | start=os.path.dirname(os.path.abspath(__file__)), 16 | filename='test.werc' 17 | ) 18 | assert config 19 | -------------------------------------------------------------------------------- /tests/test_env.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from withenv.env import find_yml_in_dir, compile, compiled_value 4 | from withenv import env 5 | 6 | 7 | HERE = os.path.dirname(os.path.abspath(__file__)) 8 | 9 | 10 | class EnvInfo(object): 11 | 12 | def envs_path(self, *tail): 13 | return os.path.join(HERE, 'envs', *tail) 14 | 15 | def setup(self): 16 | self.env = os.path.join(HERE, 'envs', 'foo') 17 | self.base = os.path.join(HERE, 'envs', 'foo', 'default') 18 | self.env_files = [ 19 | os.path.join(self.base, 'a.yml'), 20 | os.path.join(self.base, 'b.yaml'), 21 | os.path.join(self.base, 'c.yml'), 22 | ] 23 | 24 | 25 | class TestFindYmlInDir(EnvInfo): 26 | 27 | def test_load_dir(self): 28 | base = os.path.join(HERE, 'envs', 'foo', 'default') 29 | result = set(list(find_yml_in_dir(self.env))) 30 | assert result == set(self.env_files) 31 | 32 | 33 | class TestCompileEnv(EnvInfo): 34 | foo_env = { 35 | 'A': 'True', 36 | 'B': 'True', 37 | 'C': 'True', 38 | } 39 | 40 | def test_compile_with_directory(self): 41 | actions = [('directory', self.env)] 42 | assert compile(actions, {}) == self.foo_env 43 | 44 | def test_compile_with_alias(self): 45 | actions = [('alias', os.path.join(HERE, 'envs', 'alias.yml'))] 46 | assert compile(actions, {}) == self.foo_env 47 | 48 | def test_compile_with_files(self): 49 | actions = [ 50 | ('file', fname) for fname in self.env_files 51 | ] 52 | assert compile(actions, {}) == self.foo_env 53 | 54 | def test_compile_with_empty_file(self): 55 | actions = [ 56 | ('file', self.envs_path('empty.yml')) 57 | ] 58 | 59 | assert compile(actions, {}) == {} 60 | 61 | def test_compile_with_empty_alias(self): 62 | actions = [ 63 | ('alias', self.envs_path('empty.yml')) 64 | ] 65 | assert compile(actions, {}) == {} 66 | 67 | def test_compile_with_overrides(self): 68 | actions = [ 69 | ('directory', self.env), 70 | ('override', 'C=False'), 71 | ] 72 | 73 | assert compile(actions, {})['C'] == 'False' 74 | 75 | def test_compile_with_script(self): 76 | actions = [ 77 | ('script', 'cat %s' % self.env_files[0]), 78 | ] 79 | 80 | assert compile(actions, {})['A'] == 'True' 81 | 82 | def test_compile_with_script_with_pipes(self): 83 | actions = [ 84 | ('script', 'echo "%s" | xargs cat' % self.env_files[0]), 85 | ] 86 | 87 | assert compile(actions, {})['A'] == 'True' 88 | 89 | 90 | class TestCompileValue(object): 91 | def setup(self): 92 | os.environ['MYTESTVAR'] = 'foo' 93 | 94 | def teardown(self): 95 | del os.environ['MYTESTVAR'] 96 | 97 | def test_expand_envvars(self): 98 | assert 'hello-foo' == compiled_value('hello-$MYTESTVAR') 99 | assert 'hello-foo' == compiled_value('hello-${MYTESTVAR}') 100 | assert 'hello-$(MYTESTVAR)' == compiled_value('hello-$(MYTESTVAR)') 101 | 102 | def test_generate_compiled_output_from_cmd(self): 103 | assert compiled_value('`echo $MYTESTVAR`') == b'foo' 104 | 105 | 106 | class TestRunningCommands(object): 107 | piped_cmd = 'echo "foo" | tr f F' 108 | 109 | def test_find_commands(self): 110 | cmd = env.string_to_cmd(self.piped_cmd) 111 | assert env.find_piped_cmds(cmd) == [ 112 | ['echo', 'foo'], 113 | ['tr', 'f', 'F'], 114 | ] 115 | 116 | def test_get_cmd_output_with_pipes(self): 117 | cmd = env.string_to_cmd(self.piped_cmd) 118 | assert env.get_cmd_output(cmd) == b'Foo\n' 119 | -------------------------------------------------------------------------------- /tests/test_flatten.py: -------------------------------------------------------------------------------- 1 | from withenv.flatten import flatten, flatten_list 2 | 3 | 4 | def test_flatten_dict_strings(): 5 | d = {'foo': {'bar': {'baz': 'hello world'}}} 6 | assert dict(flatten(d)) == {'foo_bar_baz': 'hello world'} 7 | 8 | 9 | def test_flatten_dict_numbers(): 10 | d = {'foo': {'bar': {'baz': 1001}}} 11 | assert dict(flatten(d)) == {'foo_bar_baz': '1001'} 12 | 13 | 14 | def test_flatten_list_of_dicts(): 15 | d = [{'foo': [{'bar': [{'baz': 1001}], }], }] 16 | assert dict(flatten_list(d)) == {'foo_bar_baz': '1001'} 17 | -------------------------------------------------------------------------------- /tests/test_yml_parsing.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | 4 | import yaml 5 | 6 | from withenv.flatten import flatten 7 | 8 | 9 | HERE = os.path.dirname(os.path.abspath(__file__)) 10 | 11 | 12 | class TestYAMLParsing(object): 13 | 14 | def test_include_JSON(self): 15 | yml = os.path.join(HERE, 'envs', 'with_json.yml') 16 | for k, v in flatten(yaml.safe_load(open(yml))): 17 | assert json.loads(v) 18 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py34, py35 3 | 4 | [testenv] 5 | deps = -r{toxinidir}/dev_requirements.txt 6 | commands = py.test {posargs:tests/} 7 | -------------------------------------------------------------------------------- /withenv/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = 'Eric Larson' 4 | __email__ = 'eric@ionrock.org' 5 | __version__ = '0.7.0' 6 | -------------------------------------------------------------------------------- /withenv/args.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from argparse import ArgumentParser, Action, REMAINDER 4 | 5 | 6 | class AddToEnvsAction(Action): 7 | 8 | action_map = { 9 | '-e': 'file', 10 | '--env': 'file', 11 | 12 | '-d': 'directory', 13 | '--dir': 'directory', 14 | 15 | '-a': 'alias', 16 | '--alias': 'alias', 17 | 18 | '-E': 'override', 19 | '--envvar': 'override', 20 | 21 | '-s': 'script', 22 | '--script': 'script', 23 | } 24 | 25 | def __init__(self, *args, **kw): 26 | super(AddToEnvsAction, self).__init__(*args, **kw) 27 | self.env_type = self.action_map.get(self.dest) 28 | 29 | def __call__(self, parser, namespace, values, option_string): 30 | envs = getattr(namespace, self.dest) or [] 31 | envs.append((self.action_map[option_string], values)) 32 | setattr(namespace, self.dest, envs) 33 | 34 | 35 | def parse_args(args=None): 36 | parser = ArgumentParser( 37 | prog='we', 38 | usage='%(prog)s -h [-e ENV_YAML] [-d DIR] [-a ALIAS_YAML] CMD', 39 | description=('Prepare the environment variables ' 40 | 'prior to running a command.'), 41 | 42 | epilog=('More than one flag can be used a time. ' 43 | 'Each flag will be applied to the environment ' 44 | 'variables in order, allowing a cascade of changes.') 45 | ) 46 | 47 | parser.add_argument( 48 | '--clean', action='store_true', default=False, 49 | help='Only use the enviroment from the YAML', 50 | ) 51 | 52 | parser.add_argument( 53 | '-e', '--env', dest='actions', 54 | nargs='?', action=AddToEnvsAction, 55 | help='a YAML file to include in the environment', 56 | metavar='YML', 57 | ) 58 | 59 | parser.add_argument( 60 | '-d', '--dir', dest='actions', 61 | nargs='?', action=AddToEnvsAction, 62 | help=('a directory containing YAML files to ' 63 | 'recursively apply to the environment'), 64 | metavar='DIR', 65 | ) 66 | 67 | parser.add_argument( 68 | '-a', '--alias', dest='actions', 69 | nargs='?', action=AddToEnvsAction, 70 | help=('a YAML file containing a list of ' 71 | 'file/directory to apply to the environment'), 72 | metavar='ALIAS YML', 73 | ) 74 | 75 | parser.add_argument( 76 | '-E', '--envvar', dest='actions', 77 | nargs='?', action=AddToEnvsAction, 78 | help=('override a single envvar'), 79 | metavar='ENVVAR', 80 | ) 81 | 82 | parser.add_argument( 83 | '-s', '--script', dest='actions', 84 | nargs='?', action=AddToEnvsAction, 85 | help=('use the yaml or json output from a script or command'), 86 | metavar='SCRIPT', 87 | ) 88 | 89 | parser.add_argument( 90 | '-D', '--dump', 91 | help=('Dump the env to a file and remove when the process exits'), 92 | metavar='ENVFILE', 93 | ) 94 | 95 | parser.add_argument( 96 | 'cmd', nargs=REMAINDER, 97 | help='The command to run with the supplied environment.', 98 | metavar='CMD' 99 | ) 100 | 101 | args = args if args is not None else sys.argv[1:] 102 | 103 | return parser.parse_args(args) 104 | -------------------------------------------------------------------------------- /withenv/cli.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import subprocess 4 | 5 | import six 6 | 7 | from .config import load_config_file 8 | from .args import parse_args 9 | from .env import compile 10 | 11 | 12 | class Executor(object): 13 | 14 | def __init__(self, cmd): 15 | self.cmd = cmd 16 | 17 | def expanded_cmd(self): 18 | cmd = [] 19 | for part in self.cmd: 20 | cmd.append(os.path.expandvars(part)) 21 | return cmd 22 | 23 | def __call__(self): 24 | try: 25 | proc = subprocess.Popen(self.expanded_cmd()) 26 | proc.wait() 27 | except OSError as e: 28 | print(e) 29 | sys.exit(e.errno) 30 | except (SystemExit, KeyboardInterrupt): 31 | proc.kill() 32 | 33 | return proc 34 | 35 | 36 | def main(): 37 | args = parse_args() 38 | 39 | actions = load_config_file() 40 | actions.extend(args.actions or []) 41 | 42 | env = None 43 | if args.clean: 44 | env = {} 45 | 46 | os.environ = compile(actions, env) 47 | 48 | if args.cmd: 49 | if args.dump: 50 | print('Writing dump file: %s' % args.dump) 51 | with open(args.dump, 'w+') as fh: 52 | for k, v in os.environ.iteritems(): 53 | fh.write('%s=%s\n' % (k, v)) 54 | 55 | cmd = Executor(args.cmd) 56 | proc = cmd() 57 | 58 | if args.dump: 59 | os.remove(args.dump) 60 | 61 | sys.exit(proc.returncode) 62 | 63 | else: 64 | # print our env as a file sourceable in bash. 65 | items = sorted([(k, v) for k, v in six.iteritems(os.environ)]) 66 | for k, v in items: 67 | print("export %s='%s'" % (k, v)) 68 | 69 | if __name__ == '__main__': 70 | main() 71 | -------------------------------------------------------------------------------- /withenv/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import yaml 3 | 4 | 5 | CONFIG_FILE = '.werc' 6 | 7 | 8 | def find_config_file(start=None, filename=CONFIG_FILE): 9 | start = start or os.getcwd() 10 | conf = os.path.join(start, filename) 11 | if os.path.exists(conf): 12 | return conf 13 | 14 | if start == os.path.abspath(os.sep): 15 | return None 16 | 17 | parent = os.path.normpath(os.path.abspath(os.path.join(start, '..'))) 18 | return find_config_file(parent) 19 | 20 | 21 | def load_config_file(): 22 | config_path = find_config_file() 23 | if not config_path: 24 | return [] 25 | return [('alias', config_path)] 26 | -------------------------------------------------------------------------------- /withenv/env.py: -------------------------------------------------------------------------------- 1 | """ 2 | Compile our environment from directories and files. 3 | """ 4 | import os 5 | import shlex 6 | import subprocess 7 | 8 | from heapq import heappush 9 | 10 | import yaml 11 | 12 | from withenv.flatten import flatten 13 | 14 | 15 | def path_relative_to(root, fname): 16 | root = os.path.abspath(root) 17 | if not os.path.isdir(root): 18 | root = os.path.dirname(root) 19 | return os.path.normpath(os.path.join(root, fname)) 20 | 21 | 22 | def string_to_cmd(command): 23 | return [ 24 | os.path.expandvars(part) 25 | for part in shlex.split(command) 26 | ] 27 | 28 | 29 | def find_piped_cmds(cmd): 30 | if '|' not in cmd: 31 | return None 32 | 33 | cmds = [] 34 | cur = [] 35 | for part in cmd: 36 | if part == '|': 37 | cmds.append(cur) 38 | cur = [] 39 | else: 40 | cur.append(part) 41 | cmds.append(cur) 42 | return cmds 43 | 44 | 45 | def get_cmd_output(cmd): 46 | cmds = find_piped_cmds(cmd) 47 | 48 | if not cmds: 49 | return subprocess.check_output(cmd) 50 | 51 | # we have multiple commands 52 | proc = subprocess.Popen(cmds[0], stdout=subprocess.PIPE) 53 | stdout, _ = proc.communicate() 54 | for cmd in cmds[1:]: 55 | proc = subprocess.Popen( 56 | cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE 57 | ) 58 | stdout, _ = proc.communicate(stdout) 59 | proc.wait() 60 | return stdout 61 | 62 | 63 | def compiled_value(v): 64 | if v.startswith('`') and v.endswith('`'): 65 | cmd = string_to_cmd(v[1:-1]) 66 | v = get_cmd_output(cmd).strip() 67 | return os.path.expandvars(v) 68 | 69 | 70 | def load_shell_env_file(fname): 71 | # look for lines with export and parse them 72 | env = {} 73 | with open(fname) as fh: 74 | for line in fh: 75 | if line.startswith('export'): 76 | prefix, _, envvar = line.partition(' ') 77 | k, _, v = envvar.partition('=') 78 | env[k] = compiled_value(v) 79 | 80 | return env 81 | 82 | 83 | def load_env_file(fname): 84 | if fname.endswith(('yml', 'yaml')): 85 | return yaml.safe_load(open(fname)) 86 | return load_shell_env_file(fname) 87 | 88 | 89 | def find_yml_in_dir(dirname): 90 | def is_yaml(fn): 91 | return fn.endswith(('yml', 'yaml')) 92 | 93 | fnames = [] # a heap 94 | 95 | for dirpath, dirnames, filenames in os.walk(dirname): 96 | for fn in filter(is_yaml, filenames): 97 | heappush(fnames, os.path.join(dirpath, fn)) 98 | 99 | return fnames 100 | 101 | 102 | def update_env_from_obj(new_env, env): 103 | # Order isn't important 104 | if isinstance(new_env, dict): 105 | new_env = [new_env] 106 | 107 | if not new_env: 108 | return 109 | 110 | for item in new_env: 111 | for k, v in flatten(item): 112 | env[k] = compiled_value(v) 113 | 114 | 115 | def update_env_from_dir(dirname, env): 116 | for fname in find_yml_in_dir(dirname): 117 | update_env_from_file(fname, env) 118 | 119 | 120 | def update_env_from_file(fname, env): 121 | new_env = yaml.safe_load(open(fname)) 122 | update_env_from_obj(new_env, env) 123 | 124 | 125 | def update_env_from_alias(fname, env): 126 | action_list = yaml.safe_load(open(fname)) 127 | if not action_list: 128 | return env 129 | 130 | actions = [] 131 | for action in action_list: 132 | for k, v in action.items(): 133 | if not k == 'override': 134 | v = path_relative_to(fname, v) 135 | actions.append((k, v)) 136 | 137 | return compile(actions, env) 138 | 139 | 140 | def update_env_from_override(override, env): 141 | k, _, v = override.partition('=') 142 | env[k] = compiled_value(v) 143 | 144 | 145 | def update_env_from_script(script, env): 146 | doc = get_cmd_output(string_to_cmd(script)) 147 | try: 148 | new_env = yaml.safe_load(doc) 149 | update_env_from_obj(new_env, env) 150 | except yaml.YAMLError as e: 151 | print('Invalid YAML: %s' % e) 152 | os.exit(1) 153 | 154 | 155 | def find_action(name): 156 | actions = { 157 | 'file': update_env_from_file, 158 | 'directory': update_env_from_dir, 159 | 'alias': update_env_from_alias, 160 | 'override': update_env_from_override, 161 | 'script': update_env_from_script, 162 | } 163 | return actions[name] 164 | 165 | 166 | def compile(actions=None, env=None): 167 | actions = actions or [] 168 | env = env if env is not None else os.environ 169 | 170 | for action, arg in actions: 171 | find_action(action)(arg, env) 172 | return env 173 | -------------------------------------------------------------------------------- /withenv/flatten.py: -------------------------------------------------------------------------------- 1 | import os 2 | import six 3 | 4 | 5 | def flatten_list(node, prefix=None): 6 | for v in node: 7 | for kid in flatten_dict(v, prefix): 8 | yield kid 9 | 10 | 11 | def flatten_dict(node, prefix=None): 12 | """ 13 | This is an iterator that returns a list of flattened env 14 | vars based on the conf file supplied 15 | """ 16 | for k, v in six.iteritems(node): 17 | if prefix: 18 | k = '%s_%s' % (prefix, k) 19 | 20 | # We have a value we can stringify 21 | if not isinstance(v, (dict, list)): 22 | yield (k, os.path.expandvars(str(v))) 23 | else: 24 | for kid in flatten(v, prefix=k): 25 | yield kid 26 | 27 | 28 | def flatten(node, prefix=None): 29 | flat_func = flatten_dict 30 | if isinstance(node, list): 31 | flat_func = flatten_list 32 | 33 | for kid in flat_func(node, prefix): 34 | yield kid 35 | --------------------------------------------------------------------------------