├── .gitignore ├── .travis.yml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.rst ├── bad.yaml ├── bulk.yaml ├── doc ├── Makefile ├── changelog.rst ├── click.rst ├── commandline.rst ├── conf.py ├── error.rst ├── index.rst ├── make.bat ├── simple_api.rst └── variables.rst ├── example.py ├── setup.py ├── tests ├── __init__.py ├── test_alternatives.py ├── test_lines.py ├── test_scalar.py ├── test_structures.py ├── test_subst.py ├── test_tricks.py └── util.py ├── trafaret_config ├── __init__.py ├── commandline.py ├── error.py └── simple.py └── vagga.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | /trafaret_config.egg-info 2 | /.vagga 3 | /doc/_build 4 | __pycache__ 5 | *.pyc 6 | *.pyo 7 | /tmp 8 | /dist 9 | /build 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | install: "pip install -e ." 3 | script: nosetests 4 | 5 | jobs: 6 | include: 7 | - python: "2.7" 8 | - python: "3.5" 9 | - python: "3.6" 10 | - python: "3.7" 11 | dist: xenial 12 | sudo: true 13 | - stage: publish 14 | python: "3.6" 15 | script: true 16 | deploy: 17 | provider: pypi 18 | user: pc 19 | password: 20 | secure: "yf/0JJDcEpZpU7Dc4rKQJ00Rzc9OhN3hzJTqMHzgaaRqaV/yUQZ23Lz2Mg2yJkMJ4YL5WWr8dQ8l+RkqeoeVAYueR05ekqM0Awm/pmvChRvWcc8v4vfTCND4mntHfLdSD/QWg5k7+tbbrYK7NxD+iDKZ4nxXlmiLTg0nLYSceFtcsP3SLaJC4jeIgTGc3KKTKeqKitSpZYj9rBPtrJYjBYG5qvKXo7PDIdGqLvvRlx5zRNeV01I7mEp0ORmo29+vkLdv8lcp/vgTGTimXzGDxH2g1rClAzAO8Tf1Yi9d5CHR95wYC1lnc2UsFxmSXJhHQHzHXPw7pRUtsE04sjQFh40rxJgAJ4o8qIe0TjNxwOxR5jNkBrcqFunJdYvW79FXIP49TbAxyMd1FmWDq6fMsiTk8LUcvqoHKDIH9gUXOYLx6WHMMaCn/vSWLdD8pnK1MaRyTwsGk+S8LMNnK2Q13c5DqhEKQTHqYnC+XPWdPHklVGGzBjPrraQ/cCisQZY0hSnfNWTAP8+UkSkXyotpmSJSYkBrJmwe7+gLvXFK6c26Pj2xx2o/EahB0wt0ctRx273c7D9wF+X98sz+0Ex0BXy5EX3C4+GnAXd4TI0sjO+3D21AlypSb3GzfVub+cKL6UATFhgFT1JvkkEiZMmdnsvUAzn3jz4VLD8rzINEidQ=" 21 | distributions: "sdist" 22 | on: 23 | tags: true 24 | python: 3.6 25 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 The trafaret-config Developers 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============== 2 | Trafaret Config 3 | =============== 4 | 5 | 6 | :Status: Stable 7 | :Documentation: http://trafaret-config.readthedocs.io/ 8 | 9 | 10 | This is a wrapper that loads yaml and checks config using trafaret_ while 11 | keeping track of actual lines of file where error has happened. Additionally, 12 | it can pretty print the error. 13 | 14 | Basic Usage: 15 | 16 | .. code-block:: python 17 | 18 | import argparse 19 | import trafaret 20 | from trafaret_config import commandline 21 | 22 | TRAFARET = trafaret.Dict({'x': trafaret.String()}) 23 | 24 | def main(): 25 | ap = argparse.ArgumentParser() 26 | commandline.standard_argparse_options(ap, default_config='config.yaml') 27 | # 28 | # define your command-line arguments here 29 | # 30 | options = ap.parse_args() 31 | config = commandline.config_from_options(options, TRAFARET) 32 | pprint.pprint(config) 33 | 34 | Example output when there is an error in config (from a `example.py` which 35 | has better trafaret than example above):: 36 | 37 | bad.yaml:3: smtp.port: value can't be converted to int 38 | -> 'unknown' 39 | bad.yaml:4: smtp.ssl_port: value can't be converted to int 40 | -> 'NaN' 41 | bad.yaml:5: port: value can't be converted to int 42 | -> '???' 43 | 44 | Help looks like this:: 45 | 46 | usage: example.py [-h] [-c CONFIG] [--print-config] [--print-config-vars] [-C] 47 | 48 | optional arguments: 49 | -h, --help show this help message and exit 50 | -c CONFIG, --config CONFIG 51 | Configuration file (default: 'config.yaml') 52 | --print-config Print config as it is read after parsing and exit 53 | --print-config-vars Print variables used in configuration file 54 | -C, --check-config Check configuration and exit 55 | 56 | 57 | Since trafaret-config 2.0 environment variables in the config are replaced 58 | by default, this means that config like this: 59 | 60 | .. code-block:: yaml 61 | 62 | url: http://${HOST}:$PORT/ 63 | 64 | Will get ``HOST`` and ``PORT`` variables insert from the environment, and if 65 | variable does not exist, you will get the following error:: 66 | 67 | config.yaml:2: variable 'PORT' not found 68 | -> 'http://${HOST}:$PORT/' 69 | 70 | Low-level interface, without relying on argparse: 71 | 72 | .. code-block:: python 73 | 74 | import sys 75 | import trafaret 76 | from trafaret_config import ConfigError, read_and_validate 77 | 78 | TRAFARET = trafaret.Dict({'x': trafaret.String()}) 79 | 80 | try: 81 | config = read_and_validate('config.yaml', TRAFARET) 82 | except ConfigError as e: 83 | e.output() 84 | sys.exit(1) 85 | 86 | 87 | 88 | .. _trafaret: http://github.com/Deepwalker/trafaret 89 | 90 | Installation 91 | ============ 92 | 93 | :: 94 | 95 | pip install trafaret-config==2.0.2 96 | 97 | 98 | License 99 | ======= 100 | 101 | Licensed under either of 102 | 103 | * Apache License, Version 2.0, 104 | (./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) 105 | * MIT license (./LICENSE-MIT or http://opensource.org/licenses/MIT) 106 | at your option. 107 | 108 | ------------ 109 | Contribution 110 | ------------ 111 | 112 | Unless you explicitly state otherwise, any contribution intentionally 113 | submitted for inclusion in the work by you, as defined in the Apache-2.0 114 | license, shall be dual licensed as above, without any additional terms or 115 | conditions. 116 | -------------------------------------------------------------------------------- /bad.yaml: -------------------------------------------------------------------------------- 1 | smtp: 2 | server: mail.example.org 3 | port: unknown 4 | ssl_port: NaN 5 | port: ??? 6 | -------------------------------------------------------------------------------- /bulk.yaml: -------------------------------------------------------------------------------- 1 | minimum-bulk: v0.4.1 2 | 3 | versions: 4 | 5 | - file: setup.py 6 | regex: ^\s*version\s*=\s*["']([^"']+)["'] 7 | 8 | - file: trafaret_config/__init__.py 9 | regex: ^__version__\s*=\s*["']([^"']+)["'] 10 | 11 | - file: doc/conf.py 12 | regex: ^version\s*=\s*u?["']([^"']+)["'] 13 | partial-version: ^\d+\.\d+ 14 | 15 | - file: doc/conf.py 16 | regex: ^release\s*=\s*u?["']([^"']+)["'] 17 | 18 | - file: README.rst 19 | regex: trafaret-config==(\S+) 20 | -------------------------------------------------------------------------------- /doc/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 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help 18 | help: 19 | @echo "Please use \`make ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " singlehtml to make a single large HTML file" 23 | @echo " pickle to make pickle files" 24 | @echo " json to make JSON files" 25 | @echo " htmlhelp to make HTML files and a HTML help project" 26 | @echo " qthelp to make HTML files and a qthelp project" 27 | @echo " applehelp to make an Apple Help Book" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " epub3 to make an epub3" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " xml to make Docutils-native XML files" 41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 42 | @echo " linkcheck to check all external links for integrity" 43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 44 | @echo " coverage to run coverage check of the documentation (if enabled)" 45 | @echo " dummy to check syntax errors of document sources" 46 | 47 | .PHONY: clean 48 | clean: 49 | rm -rf $(BUILDDIR)/* 50 | 51 | .PHONY: html 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | .PHONY: dirhtml 58 | dirhtml: 59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 60 | @echo 61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 62 | 63 | .PHONY: singlehtml 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | .PHONY: pickle 70 | pickle: 71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 72 | @echo 73 | @echo "Build finished; now you can process the pickle files." 74 | 75 | .PHONY: json 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | .PHONY: htmlhelp 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | .PHONY: qthelp 89 | qthelp: 90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 91 | @echo 92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/TrafaretConfig.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/TrafaretConfig.qhc" 97 | 98 | .PHONY: applehelp 99 | applehelp: 100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 101 | @echo 102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 103 | @echo "N.B. You won't be able to view it unless you put it in" \ 104 | "~/Library/Documentation/Help or install it in your application" \ 105 | "bundle." 106 | 107 | .PHONY: devhelp 108 | devhelp: 109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 110 | @echo 111 | @echo "Build finished." 112 | @echo "To view the help file:" 113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/TrafaretConfig" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/TrafaretConfig" 115 | @echo "# devhelp" 116 | 117 | .PHONY: epub 118 | epub: 119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 120 | @echo 121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 122 | 123 | .PHONY: epub3 124 | epub3: 125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 126 | @echo 127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 128 | 129 | .PHONY: latex 130 | latex: 131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 132 | @echo 133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 135 | "(use \`make latexpdf' here to do that automatically)." 136 | 137 | .PHONY: latexpdf 138 | latexpdf: 139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 140 | @echo "Running LaTeX files through pdflatex..." 141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 143 | 144 | .PHONY: latexpdfja 145 | latexpdfja: 146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 147 | @echo "Running LaTeX files through platex and dvipdfmx..." 148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 150 | 151 | .PHONY: text 152 | text: 153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 154 | @echo 155 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 156 | 157 | .PHONY: man 158 | man: 159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 160 | @echo 161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 162 | 163 | .PHONY: texinfo 164 | texinfo: 165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 166 | @echo 167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 168 | @echo "Run \`make' in that directory to run these through makeinfo" \ 169 | "(use \`make info' here to do that automatically)." 170 | 171 | .PHONY: info 172 | info: 173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 174 | @echo "Running Texinfo files through makeinfo..." 175 | make -C $(BUILDDIR)/texinfo info 176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 177 | 178 | .PHONY: gettext 179 | gettext: 180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 181 | @echo 182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 183 | 184 | .PHONY: changes 185 | changes: 186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 187 | @echo 188 | @echo "The overview file is in $(BUILDDIR)/changes." 189 | 190 | .PHONY: linkcheck 191 | linkcheck: 192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 193 | @echo 194 | @echo "Link check complete; look for any errors in the above output " \ 195 | "or in $(BUILDDIR)/linkcheck/output.txt." 196 | 197 | .PHONY: doctest 198 | doctest: 199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 200 | @echo "Testing of doctests in the sources finished, look at the " \ 201 | "results in $(BUILDDIR)/doctest/output.txt." 202 | 203 | .PHONY: coverage 204 | coverage: 205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 206 | @echo "Testing of coverage in the sources finished, look at the " \ 207 | "results in $(BUILDDIR)/coverage/python.txt." 208 | 209 | .PHONY: xml 210 | xml: 211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 212 | @echo 213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 214 | 215 | .PHONY: pseudoxml 216 | pseudoxml: 217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 218 | @echo 219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 220 | 221 | .PHONY: dummy 222 | dummy: 223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 224 | @echo 225 | @echo "Build finished. Dummy builder generates no files." 226 | -------------------------------------------------------------------------------- /doc/changelog.rst: -------------------------------------------------------------------------------- 1 | Trafaret-config Changes by Release 2 | ================================== 3 | 4 | v2.0.1 5 | ------ 6 | 7 | * Package metadata update only 8 | 9 | 10 | v2.0.0 11 | ------ 12 | 13 | * breaking: trafaret >= 1.2.0 is only supported (previous versions may work) 14 | * breaking: PyYAML >= 4.1 is only supported (previous versions may work) 15 | * breaking feature: Variables like ``$this`` or ``${THIS}`` are substituted in 16 | all scalar in yaml file, if you relied on this kind of values present in the 17 | config verbatim, pass ``vars=None`` to config parser 18 | * feature: Add ``--print-config-vars`` command-line argument to print variables 19 | used in specific config 20 | -------------------------------------------------------------------------------- /doc/click.rst: -------------------------------------------------------------------------------- 1 | .. _click_cli: 2 | 3 | Command-Line with `click` 4 | ========================= 5 | 6 | click_ is another popular package for creating beautiful CLI. 7 | 8 | .. _click: http://click.pocoo.org 9 | 10 | One option to use `trafaret_config` is to define new `click` argument type based, which expects path 11 | to an existing configuration file plus trafaret rules. 12 | 13 | Create `cli.py`: 14 | 15 | .. code-block:: python 16 | :linenos: 17 | 18 | import click 19 | import trafaret_config as traf_cfg 20 | import trafaret as t 21 | import time 22 | 23 | CONFIG_TRAFARET = t.Dict({t.Key("host"): t.String(), t.Key("port"): t.Int()}) 24 | 25 | 26 | class TrafaretYaml(click.Path): 27 | """Configuration read from YAML file checked against trafaret rules.""" 28 | name = "trafaret yaml file" 29 | 30 | def __init__(self, trafaret): 31 | self.trafaret = trafaret 32 | super().__init__( 33 | exists=True, file_okay=True, dir_okay=False, readable=True) 34 | 35 | def convert(self, value, param, ctx): 36 | cfg_file = super().convert(value, param, ctx) 37 | try: 38 | return traf_cfg.read_and_validate(cfg_file, self.trafaret) 39 | except traf_cfg.ConfigError as e: 40 | msg = "\n".join(str(err) for err in e.errors) 41 | self.fail("\n" + msg) 42 | 43 | 44 | @click.group() 45 | def cli(): 46 | pass 47 | 48 | 49 | @cli.command() 50 | @click.argument("config", type=TrafaretYaml(CONFIG_TRAFARET)) 51 | def validate(config): 52 | """Validate configuration file structure.""" 53 | click.echo("OK: Configuration is valid.") 54 | 55 | 56 | @cli.command() 57 | @click.argument("config", type=TrafaretYaml(CONFIG_TRAFARET)) 58 | def run(config): 59 | """Run web application. 60 | """ 61 | # Start the application 62 | host = config["host"] 63 | port = config["port"] 64 | print("Would like to run the app at {host}:{port}...".format( 65 | host=host, port=port)) 66 | time.sleep(5) 67 | print("..done.") 68 | 69 | 70 | if __name__ == "__main__": 71 | cli() 72 | 73 | 74 | `CONFIG_TRAFARET` is sample trafaret rule for our config file, which may look like `config.yaml`:: 75 | 76 | host: localhost 77 | port: 1234 78 | 79 | 80 | `class TrafaretYaml(click.Path)` defines a class for new `click` type. 81 | 82 | 83 | `def cli():` defines top level command to run and it has two subcommands: 84 | 85 | 86 | Subcommand validating the configuration file is really simple:: 87 | 88 | @cli.command() 89 | @click.argument("config", type=TrafaretYaml(CONFIG_TRAFARET)) 90 | def validate(config): 91 | """Validate configuration file structure.""" 92 | click.echo("OK: Configuration is valid.") 93 | 94 | using `type=TrafaretYaml` it implicitly expects path to config file and at the same time prescribes 95 | trafaret rules for it's content. 96 | 97 | `def run():` goes one step further and uses the configuration values. 98 | 99 | 100 | Sample usage 101 | ------------ 102 | 103 | First explore the main command:: 104 | 105 | $ python cli.py 106 | Usage: cli.py [OPTIONS] COMMAND [ARGS]... 107 | 108 | Options: 109 | --help Show this message and exit. 110 | 111 | Commands: 112 | run Run web application. 113 | validate Validate configuration file structure. 114 | 115 | It provides two subcommands. 116 | 117 | Subcommand `validate` allows configuration file validation:: 118 | 119 | $ python cli.py validate cfg.yaml 120 | OK: Configuration is valid. 121 | 122 | If the config file does not exist:: 123 | 124 | $ python cli.py run cfg-not-here.yaml 125 | Usage: cli.py run [OPTIONS] CONFIG 126 | 127 | Error: Invalid value for "config": Path "cfg-not-here.yaml" does not exist. 128 | 129 | it reports this problem. 130 | 131 | If port number has value `1234a`, it uses trafaret rules to report the problem:: 132 | 133 | $ python cli.py va lidate cfg.yaml 134 | Usage: cli.py validate [OPTIONS] CONFIG 135 | 136 | Error: Invalid value for "config": 137 | cfg.yaml:2: port: value can't be converted to int 138 | 139 | If all is fine, it allows running the applicaiton:: 140 | 141 | $ python cli.py run cfg.yaml 142 | Would like to run the app at localhost:1234... 143 | ..done. 144 | 145 | Hint: add subcommand `init` printing sample configuration file content. 146 | -------------------------------------------------------------------------------- /doc/commandline.rst: -------------------------------------------------------------------------------- 1 | .. _command-line: 2 | 3 | Command-Line 4 | ============ 5 | 6 | Usually you want to accept filename of a configuration file from the 7 | command-line. While it's easy to define command-line arguments yourself, 8 | there are two helpers, which allow to define options with the standard 9 | names, so all of your applications are configured in the same way. 10 | 11 | Usage: 12 | 13 | .. code-block:: python 14 | 15 | from trafaret_config import read_and_validate, ConfigError 16 | from trafaret_config import commandline 17 | from your_config_module import CONFIG_TRAFARET 18 | 19 | def main(): 20 | ap = argparse.ArgumentParser() 21 | commandline.standard_argparse_options(ap, default_config='config.yaml') 22 | # 23 | # define your command-line arguments here 24 | # 25 | options = ap.parse_args() 26 | config = commandline.config_from_options(options, CONFIG_TRAFARET) 27 | pprint.pprint(config) 28 | 29 | 30 | You can find `full example`_ in the repository. 31 | 32 | The ``--help`` looks like:: 33 | 34 | usage: example.py [-h] [-c CONFIG] [--print-config] [--print-config-vars] [-C] 35 | 36 | optional arguments: 37 | -h, --help show this help message and exit 38 | -c CONFIG, --config CONFIG 39 | Configuration file (default: 'config.yaml') 40 | --print-config Print config as it is read after parsing and exit 41 | --print-config-vars Print variables used in configuration file 42 | -C, --check-config Check configuration and exit 43 | 44 | .. _full example: https://github.com/tailhook/trafaret-config/blob/master/example.py 45 | 46 | Alternatively you can put configuration parameters into it's own option group: 47 | 48 | .. code-block:: python 49 | 50 | def main(): 51 | ap = argparse.ArgumentParser() 52 | commandline.standard_argparse_options( 53 | ap.add_argument_group('configuration'), 54 | default_config='config.yaml') 55 | 56 | ap.add_argument('--verbose', action='store_true') 57 | 58 | Output looks like:: 59 | 60 | usage: example-cli.py [-h] [-c CONFIG] [--print-config] [-C] [--verbose] 61 | 62 | optional arguments: 63 | -h, --help show this help message and exit 64 | --verbose 65 | 66 | configuration: 67 | -c CONFIG, --config CONFIG 68 | Configuration file (default: 'config.yaml') 69 | --print-config Print config as it is read after parsing and exit 70 | -C, --check-config Check configuration and exit 71 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Trafaret Config documentation build configuration file, created by 4 | # sphinx-quickstart on Thu Aug 4 09:16:52 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | # If extensions (or modules to document with autodoc) are in another directory, 16 | # add these directories to sys.path here. If the directory is relative to the 17 | # documentation root, use os.path.abspath to make it absolute, like shown here. 18 | # 19 | # import os 20 | # import sys 21 | # sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | # 27 | # needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [] 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ['_templates'] 36 | 37 | # The suffix(es) of source filenames. 38 | # You can specify multiple suffix as a list of string: 39 | # 40 | # source_suffix = ['.rst', '.md'] 41 | source_suffix = '.rst' 42 | 43 | # The encoding of source files. 44 | # 45 | # source_encoding = 'utf-8-sig' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # General information about the project. 51 | project = u'Trafaret Config' 52 | copyright = u'2016, paul@colomiets.name' 53 | author = u'paul@colomiets.name' 54 | 55 | # The version info for the project you're documenting, acts as replacement for 56 | # |version| and |release|, also used in various other places throughout the 57 | # built documents. 58 | # 59 | # The short X.Y version. 60 | version = u'2.0' 61 | # The full version, including alpha/beta/rc tags. 62 | release = u'2.0.2' 63 | 64 | # The language for content autogenerated by Sphinx. Refer to documentation 65 | # for a list of supported languages. 66 | # 67 | # This is also used if you do content translation via gettext catalogs. 68 | # Usually you set "language" from the command line for these cases. 69 | language = None 70 | 71 | # There are two options for replacing |today|: either, you set today to some 72 | # non-false value, then it is used: 73 | # 74 | # today = '' 75 | # 76 | # Else, today_fmt is used as the format for a strftime call. 77 | # 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 | # This patterns also effect to html_static_path and html_extra_path 83 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 84 | 85 | # The reST default role (used for this markup: `text`) to use for all 86 | # documents. 87 | # 88 | # default_role = None 89 | 90 | # If true, '()' will be appended to :func: etc. cross-reference text. 91 | # 92 | # add_function_parentheses = True 93 | 94 | # If true, the current module name will be prepended to all description 95 | # unit titles (such as .. function::). 96 | # 97 | # add_module_names = True 98 | 99 | # If true, sectionauthor and moduleauthor directives will be shown in the 100 | # output. They are ignored by default. 101 | # 102 | # show_authors = False 103 | 104 | # The name of the Pygments (syntax highlighting) style to use. 105 | pygments_style = 'sphinx' 106 | 107 | # A list of ignored prefixes for module index sorting. 108 | # modindex_common_prefix = [] 109 | 110 | # If true, keep warnings as "system message" paragraphs in the built documents. 111 | # keep_warnings = False 112 | 113 | # If true, `todo` and `todoList` produce output, else they produce nothing. 114 | todo_include_todos = False 115 | 116 | 117 | # -- Options for HTML output ---------------------------------------------- 118 | 119 | # The theme to use for HTML and HTML Help pages. See the documentation for 120 | # a list of builtin themes. 121 | # 122 | html_theme = 'alabaster' 123 | 124 | # Theme options are theme-specific and customize the look and feel of a theme 125 | # further. For a list of options available for each theme, see the 126 | # documentation. 127 | # 128 | # html_theme_options = {} 129 | 130 | # Add any paths that contain custom themes here, relative to this directory. 131 | # html_theme_path = [] 132 | 133 | # The name for this set of Sphinx documents. 134 | # " v documentation" by default. 135 | # 136 | # html_title = u'Trafaret Config v0.1.0' 137 | 138 | # A shorter title for the navigation bar. Default is the same as html_title. 139 | # 140 | # html_short_title = None 141 | 142 | # The name of an image file (relative to this directory) to place at the top 143 | # of the sidebar. 144 | # 145 | # html_logo = None 146 | 147 | # The name of an image file (relative to this directory) to use as a favicon of 148 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 149 | # pixels large. 150 | # 151 | # html_favicon = None 152 | 153 | # Add any paths that contain custom static files (such as style sheets) here, 154 | # relative to this directory. They are copied after the builtin static files, 155 | # so a file named "default.css" will overwrite the builtin "default.css". 156 | html_static_path = ['_static'] 157 | 158 | # Add any extra paths that contain custom files (such as robots.txt or 159 | # .htaccess) here, relative to this directory. These files are copied 160 | # directly to the root of the documentation. 161 | # 162 | # html_extra_path = [] 163 | 164 | # If not None, a 'Last updated on:' timestamp is inserted at every page 165 | # bottom, using the given strftime format. 166 | # The empty string is equivalent to '%b %d, %Y'. 167 | # 168 | # html_last_updated_fmt = None 169 | 170 | # If true, SmartyPants will be used to convert quotes and dashes to 171 | # typographically correct entities. 172 | # 173 | # html_use_smartypants = True 174 | 175 | # Custom sidebar templates, maps document names to template names. 176 | # 177 | # html_sidebars = {} 178 | 179 | # Additional templates that should be rendered to pages, maps page names to 180 | # template names. 181 | # 182 | # html_additional_pages = {} 183 | 184 | # If false, no module index is generated. 185 | # 186 | # html_domain_indices = True 187 | 188 | # If false, no index is generated. 189 | # 190 | # html_use_index = True 191 | 192 | # If true, the index is split into individual pages for each letter. 193 | # 194 | # html_split_index = False 195 | 196 | # If true, links to the reST sources are added to the pages. 197 | # 198 | # html_show_sourcelink = True 199 | 200 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 201 | # 202 | # html_show_sphinx = True 203 | 204 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 205 | # 206 | # html_show_copyright = True 207 | 208 | # If true, an OpenSearch description file will be output, and all pages will 209 | # contain a tag referring to it. The value of this option must be the 210 | # base URL from which the finished HTML is served. 211 | # 212 | # html_use_opensearch = '' 213 | 214 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 215 | # html_file_suffix = None 216 | 217 | # Language to be used for generating the HTML full-text search index. 218 | # Sphinx supports the following languages: 219 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 220 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' 221 | # 222 | # html_search_language = 'en' 223 | 224 | # A dictionary with options for the search language support, empty by default. 225 | # 'ja' uses this config value. 226 | # 'zh' user can custom change `jieba` dictionary path. 227 | # 228 | # html_search_options = {'type': 'default'} 229 | 230 | # The name of a javascript file (relative to the configuration directory) that 231 | # implements a search results scorer. If empty, the default will be used. 232 | # 233 | # html_search_scorer = 'scorer.js' 234 | 235 | # Output file base name for HTML help builder. 236 | htmlhelp_basename = 'TrafaretConfigdoc' 237 | 238 | # -- Options for LaTeX output --------------------------------------------- 239 | 240 | latex_elements = { 241 | # The paper size ('letterpaper' or 'a4paper'). 242 | # 243 | # 'papersize': 'letterpaper', 244 | 245 | # The font size ('10pt', '11pt' or '12pt'). 246 | # 247 | # 'pointsize': '10pt', 248 | 249 | # Additional stuff for the LaTeX preamble. 250 | # 251 | # 'preamble': '', 252 | 253 | # Latex figure (float) alignment 254 | # 255 | # 'figure_align': 'htbp', 256 | } 257 | 258 | # Grouping the document tree into LaTeX files. List of tuples 259 | # (source start file, target name, title, 260 | # author, documentclass [howto, manual, or own class]). 261 | latex_documents = [ 262 | (master_doc, 'TrafaretConfig.tex', u'Trafaret Config Documentation', 263 | u'paul@colomiets.name', 'manual'), 264 | ] 265 | 266 | # The name of an image file (relative to this directory) to place at the top of 267 | # the title page. 268 | # 269 | # latex_logo = None 270 | 271 | # For "manual" documents, if this is true, then toplevel headings are parts, 272 | # not chapters. 273 | # 274 | # latex_use_parts = False 275 | 276 | # If true, show page references after internal links. 277 | # 278 | # latex_show_pagerefs = False 279 | 280 | # If true, show URL addresses after external links. 281 | # 282 | # latex_show_urls = False 283 | 284 | # Documents to append as an appendix to all manuals. 285 | # 286 | # latex_appendices = [] 287 | 288 | # It false, will not define \strong, \code, itleref, \crossref ... but only 289 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added 290 | # packages. 291 | # 292 | # latex_keep_old_macro_names = True 293 | 294 | # If false, no module index is generated. 295 | # 296 | # latex_domain_indices = True 297 | 298 | 299 | # -- Options for manual page output --------------------------------------- 300 | 301 | # One entry per manual page. List of tuples 302 | # (source start file, name, description, authors, manual section). 303 | man_pages = [ 304 | (master_doc, 'trafaretconfig', u'Trafaret Config Documentation', 305 | [author], 1) 306 | ] 307 | 308 | # If true, show URL addresses after external links. 309 | # 310 | # man_show_urls = False 311 | 312 | 313 | # -- Options for Texinfo output ------------------------------------------- 314 | 315 | # Grouping the document tree into Texinfo files. List of tuples 316 | # (source start file, target name, title, author, 317 | # dir menu entry, description, category) 318 | texinfo_documents = [ 319 | (master_doc, 'TrafaretConfig', u'Trafaret Config Documentation', 320 | author, 'TrafaretConfig', 'One line description of project.', 321 | 'Miscellaneous'), 322 | ] 323 | 324 | # Documents to append as an appendix to all manuals. 325 | # 326 | # texinfo_appendices = [] 327 | 328 | # If false, no module index is generated. 329 | # 330 | # texinfo_domain_indices = True 331 | 332 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 333 | # 334 | # texinfo_show_urls = 'footnote' 335 | 336 | # If true, do not generate a @detailmenu in the "Top" node's menu. 337 | # 338 | # texinfo_no_detailmenu = False 339 | -------------------------------------------------------------------------------- /doc/error.rst: -------------------------------------------------------------------------------- 1 | ========= 2 | Error API 3 | ========= 4 | 5 | .. py:class:: ConfigError 6 | 7 | Error returned from configuration validator. Contains filenames, 8 | line numbers, error messages and other info needed to pretty-print error 9 | messages. 10 | 11 | We don't provide programmatic API to access the data yet, because we're not 12 | sure about the details yet. 13 | 14 | .. py:method:: output(stream=None) 15 | 16 | Output the error to a stream. 17 | 18 | :param stream: A text stream (a file open in text mode) to write output 19 | to. If not specified error is printed to ``sys.stderr``. You can use 20 | :class:`io.StringIO` to collect output to an in-memory buffer. 21 | 22 | Example: 23 | 24 | .. code-block:: python 25 | 26 | try: 27 | config = read_and_validate(filename, trafaret) 28 | except ConfigError as err: 29 | err.output(stream=sys.stderr) 30 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | .. Trafaret Config documentation master file, created by 2 | sphinx-quickstart on Thu Aug 4 09:16:52 2016. 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 Trafaret Config's documentation! 7 | =========================================== 8 | 9 | Trafaret-config is a wrapper that loads yaml and checks config using trafaret_ 10 | while keeping track of actual lines of file where error has happened. 11 | 12 | Additionally, it can pretty print the error. 13 | 14 | 15 | Contents 16 | -------- 17 | 18 | .. toctree:: 19 | :maxdepth: 2 20 | 21 | simple_api 22 | error 23 | commandline 24 | click 25 | variables 26 | changelog 27 | 28 | 29 | Basic Usage 30 | ----------- 31 | 32 | For easier real-life usage see :ref:`Command-Line` section. 33 | 34 | .. code-block:: python 35 | 36 | import sys 37 | import trafaret 38 | from trafaret_config import read_and_validate 39 | 40 | TRAFARET = trafaret.Dict({'x': trafaret.String()}) 41 | 42 | try: 43 | config = read_and_validate('config.yaml', TRAFARET) 44 | except ConfigError as e: 45 | e.output() 46 | sys.exit(1) 47 | 48 | 49 | Example output (from a `test.py` which has better trafaret than example 50 | above):: 51 | 52 | bad.yaml:2: smtp.port: value can't be converted to int 53 | bad.yaml:3: smtp.ssl_port: value can't be converted to int 54 | bad.yaml:4: port: value can't be converted to int 55 | 56 | 57 | .. _trafaret: http://github.com/Deepwalker/trafaret 58 | 59 | Indices and tables 60 | ================== 61 | 62 | * :ref:`genindex` 63 | * :ref:`search` 64 | 65 | -------------------------------------------------------------------------------- /doc/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. epub3 to make an epub3 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. xml to make Docutils-native XML files 38 | echo. pseudoxml to make pseudoxml-XML files for display purposes 39 | echo. linkcheck to check all external links for integrity 40 | echo. doctest to run all doctests embedded in the documentation if enabled 41 | echo. coverage to run coverage check of the documentation if enabled 42 | echo. dummy to check syntax errors of document sources 43 | goto end 44 | ) 45 | 46 | if "%1" == "clean" ( 47 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 48 | del /q /s %BUILDDIR%\* 49 | goto end 50 | ) 51 | 52 | 53 | REM Check if sphinx-build is available and fallback to Python version if any 54 | %SPHINXBUILD% 1>NUL 2>NUL 55 | if errorlevel 9009 goto sphinx_python 56 | goto sphinx_ok 57 | 58 | :sphinx_python 59 | 60 | set SPHINXBUILD=python -m sphinx.__init__ 61 | %SPHINXBUILD% 2> nul 62 | if errorlevel 9009 ( 63 | echo. 64 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 65 | echo.installed, then set the SPHINXBUILD environment variable to point 66 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 67 | echo.may add the Sphinx directory to PATH. 68 | echo. 69 | echo.If you don't have Sphinx installed, grab it from 70 | echo.http://sphinx-doc.org/ 71 | exit /b 1 72 | ) 73 | 74 | :sphinx_ok 75 | 76 | 77 | if "%1" == "html" ( 78 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 79 | if errorlevel 1 exit /b 1 80 | echo. 81 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 82 | goto end 83 | ) 84 | 85 | if "%1" == "dirhtml" ( 86 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 87 | if errorlevel 1 exit /b 1 88 | echo. 89 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 90 | goto end 91 | ) 92 | 93 | if "%1" == "singlehtml" ( 94 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 95 | if errorlevel 1 exit /b 1 96 | echo. 97 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 98 | goto end 99 | ) 100 | 101 | if "%1" == "pickle" ( 102 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 103 | if errorlevel 1 exit /b 1 104 | echo. 105 | echo.Build finished; now you can process the pickle files. 106 | goto end 107 | ) 108 | 109 | if "%1" == "json" ( 110 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 111 | if errorlevel 1 exit /b 1 112 | echo. 113 | echo.Build finished; now you can process the JSON files. 114 | goto end 115 | ) 116 | 117 | if "%1" == "htmlhelp" ( 118 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 119 | if errorlevel 1 exit /b 1 120 | echo. 121 | echo.Build finished; now you can run HTML Help Workshop with the ^ 122 | .hhp project file in %BUILDDIR%/htmlhelp. 123 | goto end 124 | ) 125 | 126 | if "%1" == "qthelp" ( 127 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 128 | if errorlevel 1 exit /b 1 129 | echo. 130 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 131 | .qhcp project file in %BUILDDIR%/qthelp, like this: 132 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\TrafaretConfig.qhcp 133 | echo.To view the help file: 134 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\TrafaretConfig.ghc 135 | goto end 136 | ) 137 | 138 | if "%1" == "devhelp" ( 139 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 140 | if errorlevel 1 exit /b 1 141 | echo. 142 | echo.Build finished. 143 | goto end 144 | ) 145 | 146 | if "%1" == "epub" ( 147 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 148 | if errorlevel 1 exit /b 1 149 | echo. 150 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 151 | goto end 152 | ) 153 | 154 | if "%1" == "epub3" ( 155 | %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 156 | if errorlevel 1 exit /b 1 157 | echo. 158 | echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. 159 | goto end 160 | ) 161 | 162 | if "%1" == "latex" ( 163 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 164 | if errorlevel 1 exit /b 1 165 | echo. 166 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdf" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "latexpdfja" ( 181 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 182 | cd %BUILDDIR%/latex 183 | make all-pdf-ja 184 | cd %~dp0 185 | echo. 186 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 187 | goto end 188 | ) 189 | 190 | if "%1" == "text" ( 191 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 192 | if errorlevel 1 exit /b 1 193 | echo. 194 | echo.Build finished. The text files are in %BUILDDIR%/text. 195 | goto end 196 | ) 197 | 198 | if "%1" == "man" ( 199 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 200 | if errorlevel 1 exit /b 1 201 | echo. 202 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 203 | goto end 204 | ) 205 | 206 | if "%1" == "texinfo" ( 207 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 208 | if errorlevel 1 exit /b 1 209 | echo. 210 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 211 | goto end 212 | ) 213 | 214 | if "%1" == "gettext" ( 215 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 216 | if errorlevel 1 exit /b 1 217 | echo. 218 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 219 | goto end 220 | ) 221 | 222 | if "%1" == "changes" ( 223 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 224 | if errorlevel 1 exit /b 1 225 | echo. 226 | echo.The overview file is in %BUILDDIR%/changes. 227 | goto end 228 | ) 229 | 230 | if "%1" == "linkcheck" ( 231 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 232 | if errorlevel 1 exit /b 1 233 | echo. 234 | echo.Link check complete; look for any errors in the above output ^ 235 | or in %BUILDDIR%/linkcheck/output.txt. 236 | goto end 237 | ) 238 | 239 | if "%1" == "doctest" ( 240 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 241 | if errorlevel 1 exit /b 1 242 | echo. 243 | echo.Testing of doctests in the sources finished, look at the ^ 244 | results in %BUILDDIR%/doctest/output.txt. 245 | goto end 246 | ) 247 | 248 | if "%1" == "coverage" ( 249 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 250 | if errorlevel 1 exit /b 1 251 | echo. 252 | echo.Testing of coverage in the sources finished, look at the ^ 253 | results in %BUILDDIR%/coverage/python.txt. 254 | goto end 255 | ) 256 | 257 | if "%1" == "xml" ( 258 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 259 | if errorlevel 1 exit /b 1 260 | echo. 261 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 262 | goto end 263 | ) 264 | 265 | if "%1" == "pseudoxml" ( 266 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 267 | if errorlevel 1 exit /b 1 268 | echo. 269 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 270 | goto end 271 | ) 272 | 273 | if "%1" == "dummy" ( 274 | %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy 275 | if errorlevel 1 exit /b 1 276 | echo. 277 | echo.Build finished. Dummy builder generates no files. 278 | goto end 279 | ) 280 | 281 | :end 282 | -------------------------------------------------------------------------------- /doc/simple_api.rst: -------------------------------------------------------------------------------- 1 | .. default-domain:: python 2 | 3 | ========== 4 | Simple API 5 | ========== 6 | 7 | 8 | There are just two functions: 9 | 10 | .. py:function:: read_and_validate(filename, trafaret) 11 | 12 | Reads the file at ``filename`` and validates it using trafaret. Returns 13 | config when configuration is fine. 14 | 15 | Example usage: 16 | 17 | .. code-block:: python 18 | 19 | try: 20 | config = read_and_validate('config.yaml', TRAFARET) 21 | except ConfigError as e: 22 | e.output() 23 | sys.exit(1) 24 | 25 | 26 | .. py:function:: parse_and_validate(data, trafaret, filename='') 27 | 28 | Parses a string and validates it using trafaret. Returns 29 | config when configuration is fine. For having adequate filename in error 30 | messages you can either pass `filename` here or you can implement your 31 | own error printer. 32 | 33 | Example usage: 34 | 35 | .. code-block:: python 36 | 37 | with open("config.yaml") as f: 38 | text = f.read() 39 | try: 40 | config = parse_and_validate(text, TRAFARET, filename='config.yaml') 41 | except ConfigError as e: 42 | e.output() 43 | sys.exit(1) 44 | 45 | -------------------------------------------------------------------------------- /doc/variables.rst: -------------------------------------------------------------------------------- 1 | .. _variables: 2 | 3 | Variable Substitution 4 | ===================== 5 | 6 | Since trafaret-config 2.0 environment variables in the config are replaced 7 | by default, this means that config like this: 8 | 9 | .. code-block:: yaml 10 | 11 | url: http://${HOST}:$PORT/ 12 | 13 | Will get ``HOST`` and ``PORT`` variables insert from the environment, and if 14 | variable does not exist, you will get the following error:: 15 | 16 | config.yaml:2: variable 'PORT' not found 17 | -> 'http://${HOST}:$PORT/' 18 | 19 | To override variables that are subsituted pass ``vars={'some': 'dict'}`` to 20 | any of the functions: 21 | 22 | * ``config_from_options(..., vars=custom_vars)`` 23 | * ``read_and_validate(..., vars=custom_vars)`` 24 | * ``parse_and_validate(..., vars=custom_vars)`` 25 | 26 | To turn off variable substitution at all pass ``vars=None`` 27 | 28 | Sometimes you might want to print variables used in configuration file, i.e. 29 | to make some configuration file inter. If you're using 30 | ``trafaret_config.commandline`` you can do it using default command-line 31 | argument:: 32 | 33 | $ ./run.py --print-config-vars 34 | HOST 35 | PORT 36 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import pprint 3 | import argparse 4 | import trafaret as T 5 | from trafaret_config import read_and_validate, ConfigError 6 | from trafaret_config import commandline 7 | 8 | TRAFARET = T.Dict({ 9 | T.Key('port', default=8080): T.Int(), 10 | T.Key('smtp'): T.Dict({ 11 | 'server': T.String(), 12 | 'port': T.Int(), 13 | 'ssl_port': T.Int(), 14 | }), 15 | }) 16 | 17 | 18 | def main(): 19 | ap = argparse.ArgumentParser() 20 | commandline.standard_argparse_options(ap, default_config='config.yaml') 21 | options = ap.parse_args() 22 | config = commandline.config_from_options(options, TRAFARET) 23 | pprint.pprint(config) 24 | 25 | if __name__ == '__main__': 26 | main() 27 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from setuptools import setup 4 | 5 | from os import path 6 | this_directory = path.abspath(path.dirname(__file__)) 7 | with open(path.join(this_directory, 'README.rst'), 'rt') as f: 8 | long_description = f.read() 9 | 10 | setup(name='trafaret-config', 11 | version='2.0.2', 12 | description='A configuration library for python using trafaret and yaml', 13 | author='Paul Colomiets', 14 | author_email='paul@colomiets.name', 15 | url='http://github.com/tailhook/trafaret-config', 16 | packages=['trafaret_config'], 17 | install_requires=[ 18 | 'PyYaml', 19 | 'trafaret', 20 | ], 21 | classifiers=[ 22 | 'Development Status :: 5 - Production/Stable', 23 | 'Programming Language :: Python :: 2', 24 | 'Programming Language :: Python :: 2.7', 25 | 'Programming Language :: Python :: 3', 26 | 'Programming Language :: Python :: 3.5', 27 | 'Programming Language :: Python :: 3.6', 28 | 'Programming Language :: Python :: 3.7', 29 | 'License :: OSI Approved :: MIT License', 30 | 'License :: OSI Approved :: Apache Software License', 31 | ], 32 | long_description=long_description, 33 | ) 34 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tailhook/trafaret-config/0063a5027e7db015e0b0b0dafd8159df409121f2/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_alternatives.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from textwrap import dedent 3 | 4 | import trafaret as T 5 | 6 | from .util import get_err 7 | 8 | BEAUTY_ERROR = hasattr(T.DataError, 'trafaret') 9 | 10 | 11 | class TestEasyAlternatives(unittest.TestCase): 12 | maxDiff = 8192 13 | 14 | TRAFARET = T.Dict({ 15 | "connection": T.Or( 16 | T.Dict({ 17 | "kind": T.Atom("unix"), 18 | "path": T.String(), 19 | }), 20 | T.Dict({ 21 | "kind": T.Atom("tcp"), 22 | "host": T.String(), 23 | "port": T.Int, 24 | }), 25 | ), 26 | }) 27 | 28 | if BEAUTY_ERROR: 29 | 30 | def test_tcp(self): 31 | self.assertEqual(get_err(self.TRAFARET, u""" 32 | connection: 33 | kind: tcp 34 | host: localhost 35 | port: http 36 | """), dedent(u"""\ 37 | config.yaml:2: connection.port: value can't be converted to int (where .kind is 'tcp') 38 | """)) 39 | 40 | def test_unix(self): 41 | self.assertEqual(get_err(self.TRAFARET, u""" 42 | connection: 43 | kind: unix 44 | path: /tmp/sock 45 | port: http 46 | """), dedent(u"""\ 47 | config.yaml:2: connection.port: port is not allowed key (where .kind is 'unix') 48 | """)) 49 | 50 | else: 51 | 52 | def test_tcp(self): 53 | self.assertEqual(get_err(self.TRAFARET, u""" 54 | connection: 55 | kind: tcp 56 | host: localhost 57 | port: http 58 | """), dedent(u"""\ 59 | config.yaml:3: connection[0].host: host is not allowed key 60 | config.yaml:3: connection[0].kind: value is not exactly 'unix' 61 | config.yaml:3: connection[0].path: is required 62 | config.yaml:3: connection[0].port: port is not allowed key 63 | config.yaml:3: connection[1].port: value can't be converted to int 64 | """)) 65 | 66 | def test_unix(self): 67 | self.assertEqual(get_err(self.TRAFARET, u""" 68 | connection: 69 | kind: unix 70 | path: /tmp/sock 71 | port: http 72 | """), dedent(u"""\ 73 | config.yaml:3: connection[0].port: port is not allowed key 74 | config.yaml:3: connection[1].host: is required 75 | config.yaml:3: connection[1].kind: value is not exactly 'tcp' 76 | config.yaml:3: connection[1].path: path is not allowed key 77 | config.yaml:3: connection[1].port: value can't be converted to int 78 | """)) 79 | 80 | 81 | class TestHardAlternatives(unittest.TestCase): 82 | maxDiff = 8192 83 | 84 | TRAFARET = T.Dict({ 85 | "connection": T.Or( 86 | T.Dict({ 87 | "path": T.String(), 88 | }), 89 | T.Dict({ 90 | "host": T.String(), 91 | "port": T.Int, 92 | }), 93 | ), 94 | }) 95 | 96 | if BEAUTY_ERROR: 97 | 98 | def test_tcp(self): 99 | self.assertEqual(get_err(self.TRAFARET, u""" 100 | connection: 101 | host: localhost 102 | port: http 103 | """), dedent(u"""\ 104 | config.yaml:3: connection..host: host is not allowed key 105 | -> 'localhost' 106 | config.yaml:3: connection..path: is required 107 | config.yaml:4: connection..port: port is not allowed key 108 | -> 'http' 109 | config.yaml:4: connection..port: value can't be converted to int 110 | -> 'http' 111 | """)) 112 | 113 | def test_unix(self): 114 | self.assertEqual(get_err(self.TRAFARET, u""" 115 | connection: 116 | path: /tmp/sock 117 | port: http 118 | """), dedent(u"""\ 119 | config.yaml:3: connection..host: is required 120 | config.yaml:3: connection..path: path is not allowed key 121 | -> '/tmp/sock' 122 | config.yaml:4: connection..port: port is not allowed key 123 | -> 'http' 124 | config.yaml:4: connection..port: value can't be converted to int 125 | -> 'http' 126 | """)) 127 | 128 | else: 129 | 130 | def test_tcp(self): 131 | self.assertEqual(get_err(self.TRAFARET, u""" 132 | connection: 133 | host: localhost 134 | port: http 135 | """), dedent(u"""\ 136 | config.yaml:3: connection[0].host: host is not allowed key 137 | config.yaml:3: connection[0].path: is required 138 | config.yaml:3: connection[0].port: port is not allowed key 139 | config.yaml:3: connection[1].port: value can't be converted to int 140 | """)) 141 | 142 | def test_unix(self): 143 | self.assertEqual(get_err(self.TRAFARET, u""" 144 | connection: 145 | path: /tmp/sock 146 | port: http 147 | """), dedent(u"""\ 148 | config.yaml:3: connection[0].port: port is not allowed key 149 | config.yaml:3: connection[1].host: is required 150 | config.yaml:3: connection[1].path: path is not allowed key 151 | config.yaml:3: connection[1].port: value can't be converted to int 152 | """)) 153 | 154 | 155 | class TestMappingOr(unittest.TestCase): 156 | 157 | TRAFARET = T.Mapping(T.String, T.Dict({}) | T.Dict({})) 158 | 159 | if BEAUTY_ERROR: 160 | 161 | def test_items(self): 162 | self.assertEqual( 163 | get_err(self.TRAFARET, u"""test: qwe"""), 164 | dedent(u"""\ 165 | config.yaml:1: test.value.: value is not a dict 166 | config.yaml:1: test.value.: value is not a dict 167 | """)) 168 | else: 169 | 170 | def test_items(self): 171 | self.assertEqual( 172 | get_err(self.TRAFARET, u"""test: qwe"""), 173 | dedent(u"""\ 174 | config.yaml:1: test.value[0]: value is not a dict 175 | config.yaml:1: test.value[1]: value is not a dict 176 | """)) 177 | -------------------------------------------------------------------------------- /tests/test_lines.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from textwrap import dedent 3 | 4 | import trafaret as T 5 | from .util import get_err 6 | 7 | 8 | class TestSMTP(unittest.TestCase): 9 | 10 | TRAFARET = T.Dict({ 11 | T.Key('port'): T.Int(), 12 | T.Key('smtp'): T.Dict({ 13 | 'server': T.String(), 14 | 'port': T.Int(), 15 | 'ssl_port': T.Int(), 16 | }), 17 | }) 18 | 19 | def test_bad(self): 20 | self.assertEqual(get_err(self.TRAFARET, u"""\ 21 | smtp: 22 | server: mail.example.org 23 | port: unknown 24 | ssl_port: NaN 25 | port: ??? 26 | """),dedent("""\ 27 | config.yaml:3: smtp.port: value can't be converted to int 28 | -> 'unknown' 29 | config.yaml:4: smtp.ssl_port: value can't be converted to int 30 | -> 'NaN' 31 | config.yaml:5: port: value can't be converted to int 32 | -> '???' 33 | """)) 34 | 35 | 36 | class TestList(unittest.TestCase): 37 | 38 | TRAFARET = T.Dict({ 39 | "hosts": T.List(T.String() & T.Regexp("\w+:\d+")), 40 | }) 41 | 42 | def test_ok(self): 43 | self.assertEqual(get_err(self.TRAFARET, u"""\ 44 | hosts: 45 | - bear:8080 46 | - cat:7070 47 | """), None) 48 | 49 | def test_err(self): 50 | self.assertEqual(get_err(self.TRAFARET, u"""\ 51 | hosts: 52 | - bear:8080 53 | - cat:x 54 | """), 55 | "config.yaml:3: hosts[1]: " 56 | "does not match pattern \\w+:\\d+\n" 57 | ) 58 | 59 | 60 | class TestInvalidYaml(unittest.TestCase): 61 | 62 | TRAFARET = T.Dict() 63 | 64 | def test_star(self): 65 | self.assertIn(get_err(self.TRAFARET, u"""\ 66 | port: 8080 67 | host: localhost 68 | *: 1 69 | """),{ 70 | # message depends on whether we use libyaml (C speedups) or not 71 | dedent( # with C speedups 72 | "config.yaml:3: did not find expected alphabetic or " 73 | "numeric character\n" 74 | "config.yaml:3: while scanning an alias\n" 75 | ), dedent( # without C speedups 76 | "config.yaml:3: expected alphabetic or numeric character, " 77 | "but found ':'\n" 78 | "config.yaml:3: while scanning an alias\n" 79 | )}) 80 | -------------------------------------------------------------------------------- /tests/test_scalar.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from textwrap import dedent 3 | 4 | import trafaret as T 5 | 6 | from .util import get_err 7 | 8 | 9 | class TestScalar(unittest.TestCase): 10 | 11 | TRAFARET = T.Dict({ 12 | T.Key("a_null", optional=True): T.Null, 13 | T.Key("a_bool", optional=True): T.Bool, 14 | T.Key("a_float", optional=True): T.Float, 15 | T.Key("a_int", optional=True): T.Int, 16 | T.Key("a_atom_str", optional=True): T.Atom("hello"), 17 | T.Key("a_atom_list", optional=True): T.Atom(["x", "y"]), 18 | T.Key("a_enum_str", optional=True): T.Enum(["x", "y"]), 19 | T.Key("a_str", optional=True): T.String(max_length=12), 20 | T.Key("a_email", optional=True): T.Email, 21 | T.Key("a_url", optional=True): T.URL, 22 | }) 23 | 24 | def test_null(self): 25 | self.assertEqual(get_err(self.TRAFARET, u""" 26 | a_null: "hello" 27 | """), dedent(u"""\ 28 | config.yaml:2: a_null: value should be None 29 | -> 'hello' 30 | """)) 31 | 32 | def test_bool(self): 33 | self.assertEqual(get_err(self.TRAFARET, u""" 34 | a_bool: "hello" 35 | """), dedent(u"""\ 36 | config.yaml:2: a_bool: value should be True or False 37 | -> 'hello' 38 | """)) 39 | 40 | def test_float(self): 41 | self.assertEqual(get_err(self.TRAFARET, u""" 42 | a_float: "hello" 43 | """), dedent(u"""\ 44 | config.yaml:2: a_float: value can't be converted to float 45 | -> 'hello' 46 | """)) 47 | 48 | def test_int(self): 49 | self.assertEqual(get_err(self.TRAFARET, u""" 50 | a_int: 2.57 51 | """), dedent(u"""\ 52 | config.yaml:2: a_int: value is not int 53 | -> 2.57 54 | """)) 55 | 56 | def test_atom_str(self): 57 | self.assertEqual(get_err(self.TRAFARET, u""" 58 | a_atom_str: "xxx" 59 | """), dedent(u"""\ 60 | config.yaml:2: a_atom_str: value is not exactly 'hello' 61 | -> 'xxx' 62 | """)) 63 | 64 | def test_atom_list(self): 65 | self.assertEqual(get_err(self.TRAFARET, u""" 66 | a_atom_list: "xxx" 67 | """), dedent(u"""\ 68 | config.yaml:2: a_atom_list: value is not exactly '['x', 'y']' 69 | -> 'xxx' 70 | """)) 71 | 72 | def test_enum_str(self): 73 | self.assertEqual(get_err(self.TRAFARET, u""" 74 | a_enum_str: "hello" 75 | """), dedent(u"""\ 76 | config.yaml:2: a_enum_str: value doesn't match any variant 77 | -> 'hello' 78 | """)) 79 | 80 | def test_string(self): 81 | self.assertEqual(get_err(self.TRAFARET, u""" 82 | a_str: 1 83 | """), dedent(u"""\ 84 | config.yaml:2: a_str: value is not a string 85 | -> 1 86 | """)) 87 | 88 | def test_long_string(self): 89 | self.assertEqual(get_err(self.TRAFARET, u""" 90 | a_str: "hello my good friends" 91 | """), dedent(u"""\ 92 | config.yaml:2: a_str: String is longer than 12 characters 93 | -> 'hello my good friends' 94 | """)) 95 | 96 | def test_email(self): 97 | self.assertEqual(get_err(self.TRAFARET, u""" 98 | a_email: "hello" 99 | """), dedent(u"""\ 100 | config.yaml:2: a_email: value is not a valid email address 101 | -> 'hello' 102 | """)) 103 | 104 | def test_url(self): 105 | self.assertEqual(get_err(self.TRAFARET, u""" 106 | a_url: "hello" 107 | """), dedent(u"""\ 108 | config.yaml:2: a_url: value is not URL 109 | -> 'hello' 110 | """)) 111 | -------------------------------------------------------------------------------- /tests/test_structures.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from textwrap import dedent 3 | 4 | import trafaret as T 5 | 6 | from .util import get_err 7 | 8 | 9 | class TestList(unittest.TestCase): 10 | 11 | TRAFARET = T.Dict({ 12 | T.Key("strs", optional=True): T.List(T.String()), 13 | T.Key("ints", optional=True): T.List(T.Int()), 14 | }) 15 | 16 | def test_strings(self): 17 | self.assertEqual(get_err(self.TRAFARET, u""" 18 | strs: [1, 2] 19 | """), dedent(u"""\ 20 | config.yaml:2: strs[0]: value is not a string 21 | config.yaml:2: strs[1]: value is not a string 22 | """)) 23 | 24 | def test_ints(self): 25 | self.assertEqual(get_err(self.TRAFARET, u""" 26 | ints: ["hello", "world"] 27 | """), dedent(u"""\ 28 | config.yaml:2: ints[0]: value can't be converted to int 29 | config.yaml:2: ints[1]: value can't be converted to int 30 | """)) 31 | 32 | 33 | class TestMapping(unittest.TestCase): 34 | 35 | TRAFARET = T.Dict({ 36 | T.Key("items", optional=True): T.Mapping(T.String(), T.String()), 37 | }) 38 | 39 | def test_items(self): 40 | self.assertEqual(get_err(self.TRAFARET, u""" 41 | items: 42 | a: x 43 | b: 1 44 | 3: b 45 | """), dedent(u"""\ 46 | config.yaml:4: items.b.value: value is not a string 47 | config.yaml:5: items[3].key: value is not a string 48 | """)) 49 | 50 | 51 | class TestTuple(unittest.TestCase): 52 | 53 | TRAFARET = T.Dict({ 54 | T.Key("tuple", optional=True): T.Tuple(T.String(), T.Int()), 55 | }) 56 | 57 | def test_items(self): 58 | self.assertEqual(get_err(self.TRAFARET, u""" 59 | tuple: 60 | - "hello" 61 | - "world" 62 | """), dedent(u"""\ 63 | config.yaml:4: tuple[1]: value can't be converted to int 64 | """)) 65 | -------------------------------------------------------------------------------- /tests/test_subst.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from textwrap import dedent 3 | 4 | import trafaret as T 5 | 6 | from .util import get_err, get_ok 7 | 8 | 9 | class TestSubst(unittest.TestCase): 10 | 11 | TRAFARET = T.Dict({ 12 | T.Key("a_int", optional=True): T.Int, 13 | T.Key("a_str", optional=True): T.String(), 14 | }) 15 | 16 | def test_int(self): 17 | self.assertEqual(get_ok(self.TRAFARET, u""" 18 | a_int: ${NUMBER} 19 | """, {'NUMBER': '177'}), {'a_int': 177}) 20 | 21 | def test_int_concat(self): 22 | self.assertEqual(get_ok(self.TRAFARET, u""" 23 | a_int: ${NUMBER}99 24 | """, {'NUMBER': '13'}), {'a_int': 1399}) 25 | 26 | def test_bad_int(self): 27 | self.assertEqual(get_err(self.TRAFARET, u""" 28 | a_int: ${NUMBER} 29 | """, {'NUMBER': '12b'}), dedent(u"""\ 30 | config.yaml:2: a_int: value can't be converted to int 31 | -> '${NUMBER}' 32 | -> variable 'NUMBER' consists of 3 hexadecimal characters 33 | """)) 34 | 35 | 36 | def test_string(self): 37 | self.assertEqual(get_ok(self.TRAFARET, u""" 38 | a_str: http://${HOST}:$PORT/ 39 | """, {'PORT': '8080', 'HOST': 'localhost'}), { 40 | 'a_str': u'http://localhost:8080/', 41 | }) 42 | 43 | def test_no_var(self): 44 | self.assertEqual(get_err(self.TRAFARET, u""" 45 | a_str: http://${HOST}:$PORT/ 46 | """, {'HOST': 'localhost'}), dedent(u"""\ 47 | config.yaml:2: variable 'PORT' not found 48 | -> 'http://${HOST}:$PORT/' 49 | """)) 50 | 51 | def test_no_subst(self): 52 | self.assertEqual(get_ok(self.TRAFARET, u""" 53 | a_str: http://${HOST}:$PORT/ 54 | """, None), {"a_str": "http://${HOST}:$PORT/"}) 55 | -------------------------------------------------------------------------------- /tests/test_tricks.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from collections import OrderedDict 3 | from textwrap import dedent 4 | 5 | import trafaret as T 6 | 7 | from .util import get_err 8 | 9 | 10 | class TestCall(unittest.TestCase): 11 | 12 | TRAFARET = T.Dict({ 13 | T.Key("call_dict", optional=True): 14 | # The following is the ordered dict because we want to obey order 15 | # in the error messages. Otherwise, it could be normal dict as well 16 | T.Call(lambda _: T.DataError({ 17 | "anything": "bad idea", 18 | "bad": "another bad idea", 19 | })), 20 | T.Key("call_str", optional=True): 21 | T.Call(lambda _: T.DataError("some error")), 22 | }) 23 | 24 | def test_call_dict(self): 25 | self.assertEqual(get_err(self.TRAFARET, u""" 26 | call_dict: "hello" 27 | """), dedent(u"""\ 28 | config.yaml:2: call_dict.anything: bad idea 29 | config.yaml:2: call_dict.bad: another bad idea 30 | """)) 31 | 32 | def test_call_str(self): 33 | self.assertEqual(get_err(self.TRAFARET, u""" 34 | call_str: "hello" 35 | """), dedent(u"""\ 36 | config.yaml:2: call_str: some error 37 | -> 'hello' 38 | """)) 39 | 40 | 41 | class TestForward(unittest.TestCase): 42 | 43 | FWD = T.Forward() 44 | TRAFARET = T.Dict({ 45 | T.Key("value", optional=True): FWD, 46 | }) 47 | FWD << T.Int() 48 | 49 | def test_int(self): 50 | self.assertEqual(get_err(self.TRAFARET, u""" 51 | value: "hello" 52 | """), dedent(u"""\ 53 | config.yaml:2: value: value can't be converted to int 54 | -> 'hello' 55 | """)) 56 | -------------------------------------------------------------------------------- /tests/util.py: -------------------------------------------------------------------------------- 1 | from io import StringIO 2 | from textwrap import dedent 3 | from trafaret_config import parse_and_validate, ConfigError 4 | 5 | 6 | def get_err(trafaret, text, vars={}): 7 | data = dedent(text) 8 | try: 9 | config = parse_and_validate(text, trafaret, 10 | filename='config.yaml', vars=vars) 11 | except ConfigError as e: 12 | buf = StringIO() 13 | e.output(buf) 14 | return buf.getvalue() 15 | 16 | def get_ok(trafaret, text, vars={}): 17 | data = dedent(text) 18 | return parse_and_validate(text, trafaret, 19 | filename='config.yaml', vars=vars) 20 | 21 | 22 | -------------------------------------------------------------------------------- /trafaret_config/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '2.0.2' 2 | 3 | from .simple import read_and_validate, parse_and_validate 4 | from .error import ConfigError 5 | -------------------------------------------------------------------------------- /trafaret_config/commandline.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import yaml 3 | import os.path 4 | 5 | from . import simple 6 | from .error import ConfigError 7 | 8 | 9 | def standard_argparse_options(argument_parser, default_config): 10 | argument_parser.add_argument('-c', '--config', default=default_config, 11 | help="Configuration file (default: %(default)r)") 12 | argument_parser.add_argument('--print-config', action='store_true', 13 | help="Print config as it is read after parsing and exit") 14 | argument_parser.add_argument('--print-config-vars', action='store_true', 15 | help="Print variables used in configuration file") 16 | argument_parser.add_argument('-C', '--check-config', action='store_true', 17 | help="Check configuration and exit") 18 | 19 | 20 | def config_from_options(options, trafaret, vars=os.environ): 21 | 22 | if getattr(options, 'print_config_vars'): 23 | vars = simple.read_and_get_vars(options.config, trafaret, vars=vars) 24 | for name in vars: 25 | print(name) 26 | sys.exit(0) 27 | 28 | try: 29 | config = simple.read_and_validate(options.config, trafaret, vars=vars) 30 | except ConfigError as e: 31 | e.output() 32 | sys.exit(1) 33 | 34 | if getattr(options, 'print_config'): 35 | yaml.dump(config, sys.stdout, default_flow_style=False) 36 | sys.exit(0) 37 | 38 | if getattr(options, 'check_config'): 39 | sys.exit(0) 40 | 41 | return config 42 | -------------------------------------------------------------------------------- /trafaret_config/error.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import namedtuple 3 | from collections import defaultdict 4 | import trafaret 5 | 6 | 7 | MAX = float('inf') 8 | try: 9 | SCALAR_TYPES = (str, unicode, int, float) 10 | except NameError: 11 | SCALAR_TYPES = (str, int, float) 12 | 13 | 14 | class ErrorLine(object): 15 | __slots__ = ('start_mark', 'end_mark', 'path', 'message', 'value') 16 | 17 | def __init__(self, marks, path, message, value=None): 18 | if marks: 19 | self.start_mark, self.end_mark = marks 20 | else: 21 | self.start_mark = None 22 | self.end_mark = None 23 | self.path = path 24 | self.message = message 25 | self.value = value 26 | 27 | def __str__(self): 28 | if self.start_mark: 29 | if self.path: 30 | return '{}:{}: {}: {}'.format( 31 | self.start_mark.name, self.start_mark.line+1, 32 | self.path, self.message) 33 | else: 34 | return '{}:{}: {}'.format( 35 | self.start_mark.name, self.start_mark.line+1, 36 | self.message) 37 | else: 38 | if self.path: 39 | return '{}: {}'.format(self.path, self.message) 40 | else: 41 | return 'CONFIG ERROR: {}'.format(self.message) 42 | 43 | def hint(self): 44 | value = self.value 45 | if value is None: 46 | return 47 | if isinstance(value, SCALAR_TYPES): 48 | return [repr(value).lstrip('u')] 49 | if hasattr(value, '_trafaret_config_hint'): 50 | return value._trafaret_config_hint() 51 | 52 | 53 | def _is_simple_or(traf, data): 54 | """Simple or is when all subtrafarets are dicts and they are distinguished 55 | by a single key which is atom and all it's atom values are distinct 56 | """ 57 | intersect = None 58 | dic = defaultdict(list) 59 | for child in traf.trafarets: 60 | if not isinstance(child, trafaret.Dict): 61 | return None, None, None 62 | if intersect is None: 63 | intersect = set(key.name for key in child.keys) 64 | else: 65 | intersect.intersection_update(key.name for key in child.keys) 66 | for key in child.keys: 67 | if key.name in intersect: 68 | dic[key.name].append(key.trafaret) 69 | if not intersect: 70 | return None, None, None 71 | key = next(iter(intersect)) 72 | num_alters = len(traf.trafarets) 73 | for key in intersect: 74 | if not key in data: 75 | # this might somehow be tweaked to shorten alternatives too 76 | continue 77 | all_atoms = all(isinstance(t, trafaret.Atom) for t in dic[key]) 78 | if all_atoms: 79 | values = [t.value for t in dic[key]] 80 | if len(set(values)) == num_alters: 81 | return key, data[key], values.index(data[key]) 82 | return None, None, None 83 | 84 | def _convert(parent_marks, prefix, err, data): 85 | cur_trafaret = getattr(err, 'trafaret', None) 86 | is_alter = isinstance(cur_trafaret, trafaret.Or) 87 | if is_alter: 88 | key, value, index = _is_simple_or(cur_trafaret, data) 89 | if key: 90 | suberror = err.error[index] 91 | for e in _convert(parent_marks, prefix, suberror, data.get(key)): 92 | yield ErrorLine([e.start_mark, e.end_mark], e.path, 93 | '{} (where .{} is {!r})'.format(e.message, key, value)) 94 | return 95 | if isinstance(err.error, dict): 96 | items = err.error.items() 97 | else: 98 | items = [('', err)] 99 | for key, suberror in items: 100 | if is_alter: 101 | kprefix = prefix + '.'.format(key+1) 102 | elif isinstance(key, int): 103 | kprefix = prefix + '[{}]'.format(key) 104 | elif prefix: 105 | kprefix = prefix + '.' + str(key) 106 | else: 107 | kprefix = str(key) 108 | cmarks = getattr(data, 'marks', {}) 109 | marks = (cmarks.get(key) or cmarks.get(str(key)) or 110 | cmarks.get('__self__') or parent_marks) 111 | if isinstance(getattr(suberror, 'error', None), dict): 112 | if not is_alter and isinstance(data, dict): 113 | cur_data = data.get(key) 114 | else: 115 | cur_data = data 116 | for e in _convert(marks, kprefix, suberror, cur_data): 117 | yield e 118 | else: 119 | if isinstance(data, dict): 120 | hint = getattr(data, 'extra', {}).get(str(key), 121 | data.get(str(key))) 122 | else: 123 | hint = None 124 | yield ErrorLine(marks, kprefix, suberror, hint) 125 | 126 | 127 | def _err_sort_key(err): 128 | mark = err.start_mark 129 | if mark: 130 | return mark.name, mark.line, err.path or '' 131 | else: 132 | return 'zzzzzzzzzzzzzzz', MAX, err.path or '' 133 | 134 | 135 | class ConfigError(Exception): 136 | 137 | def __init__(self, list_of_errors): 138 | self.errors = list_of_errors 139 | # Show first error in a context where one line is desired 140 | super(ConfigError, self).__init__(self.errors[0]) 141 | 142 | @classmethod 143 | def from_loader_errors(ConfigError, error_list): 144 | return ConfigError(list(error_list)) 145 | 146 | @classmethod 147 | def from_data_error(ConfigError, err, orig_data, extra=[]): 148 | errs = list(_convert(None, '', err, orig_data)) 149 | errs.extend(extra) 150 | errs.sort(key=_err_sort_key) 151 | return ConfigError(errs) 152 | 153 | @classmethod 154 | def from_scanner_error(ConfigError, err, filename, extra=[]): 155 | return ConfigError([ 156 | ErrorLine([err.problem_mark, err.problem_mark], None, err.problem), 157 | ErrorLine([err.problem_mark, err.problem_mark], None, err.context), 158 | ] + extra) 159 | 160 | def output(self, stream=None): 161 | if stream is None: 162 | stream = sys.stderr 163 | for err in self.errors: 164 | stream.write(str(err) + u'\n') 165 | hint = err.hint() 166 | for line in hint or (): 167 | stream.write(u' -> ' + line + u'\n') 168 | -------------------------------------------------------------------------------- /trafaret_config/simple.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | from weakref import WeakKeyDictionary 4 | 5 | from io import StringIO 6 | import trafaret as _trafaret 7 | from yaml import load, dump, ScalarNode 8 | from yaml.scanner import ScannerError 9 | try: 10 | from yaml import CSafeLoader as SafeLoader 11 | except ImportError: 12 | from yaml import SafeLoader 13 | 14 | from .error import ConfigError, ErrorLine 15 | 16 | 17 | VARS_REGEX = re.compile(r'\$(\w+)|\$\{([^}]+)\}') 18 | 19 | try: 20 | STR_TYPES = (str, unicode) 21 | UNICODE_TYPE = unicode 22 | except NameError: 23 | STR_TYPES = str 24 | UNICODE_TYPE = str 25 | 26 | 27 | class ConfigDict(dict): 28 | __slots__ = ('marks', 'extra') 29 | 30 | def __init__(self, data, marks, extra): 31 | dict.__init__(self, data) 32 | self.marks = marks 33 | self.extra = extra 34 | 35 | 36 | class ConfigList(list): 37 | __slots__ = ('marks', 'extra') 38 | 39 | def __init__(self, data, marks, extra): 40 | list.__init__(self, data) 41 | self.marks = marks 42 | self.extra = extra 43 | 44 | 45 | class SubstInfo(object): 46 | 47 | def __init__(self, original, vars): 48 | self.original = original 49 | self.vars = vars 50 | 51 | def _trafaret_config_hint(self): 52 | return ( 53 | [repr(self.original).lstrip('u')] + 54 | [_format_var(k, v) for k, v in self.vars.items()] 55 | ) 56 | 57 | 58 | def _format_var(key, value): 59 | if value is None: 60 | return 'variable {} is undefined'.format(repr(key).lstrip('u')) 61 | else: 62 | value = UNICODE_TYPE(value) 63 | if value.isdecimal(): 64 | kind = 'numeric' 65 | elif value.isalnum(): 66 | if all(c.isdecimal() or 97 <= ord(c) <= 102 67 | for c in value.lower()): 68 | kind = 'hexadecimal' 69 | elif value.isalpha(): 70 | kind = 'letter' 71 | else: 72 | kind = 'alphanumeric' 73 | else: 74 | kind = 'various' 75 | return 'variable {} consists of {} {} characters'.format( 76 | repr(key).lstrip('u'), len(value), kind) 77 | 78 | 79 | class ConfigLoader(SafeLoader): 80 | 81 | def __init__(self, stream, expand_vars, errors): 82 | SafeLoader.__init__(self, stream) 83 | self.__vars = expand_vars 84 | self.__errors = errors 85 | self.__used_vars = set() 86 | 87 | def construct_yaml_map(self, node): 88 | data = ConfigDict({}, {}, {}) 89 | yield data 90 | data.update(self.construct_mapping(node)) 91 | marks = {'__self__': [node.start_mark, node.end_mark]} 92 | for (key, value) in node.value: 93 | if isinstance(key, ScalarNode): 94 | key_str = self.construct_scalar(key) 95 | marks[key_str] = cur_marks = [key.start_mark, value.end_mark] 96 | if self.__vars is not None and isinstance(value, ScalarNode): 97 | val = self.construct_scalar(value) 98 | if isinstance(val, STR_TYPES): 99 | nval, ext = self.__expand_vars(val, cur_marks) 100 | if nval != val: 101 | data[key_str] = nval 102 | data.extra[key_str] = ext 103 | data.marks = marks 104 | 105 | def construct_yaml_seq(self, node): 106 | data = ConfigList([], {}, {}) 107 | yield data 108 | data.extend(self.construct_sequence(node)) 109 | marks = {'__self__': [node.start_mark, node.end_mark]} 110 | for idx, value in enumerate(node.value): 111 | marks[idx] = cur_marks = [value.start_mark, value.end_mark] 112 | if self.__vars is not None and isinstance(value, ScalarNode): 113 | val = data[idx] 114 | if isinstance(val, str): 115 | data[idx], ext = self.__expand_vars(val, cur_marks) 116 | data.extra[idx] = ext 117 | data.marks = marks 118 | 119 | def __expand_vars(self, value, marks): 120 | replaced = {} 121 | def replacer(match): 122 | key = match.group(1) 123 | if not key: 124 | key = match.group(2) 125 | replaced[key] = self.__vars.get(key) 126 | self.__used_vars.add(key) 127 | try: 128 | return self.__vars[key] 129 | except KeyError: 130 | self.__errors.append(ErrorLine( 131 | marks, None, 132 | 'variable {} not found'.format(repr(key).lstrip('u')), 133 | value)) 134 | return match.group(0) 135 | return VARS_REGEX.sub(replacer, value), SubstInfo(value, replaced) 136 | 137 | def get_expanded_vars(self): 138 | return set(self.__used_vars) 139 | 140 | 141 | ConfigLoader.add_constructor( 142 | 'tag:yaml.org,2002:map', 143 | ConfigLoader.construct_yaml_map) 144 | 145 | ConfigLoader.add_constructor( 146 | 'tag:yaml.org,2002:seq', 147 | ConfigLoader.construct_yaml_seq) 148 | 149 | 150 | def read_and_validate(filename, trafaret, vars=os.environ): 151 | with open(filename) as input: 152 | return _validate_input(input, trafaret, filename=filename, vars=vars) 153 | 154 | 155 | def read_and_get_vars(filename, trafaret, vars=os.environ): 156 | with open(filename) as input: 157 | errors = [] 158 | loader = ConfigLoader(input, vars, errors) 159 | try: 160 | loader.get_single_data() 161 | except ScannerError as e: 162 | raise ConfigError.from_scanner_error(e, filename, errors) 163 | finally: 164 | loader.dispose() 165 | return loader.get_expanded_vars() 166 | 167 | 168 | def parse_and_validate(string, trafaret, 169 | filename='', vars=os.environ): 170 | errors = [] 171 | input = StringIO(string) 172 | input.name = filename 173 | return _validate_input(input, trafaret, filename=filename, vars=vars) 174 | 175 | 176 | def _validate_input(input, trafaret, filename, vars): 177 | errors = [] 178 | loader = ConfigLoader(input, vars, errors) 179 | try: 180 | data = loader.get_single_data() 181 | except ScannerError as e: 182 | raise ConfigError.from_scanner_error(e, filename, errors) 183 | finally: 184 | loader.dispose() 185 | 186 | try: 187 | result = trafaret.check(data) 188 | except _trafaret.DataError as e: 189 | raise ConfigError.from_data_error(e, data, errors) 190 | 191 | if errors: 192 | raise ConfigError.from_loader_errors(errors) 193 | 194 | return result 195 | -------------------------------------------------------------------------------- /vagga.yaml: -------------------------------------------------------------------------------- 1 | _trafaret: &trafaret trafaret==1.2.0 2 | containers: 3 | 4 | py3: 5 | setup: 6 | - !Alpine v3.8 7 | - !Install [ca-certificates] 8 | - !Py3Install [pip, *trafaret] 9 | - !Sh "pip install -e ." 10 | 11 | py2: 12 | setup: 13 | - !Alpine v3.8 14 | - !Py2Install [pip, setuptools, *trafaret] 15 | - !Sh "pip install -e ." 16 | 17 | py3_c: 18 | setup: 19 | - !Alpine v3.8 20 | - !BuildDeps [build-base, yaml-dev] 21 | - !Install [ca-certificates, yaml] 22 | - !Py3Install [pip, *trafaret] 23 | - !Sh "pip install -e ." 24 | 25 | py2_c: 26 | setup: 27 | - !Alpine v3.8 28 | - !BuildDeps [build-base, yaml-dev] 29 | - !Install [ca-certificates, yaml] 30 | - !Py2Install [pip, setuptools, *trafaret] 31 | - !Sh "pip install -e ." 32 | 33 | doc: 34 | setup: 35 | - !Alpine v3.7 36 | - !Install [alpine-base, py-sphinx, make] 37 | - &bulk !Tar 38 | url: "https://github.com/tailhook/bulk/releases/download/v0.4.11/bulk-v0.4.11.tar.gz" 39 | sha256: b718bb8448e726690c94d98d004bf7575f7a429106ec26ad3faf11e0fd9a7978 40 | path: / 41 | 42 | commands: 43 | 44 | test: !Command 45 | description: Run all the tests 46 | container: py3 47 | prerequisites: [test-py2, test-py2c, test-py3, test-py3c] 48 | run: [echo, 'ok'] 49 | 50 | test-py2c: !Command 51 | description: Run tests for py2 with C speedups 52 | container: py2_c 53 | run: [python2, -m, unittest, discover] 54 | 55 | test-py3c: !Command 56 | description: Run tests for py3 with C speedups 57 | container: py3_c 58 | run: [python3, -m, unittest, discover] 59 | 60 | test-py2: !Command 61 | description: Run tests for py2 (without C speedups) 62 | container: py2 63 | run: [python2, -m, unittest, discover] 64 | 65 | test-py3: !Command 66 | description: Run tests for py3 (without C speedups) 67 | container: py3 68 | run: [python3, -m, unittest, discover] 69 | 70 | example: !Command 71 | description: Run the only available example so far 72 | container: py3 73 | run: [python3, example.py] 74 | 75 | doc: !Command 76 | description: Build documentation 77 | container: doc 78 | run: [make, html] 79 | work-dir: doc 80 | epilog: | 81 | -------------------------------------------------------- 82 | xdg-open doc/_build/html/index.html 83 | 84 | bulk: !Command 85 | description: Run arbitrary bulk command (maintains version number) 86 | container: doc 87 | run: [bulk] 88 | --------------------------------------------------------------------------------