pax_global_header00006660000000000000000000000064147051005310014506gustar00rootroot0000000000000052 comment=361e779d394548877f6b18fd2660c57bd61deed5 hiyapyco-release-0.7.0/000077500000000000000000000000001470510053100147555ustar00rootroot00000000000000hiyapyco-release-0.7.0/.github/000077500000000000000000000000001470510053100163155ustar00rootroot00000000000000hiyapyco-release-0.7.0/.github/dependabot.yml000066400000000000000000000004061470510053100211450ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "pip" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "weekly" pull-request-branch-name: separator: "-" reviewers: - "zerwes" hiyapyco-release-0.7.0/.github/workflows/000077500000000000000000000000001470510053100203525ustar00rootroot00000000000000hiyapyco-release-0.7.0/.github/workflows/pylint.yml000066400000000000000000000010511470510053100224110ustar00rootroot00000000000000name: Pylint on: pull_request: push: schedule: # first of each month - cron: '0 0 1 * *' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip pip install pylint PyYAML Jinja2 - name: Install make run: sudo apt-get install make - name: Analysing the code with pylint run: make pylint hiyapyco-release-0.7.0/.github/workflows/test.yml000066400000000000000000000022401470510053100220520ustar00rootroot00000000000000name: Test on: pull_request: push: schedule: # first of each month - cron: '0 0 1 * *' jobs: build: runs-on: ubuntu-latest strategy: matrix: distro: - debian11 - debian12 python-version: - '3.9' - '3.11' steps: - name: checkout uses: actions/checkout@v2 - name: Set up python uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies for ${{ matrix.python-version }} run: | sudo pip3 install pylint PyYAML Jinja2 sudo pip3 install -U setuptools wheel ujson pip virtualenv - name: Install make run: sudo apt-get install make - name: test install with virtualenv and run some tests run: PYVERSIONS=python${{ matrix.python-version }} make testinstallvirtualenv - name: install build deps run: | sudo apt-get update sudo apt install python3-all python3-virtualenv dh-python debhelper lintian python3-restructuredtext-lint - name: test readme run: make testreadme - name: test building deb package run: make debunsigned hiyapyco-release-0.7.0/.gitignore000066400000000000000000000001751470510053100167500ustar00rootroot00000000000000*.pyc *~ *.swp # PyCharm .idea # vscode .vscode build HiYaPyCo.egg-info dist deb_dist hiyapyco_0.1.0-1_amd64.build release hiyapyco-release-0.7.0/LICENSE000066400000000000000000001045051470510053100157670ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . hiyapyco-release-0.7.0/MANIFEST.in000066400000000000000000000000441470510053100165110ustar00rootroot00000000000000include README.rst include LICENSE hiyapyco-release-0.7.0/Makefile000066400000000000000000000221161470510053100164170ustar00rootroot00000000000000SHELL = /bin/bash PYVERSIONS ?= $(shell py3versions -i) PYVERSIONSPATHS = $(shell for PV in $(PYVERSIONS); do which $$PV; done) TESTLOGLEVEL ?= WARN .PHONY: test examples testinstall all PYTHONPATH=$(shell pwd) export PYTHONPATH HIYAPYCOVERSION=$(shell PYTHONPATH=$(PYTHONPATH)/hiyapyco:$(PYTHONPATH) python -c 'from version import VERSION; print(VERSION)') export GPGKEY=C9B1F13E67CAB37AE6D132134C2B4A1677DE7FB4 # FIXME: why this hack! w/ -p DPKGBUILDPKGVERSION = $(shell dpkg-buildpackage --version | sed '1!d;s/^.* //g;s/\.$//g') DPKGBUILDPKGSIGNARG = $(shell dpkg --compare-versions $DPKGBUILDPKGVERSION lt 1.17.26 && echo "-p'gpg --use-agent'") pypiupload: PYPIREPO := pypi pypiupload: PYPIREPOURL := https://pypi.python.org/pypi/HiYaPyCo pypiuploadtest: PYPIREPO := pypitest pypiuploadtest: PYPIREPOURL := https://test.pypi.org/project/HiYaPyCo/ quicktest: pylint test examples # FIXME: testinstallvirtualenv fails due to jinja2 2.8 error w/ python3.2 but works w/ python3.4 ... WTF alltest: clean quicktest testreadme testinstall testinstallvirtualenv @echo "$@ passed" printversions: @echo -e "HIYAPYCOVERSION:\t$(HIYAPYCOVERSION)" @echo -e "PYVERSIONS:\t\t$(PYVERSIONS)" @echo -e "PYVERSIONSPATHS:\t$(PYVERSIONSPATHS)" pylint: pylint --disable=missing-module-docstring,unused-import,consider-using-with,unspecified-encoding,consider-using-f-string setup.py @# FIXME: logging-not-lazy global-statement invalid-name @# py3 only: raise-missing-from pylint --class-naming-style=any --disable=fixme,pointless-string-statement,missing-module-docstring,unnecessary-pass,logging-not-lazy,global-statement,invalid-name,raise-missing-from,consider-merging-isinstance,too-many-nested-blocks,consider-using-f-string,deprecated-module hiyapyco/__init__.py testreadme: # requires python3-restructuredtext-lint rst-lint README.rst test: @RET=0; \ for p in $(PYVERSIONS); do \ echo "python version $$p"; \ for t in test/test_*.py; do \ $$p -t $$t -l $(TESTLOGLEVEL); \ RET=$$?; \ if [ $$RET -gt 0 ]; then break 2; fi; \ done; \ echo ""; \ done; \ exit $$RET examples: @RET=0; \ for p in $(PYVERSIONS); do \ echo "python version $$p"; \ for t in examples/*.py; do \ [ "$$t" = "examples/hiyapyco_example.py" ] && continue; \ [ "$$t" = "examples/issue73compareOrderedDict.py" ] && continue; \ echo "$$p -t $$t ..."; \ $$p -t $$t > /dev/null 2>&1; \ RET=$$?; \ if [ $$RET -gt 0 ]; then $$p -t $$t; break 2; fi; \ done; \ echo ""; \ done; \ exit $$RET testinstall: @set -e; \ for p in $(PYVERSIONS); do \ rm -rf /tmp/hiyapyco; \ echo ""; \ echo "$@ w/ python version $$p ..."; \ echo ""; \ $$p setup.py install --root=/tmp/hiyapyco; \ echo ""; \ echo "$@ w/ python version $$p : OK"; \ echo ""; \ done testinstallvirtualenv: @set -e; \ BASETMP=/tmp/hiyapyco; \ rm -rf $$BASETMP; \ for p in $(PYVERSIONSPATHS); do \ VENV=$$BASETMP/$$(basename $$p); \ mkdir -p $$VENV; \ echo "$@ w/ python version $$(basename $$p) in $$VENV ..."; \ virtualenv -p $$p $$VENV; \ source $$VENV/bin/activate; \ which python; \ python --version; \ python setup.py install; \ echo ""; \ echo " ... test install ..."; \ python -c 'import sys; from hiyapyco import __version__ as HIYAPYCOVERSION; print ("hiyapyco %s" % HIYAPYCOVERSION); print (sys.version)'; \ pip install -r test/requirements.txt; \ make test; \ make examples; \ deactivate; \ done clean: distclean distclean: python setup.py clean rm -rf release dist build HiYaPyCo.egg-info find . -type f -name \*.pyc -exec rm -v {} \; sdist: python setup.py sdist @echo "$@ done" wheel: # requires a 'sudo pip install wheel' python setup.py bdist_wheel @echo "$@ done" twinecheckdist: twine check dist/HiYaPyCo-*.tar.gz @echo "$@ done" pypi: sdist wheel twinecheckdist @echo "$@ done" pypiuploadtest: pypi pypiuploaddo pypiupload: pypi pypiuploaddo pypiuploaddo: pypi # set use-agent in ~/.gnupg/gpg.conf to use the agent rm -rf dist/HiYaPyCo-*.egg* twine upload --verbose -s -i $(GPGKEY) -r $(PYPIREPO) dist/* @echo "test the result at: $(PYPIREPOURL)" gpg-agent: @gpg-agent; \ RET=$$?; echo "gpg agent running: $$RET"; \ if [ $$RET -gt 0 ]; then \ gpg-agent; \ echo 'please run eval "eval $$(gpg-agent --daemon)"'; \ exit 1; \ fi gpg-connect-agent 'keyinfo --list' /bye dch-increment: @# use this to increment the deb release number for a existing release @DEBEMAIL=$$(git config --local --get user.email) \ DEBFULLNAME="Klaus Zerwes zero-sys.net" \ dch -i "new debian release" @git diff debian/changelog dch-version: @# use this after updating hiyapyco/version.py @if $$(dpkg --compare-versions $$(dpkg-parsechangelog | sed '/^Version: /!d; s/^Version: \([.0-9]*\).*/\1/g') lt $(HIYAPYCOVERSION)); then \ DEBEMAIL=$$(git config --local --get user.email) \ DEBFULLNAME="Klaus Zerwes zero-sys.net" \ dch -v $(HIYAPYCOVERSION)-1 -D stable "release version $(HIYAPYCOVERSION)"; \ git diff debian/changelog; \ else \ echo "nothing to do"; \ fi debunsigned: rm -rf release/deb/build mkdir -p release/deb/build tar cv -Sp --exclude=dist --exclude=build --exclude='*/.git*' -f - . | ( cd release/deb/build && tar x -Sp -f - ) cd release/deb/build && dpkg-buildpackage -b --no-sign rm -rf release/deb/build lintian release/deb/*.deb deb: gpg-agent rm -rf release/deb/build mkdir -p release/deb/build tar cv -Sp --exclude=dist --exclude=build --exclude='*/.git*' -f - . | ( cd release/deb/build && tar x -Sp -f - ) cd release/deb/build && dpkg-buildpackage -b -k$(GPGKEY) $(DPKGBUILDPKGSIGNARG) gpg --verify release/deb/hiyapyco_*.changes rm -rf release/deb/build lintian release/deb/*.deb debrepo: deb cd release/deb && \ apt-ftparchive packages . > Packages && \ gzip -c Packages > Packages.gz && \ bzip2 -c Packages > Packages.bz2 && \ lzma -c Packages > Packages.lsma echo "Suite: stable testing" >> release/deb/Release echo "Origin: Klaus Zerwes zero-sys.net" >> release/deb/Release echo "Label: hiyapyco" >> release/deb/Release echo "Architectures: all" >> release/deb/Release echo "Description: HiYaPyCo Debian Repository" >> release/deb/Release cd release/deb && apt-ftparchive release . >> Release cd release/deb && \ gpg --clearsign --default-key $(GPGKEY) --use-agent -o InRelease Release && \ gpg -abs --default-key $(GPGKEY) --use-agent -o Release.gpg Release gpg --verify release/deb/Release.gpg release/deb/Release gpg --check-sigs InRelease Release rpm: gpg-agent mkdir -p release/rpm/noarch python setup.py bdist_rpm --binary-only \ --doc-files README.rst --requires python-yaml,python-jinja2 \ -d release/rpm/noarch for f in release/rpm/noarch/*.rpm; do \ echo "rpmsign $f ..."; \ rm -f $$f.sig; \ rpmsign \ -D "%__gpg_sign_cmd %{__gpg} gpg --batch --no-armor --use-agent --no-secmem-warning -u '\%{_gpg_name}' -sbo \%{__signature_filename} \%{__plaintext_filename}" \ -D "%__gpg_check_password_cmd /bin/true" \ --resign --key-id=$(GPGKEY) $$f; \ rpm --checksig --verbose $$f | grep -i $(GPGKEY); \ echo "rpmsign $f done"; \ done rpmrepo: rpm cd release/rpm; \ rm -fv repodata/repomd.xml*; \ createrepo_c . ; \ gpg --default-key $(GPGKEY) --use-agent -a --detach-sign repodata/repomd.xml; \ gpg -a --export $(KEY) > repodata/repomd.xml.key tag: @git pull --rebase --ff-only @if [ -n "$$(git status --porcelain)" ]; then \ echo "uncommited changes"; \ git status --porcelain; \ false; \ fi @if [ -n "$$(git log --branches --source --not --remotes --no-walk --oneline | awk '{print $2}' | grep \"$$(git branch --show-current)\")" ]; then \ echo "unpushed changes"; \ git log --branches --source --not --remotes --no-walk --oneline; \ false; \ fi git tag -s "release-$(HIYAPYCOVERSION)" -m "version $(HIYAPYCOVERSION) released on $$(date -R)" pushtag: git push origin "release-$(HIYAPYCOVERSION)" repo: debrepo rpmrepo upload: uploadrepo pypiupload uploadrepo: repo scp -r release/* repo.zero-sys.net:/srv/www/repo.zero-sys.net/hiyapyco/ testversion: testdebversion testsetupversion testchangelogversion testsetupversion: @if $$(dpkg --compare-versions $$(python setup.py -V) lt $(HIYAPYCOVERSION)); then \ echo "setup.py version must be incremented to HIYAPYCOVERSION $(HIYAPYCOVERSION)"; \ false; \ fi testdebversion: @if $$(dpkg --compare-versions $$(dpkg-parsechangelog | sed '/^Version: /!d; s/^Version: \([.0-9]*\).*/\1/g') lt $(HIYAPYCOVERSION)); then \ echo "debian version must be incremented to HIYAPYCOVERSION $(HIYAPYCOVERSION)"; \ echo "run make dch --distribution stable --newversion $(HIYAPYCOVERSION)"; \ false; \ fi testchangelogversion: @if $$(dpkg --compare-versions $$(sed -e '/^Changelog$$/,+3!d' README.rst | sed '4!d') lt $(HIYAPYCOVERSION)); then \ echo "please add $(HIYAPYCOVERSION) section to the Changelog in README.rst"; \ false; \ fi releasetest: distclean alltest testversion repo pypi @echo "$@ done" @echo "you may like to run $(MAKE) pypiuploadtest after this ..." release: distclean alltest testversion tag upload pushtag @echo "done $@ for version $(HIYAPYCOVERSION)" all: releasetest release @echo "done $@ for version $(HIYAPYCOVERSION)" hiyapyco-release-0.7.0/README.rst000066400000000000000000000267771470510053100164670ustar00rootroot00000000000000.. |pylint| image:: https://github.com/zerwes/hiyapyco/actions/workflows/pylint.yml/badge.svg?branch=main :target: https://github.com/zerwes/hiyapyco/actions/workflows/pylint.yml .. |test| image:: https://github.com/zerwes/hiyapyco/actions/workflows/test.yml/badge.svg :target: https://github.com/zerwes/hiyapyco/actions/workflows/test.yml .. |gpl| image:: https://img.shields.io/badge/License-GPL%20v3-blue.svg :target: http://www.gnu.org/licenses/gpl-3.0 |pylint| |test| |gpl| hiyapyco ======== HiYaPyCo - A Hierarchical Yaml Python Config Description ----------- A simple python lib allowing hierarchical overlay of config files in YAML syntax, offering different merge methods and variable interpolation based on jinja2. The goal was to have something similar to puppets hiera ``merge_behavior: deeper`` for python. Key Features ------------ - hierarchical overlay of multiple YAML files - multiple merge methods for hierarchical YAML files - variable interpolation using jinja2 Requirements ------------ - PyYAML aka. python3-yaml - Jinja2 aka. python3-jinja2 Python Version ~~~~~~~~~~~~~~ HiYaPyCo was designed to run on current major python versions without changes. Tested versions: - 3.9 - 3.11 Usage ----- A simple example: :: import hiyapyco conf = hiyapyco.load('yamlfile1' [,'yamlfile2' [,'yamlfile3' [...]]] [,kwargs]) print(hiyapyco.dump(conf, default_flow_style=False)) real life example: ~~~~~~~~~~~~~~~~~~ ``yaml1.yaml``: :: --- first: first element second: xxx deep: k1: - 1 - 2 ``yaml2.yaml``: :: --- second: again {{ first }} deep: k1: - 4 - 6 k2: - 3 - 6 load ... :: >>> import pprint >>> import hiyapyco >>> conf = hiyapyco.load('yaml1.yaml', 'yaml2.yaml', method=hiyapyco.METHOD_MERGE, interpolate=True, failonmissingfiles=True) >>> pprint.PrettyPrinter(indent=4).pprint(conf) { 'deep': { 'k1': [1, 2, 4, 6], 'k2': [3, 6]}, 'first': u'first element', 'ma': { 'ones': u'12', 'sum': u'22'}, 'second': u'again first element'} real life example using yaml documents as strings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: >>> import hiyapyco >>> y1=""" ... yaml: 1 ... y: ... y1: abc ... y2: xyz ... """ >>> y2=""" ... yaml: 2 ... y: ... y2: def ... y3: XYZ ... """ >>> conf = hiyapyco.load([y1, y2], method=hiyapyco.METHOD_MERGE) >>> print (conf) OrderedDict([('yaml', 2), ('y', OrderedDict([('y1', 'abc'), ('y2', 'def'), ('y3', 'XYZ')]))]) >>> hiyapyco.dump(conf, default_flow_style=True) '{yaml: 2, y: {y1: abc, y2: def, y3: XYZ}}\n' args ~~~~ All ``args`` are handled as *file names* or *yaml documents*. They may be strings or list of strings. kwargs ~~~~~~ - ``method``: bit (one of the listed below): - ``hiyapyco.METHOD_SIMPLE``: replace values (except for lists a simple merge is performed) (default method) - ``hiyapyco.METHOD_MERGE``: perform a deep merge - ``hiyapyco.METHOD_SUBSTITUTE``: perform a merge w/ lists substituted (unsupported) - ``mergelists``: boolean try to merge lists of dict (default: ``True``) - ``none_behavior``: bit (one of the listed below): - ``hiyapyco.NONE_BEHAVIOR_DEFAULT``: attempt to merge the value with ``None`` and fail if this is not possible (default method) - ``hiyapyco.NONE_BEHAVIOR_OVERRIDE``: ``None`` always overrides any other value. - ``interpolate``: boolean : perform interpolation after the merge (default: ``False``) - ``castinterpolated``: boolean : try to perform a *best possible match* cast for interpolated strings (default: ``False``) - ``usedefaultyamlloader``: boolean : force the usage of the default *PyYAML* loader/dumper instead of *HiYaPyCo*\ s implementation of a OrderedDict loader/dumper (see: Ordered Dict Yaml Loader / Dumper aka. ODYLDo) (default: ``False``) - ``dereferenceyamlanchors``: boolean : dereference yaml anchors and use a copy (default: ``True``) - ``encoding``: string : encoding used to read yaml files (default: ``utf-8``) - ``failonmissingfiles``: boolean : fail if a supplied YAML file can not be found (default: ``True``) - ``loglevel``: int : loglevel for the hiyapyco logger; should be one of the valid levels from ``logging``: 'WARN', 'ERROR', 'DEBUG', 'I NFO', 'WARNING', 'CRITICAL', 'NOTSET' (default: default of ``logging``) - ``loglevelmissingfiles``: int : one of the valid levels from ``logging``: 'WARN', 'ERROR', 'DEBUG', 'INFO', 'WARNING', 'CRITICAL', 'NOTSET' (default: ``logging.ERROR`` if ``failonmissingfiles = True``, else ``logging.WARN``) - ``mergeoverride``: optional function to customize merge for primitive values (see `PR #76 `_.) - ``loader_callback``: optional custom callback function to load yaml files. The callback function shall behave like ``yaml.load_all`` from PyYAML, taking a IO stream as input and returning a list of objects. Using this method, for example `ruamel `_ can be used instead of PyYAML etc. interpolation ~~~~~~~~~~~~~ For using interpolation, I strongly recomend *not* to use the default PyYAML loader, as it sorts the dict entrys alphabetically, a fact that may break interpolation in some cases (see ``test/odict.yaml`` and ``test/test_odict.py`` for an example). See Ordered Dict Yaml Loader / Dumper aka. ODYLDo default ^^^^^^^ The default jinja2.Environment for the interpolation is :: hiyapyco.jinja2env = Environment(undefined=Undefined) This means that undefined vars will be ignored and replaced with a empty string. change the jinja2 Environment ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you like to change the jinja2 Environment used for the interpolation, set ``hiyapyco.jinja2env`` **before** calling ``hiyapyco.load``! use jinja2 DebugUndefined ^^^^^^^^^^^^^^^^^^^^^^^^^ If you like to keep the undefined var as string but raise no error, use :: from jinja2 import Environment, Undefined, DebugUndefined, StrictUndefined hiyapyco.jinja2env = Environment(undefined=DebugUndefined) use jinja2 StrictUndefined ^^^^^^^^^^^^^^^^^^^^^^^^^^ If you like to raise a error on undefined vars, use :: from jinja2 import Environment, Undefined, DebugUndefined, StrictUndefined hiyapyco.jinja2env = Environment(undefined=StrictUndefined) This will raise a ``hiyapyco.HiYaPyCoImplementationException`` wrapped arround the ``jinja2.UndefinedError`` pointing at the string causing the error. more informations ^^^^^^^^^^^^^^^^^ See: `jinja2.Environment `_ cast interpolated strings ~~~~~~~~~~~~~~~~~~~~~~~~~ As you must use interpolation as strings (PyYAML will weep if you try to start a value with ``{{``), you can set ``castinterpolated`` to *True* in order to try to get a ``best match`` cast for the interpolated values. **The ``best match`` cast is currently only a q&d implementation and may not give you the expected results!** Ordered Dict Yaml Loader / Dumper aka. ODYLDo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is a simple implementation of a PyYAML loader / dumper using ``OrderedDict`` from collections. **Because chaos is fun but order matters on loading dicts from a yaml file.** Install ------- From Source ~~~~~~~~~~~ GitHub ^^^^^^ `https://github.com/zerwes/hiyapyco `_ :: git clone https://github.com/zerwes/hiyapyco cd hiyapyco sudo python setup.py install PyPi ^^^^ Download the latest or desired version of the source package from `https://pypi.python.org/pypi/HiYaPyCo `_. Unpack the archive and install by executing: :: sudo python setup.py install pip ~~~ Install the latest wheel package using: :: pip install HiYaPyCo debian packages ~~~~~~~~~~~~~~~ install the latest debian packages from http://repo.zero-sys.net/hiyapyco:: # create the sources list file: sudo echo "deb http://repo.zero-sys.net/hiyapyco/deb ./" > /etc/apt/sources.list.d/hiyapyco.list # import the key: gpg --keyserver keys.gnupg.net --recv-key 77DE7FB4 # or use: wget https://repo.zero-sys.net/77DE7FB4.asc -O - | gpg --import - # apt tasks: gpg --armor --export 77DE7FB4 | sudo tee /etc/apt/trusted.gpg.d/hiyapyco.asc sudo apt-get update sudo apt-get install python3-hiyapyco a ansible playbook exists: https://github.com/zerwes/ansible-role-hiyapyco rpm packages ~~~~~~~~~~~~ use `http://repo.zero-sys.net/hiyapyco/rpm `_ as URL for the yum repo and `https://repo.zero-sys.net/77DE7FB4.asc `_ as the URL for the key. Arch Linux ~~~~~~~~~~ An `AUR package `_ is available (provided by `Pete Crighton `_ and not always up to date). License ------- Copyright |copy| 2014 - 2024 Klaus Zerwes `zero-sys.net `_ .. |copy| unicode:: 0xA9 .. copyright sign This package is free software. This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE version 3 or later, as published by the Free Software Foundation. See `https://www.gnu.org/licenses/gpl.html `_ Changelog --------- 0.7.0 ~~~~~~ MERGED: allow custom yaml loaders as callback functions by @grst (PR #77) MERGED: implement none-behavior strategies by @grst (PR #78) MERGED: update markupsafe requirement from <3 to <4 (#80) IMPROVED: added some example how to use ruamel 0.6.1 ~~~~~~ MERGED: #76 Override mechanism for primitive value merge by malachib IMPROVED: added link to ansible playbook 0.6.0 ~~~~~~ FIXED: #69 (weird merge behavior with anchors) MERGED: #71 (dereference anchors) 0.5.6 ~~~~~~ MERGED: #70 by itachi-cracker FIXED: #61 (removed deprecated distutils) 0.5.5 ~~~~~~ FIXED: #67 cosmetic changes 0.5.4 ~~~~~~ FIXED: #60 recursive calls to _substmerge IMPROVED: testing and python support (3.11) 0.5.1 ~~~~~~ MERGED: #52 by ryanfaircloth 0.5.0 ~~~~~~ MERGED: #41 Jinja2 dependency increased to include Jinja2 3.x.x REMOVED: Support for Python 2 0.4.16 ~~~~~~ MERGED: #37 alex-ber 0.4.15 ~~~~~~ MERGED: #30 lesiak:issue-30-utf MERGED: #28 lesiak:issue-28 0.4.14 ~~~~~~ FIXED: issue #33 MERGED: issue #32 0.4.13 ~~~~~~ IMPLEMENTED: [issue #27] support multiple yaml documents in one file 0.4.12 ~~~~~~ FIXED: logging by Regev Golan 0.4.11 ~~~~~~ IMPLEMENTED: mergelists (see issue #25) 0.4.10 ~~~~~~ FIXED: issue #24 repo signing 0.4.9 ~~~~~ FIXED: issue #23 loglevelonmissingfiles 0.4.8 ~~~~~ Fixed pypi doc 0.4.7 ~~~~~ Reverted: logger settings to initial state Improved: dump Merged: - flatten mapping from Chris Petersen geek@ex-nerd.com - arch linux package info from Peter Crighton git@petercrighton.de 0.4.6 ~~~~~ MERGED: fixes from mmariani 0.4.5 ~~~~~ FIXED: issues #9 and #11 0.4.4 ~~~~~ deb packages: - removed support for python 2.6 - include examples as doc 0.4.3 ~~~~~ FIXED: issue #6 *import of hiyapyco **version** in setup.py causes pip install failures* 0.4.2 ~~~~~ Changed: moved to GPL Improvements: missing files handling, doc 0.4.1 ~~~~~ Implemented: ``castinterpolated`` 0.4.0 ~~~~~ Implemented: loading yaml docs from string 0.3.2 ~~~~~ Improved tests and bool args checks 0.3.0 / 0.3.1 ~~~~~~~~~~~~~ Implemented a Ordered Dict Yaml Loader 0.2.0 ~~~~~ Fixed unicode handling 0.1.0 / 0.1.1 ~~~~~~~~~~~~~ Initial release hiyapyco-release-0.7.0/debian/000077500000000000000000000000001470510053100161775ustar00rootroot00000000000000hiyapyco-release-0.7.0/debian/changelog000066400000000000000000000123361470510053100200560ustar00rootroot00000000000000hiyapyco (0.7.0-1) stable; urgency=medium * release version 0.7.0 -- Klaus Zerwes zero-sys.net Sun, 20 Oct 2024 05:48:26 +0200 hiyapyco (0.6.1) stable; urgency=medium * release version 0.6.1 -- Klaus Zerwes zero-sys.net Thu, 29 Aug 2024 20:46:06 +0200 hiyapyco (0.6.0-1) stable; urgency=medium * release version 0.6.0 -- Klaus Zerwes zero-sys.net Fri, 24 May 2024 12:38:46 +0200 hiyapyco (0.5.6-1) stable; urgency=medium * release version 0.5.6 -- Klaus Zerwes zero-sys.net Sat, 11 May 2024 06:43:47 +0200 hiyapyco (0.5.5-1) stable; urgency=medium * release version 0.5.5 -- Klaus Zerwes zero-sys.net Sat, 13 Apr 2024 10:41:28 +0200 hiyapyco (0.5.4-1) stable; urgency=medium * release version 0.5.4 -- Klaus Zerwes zero-sys.net Wed, 29 Nov 2023 12:33:15 +0100 hiyapyco (0.5.2-1) stable; urgency=medium * release version 0.5.2 -- Klaus Zerwes zero-sys.net Wed, 29 Nov 2023 08:39:37 +0100 hiyapyco (0.5.1-1) stable; urgency=medium * release version 0.5.1 -- Klaus Zerwes zero-sys.net Wed, 14 Sep 2022 20:28:17 +0200 hiyapyco (0.5.0-1) stable; urgency=medium * release version 0.5.0 -- Klaus Zerwes zero-sys.net Thu, 05 May 2022 06:38:08 +0200 hiyapyco (0.4.16-1) stable; urgency=medium * release version 0.4.16 -- Klaus Zerwes zero-sys.net Tue, 10 Mar 2020 09:46:37 +0100 hiyapyco (0.4.15-1) stable; urgency=medium * release version 0.4.15 -- Klaus Zerwes zero-sys.net Mon, 13 Jan 2020 20:50:17 +0100 hiyapyco (0.4.14-1) stable; urgency=medium * release version 0.4.14 -- Klaus Zerwes zero-sys.net Mon, 25 Mar 2019 23:41:32 +0100 hiyapyco (0.4.13) stable; urgency=medium * support multiple yaml documents in one file -- zerwes Fri, 14 Dec 2018 06:49:59 +0100 hiyapyco (0.4.12-1) stable; urgency=medium * release version 0.4.12 -- Klaus Zerwes zero-sys.net Fri, 05 Oct 2018 22:15:56 +0200 hiyapyco (0.4.11-1) stable; urgency=medium * release version 0.4.11 -- Klaus Zerwes zero-sys.net Thu, 06 Jul 2017 23:48:59 +0200 hiyapyco (0.4.10-1) stable; urgency=medium * release version 0.4.10 -- Klaus Zerwes zero-sys.net Tue, 16 May 2017 22:37:59 +0200 hiyapyco (0.4.9-1) stable; urgency=medium * release version 0.4.9 -- Klaus Zerwes zero-sys.net Sun, 14 May 2017 22:15:58 +0200 hiyapyco (0.4.8-1) stable; urgency=medium * release version 0.4.8 -- Klaus Zerwes zero-sys.net Sat, 18 Jun 2016 23:52:40 +0200 hiyapyco (0.4.7-1) stable; urgency=medium * release version 0.4.7 -- Klaus Zerwes zero-sys.net Tue, 31 May 2016 22:52:49 +0200 hiyapyco (0.4.6-1) stable; urgency=low * release version 0.4.6 -- Klaus Zerwes zero-sys.net Wed, 20 Jan 2016 13:38:29 +0100 hiyapyco (0.4.5-1) stable; urgency=low * release version 0.4.5 -- Klaus Zerwes zero-sys.net Thu, 14 Jan 2016 15:50:01 +0100 hiyapyco (0.4.4-1) stable; urgency=low * release version 0.4.4 -- Klaus Zerwes zero-sys.net Fri, 04 Sep 2015 10:02:04 +0200 hiyapyco (0.4.3-1) stable; urgency=low * release version 0.4.3 -- Klaus Zerwes zero-sys.net Thu, 03 Sep 2015 14:56:14 +0200 hiyapyco (0.4.2-1) stable; urgency=low * release version 0.4.2 -- Klaus Zerwes zero-sys.net Wed, 12 Aug 2015 12:29:25 +0200 hiyapyco (0.4.1-1) stable; urgency=low * release version 0.4.1 -- Klaus Zerwes zero-sys.net Wed, 15 Jul 2015 15:52:54 +0200 hiyapyco (0.4.0-1) stable; urgency=low * release version 0.4.0 -- Klaus Zerwes zero-sys.net Mon, 22 Dec 2014 22:58:34 +0100 hiyapyco (0.3.2-1) stable; urgency=low * release version 0.3.2 -- Klaus Zerwes zero-sys.net Sat, 20 Dec 2014 23:00:56 +0100 hiyapyco (0.3.1-1) stable; urgency=low * release version 0.3.1 -- Klaus Zerwes zero-sys.net Tue, 25 Nov 2014 10:47:14 +0100 hiyapyco (0.3.0-1) stable; urgency=low * release version 0.3.0 -- Klaus Zerwes zero-sys.net Mon, 24 Nov 2014 17:09:40 +0100 hiyapyco (0.2.0-1) stable; urgency=low * release version 0.2.0 -- Klaus Zerwes zero-sys.net Thu, 20 Nov 2014 19:48:18 +0100 hiyapyco (0.1.1-1) stable; urgency=low * release version 0.1.1 -- Klaus Zerwes zero-sys.net Wed, 19 Nov 2014 17:58:26 +0100 hiyapyco (0.1.0-1) stable; urgency=low * initial releae -- Klaus Zerwes zero-sys.net Mon, 17 Nov 2014 23:38:33 +0100 hiyapyco-release-0.7.0/debian/compat000066400000000000000000000000031470510053100173760ustar00rootroot0000000000000011 hiyapyco-release-0.7.0/debian/control000066400000000000000000000014761470510053100176120ustar00rootroot00000000000000Source: hiyapyco Maintainer: Klaus Zerwes zero-sys.net Section: python Priority: optional Build-Depends: python3-setuptools, python3-all (>= 3.2.3-6), python3-setuptools, python3-yaml, python3-jinja2 , dh-python, debhelper (>= 11) Standards-Version: 4.6.2 X-Python3-Version: >= 3.2 Vcs-Git: https://github.com/zerwes/hiyapyco/ Vcs-Browser: https://github.com/zerwes/hiyapyco Rules-Requires-Root: no Package: python3-hiyapyco Architecture: all Depends: ${misc:Depends}, ${python3:Depends} Description: Hierarchical YAML Python Config A simple python lib allowing hierarchical overlay of config files in YAML syntax, offering different merge methods and variable interpolation based on jinja2. hiyapyco-release-0.7.0/debian/copyright000066400000000000000000000022051470510053100201310ustar00rootroot00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Source: https://github.com/zerwes/hiyapyco Upstream-Name: HiYaPyCo Files: * Copyright: 2014 - 2024 Klaus Zerwes zero-sys.net License: GPL-3.0+ Files: debian/* Copyright: 2014 - 2024 Klaus Zerwes zero-sys.net 2022 Updates by Steffen Moeller License: GPL-3.0+ License: GPL-3.0+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. . This package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. . You should have received a copy of the GNU General Public License along with this program. If not, see . Comment: On Debian systems, the complete text of the GNU General Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". hiyapyco-release-0.7.0/debian/docs000066400000000000000000000000241470510053100170460ustar00rootroot00000000000000README.rst examples hiyapyco-release-0.7.0/debian/python3-hiyapyco.lintian-overrides000066400000000000000000000000631470510053100250050ustar00rootroot00000000000000python3-hiyapyco: new-package-should-close-itp-bug hiyapyco-release-0.7.0/debian/rules000077500000000000000000000002121470510053100172520ustar00rootroot00000000000000#!/usr/bin/make -f %: dh $@ --with python3 --buildsystem=pybuild override_dh_auto_clean: rm -rf HiYaPyCo.egg-info dist dh_auto_clean hiyapyco-release-0.7.0/debian/source/000077500000000000000000000000001470510053100174775ustar00rootroot00000000000000hiyapyco-release-0.7.0/debian/source/format000066400000000000000000000000141470510053100207050ustar00rootroot000000000000003.0 (quilt) hiyapyco-release-0.7.0/debian/watch000066400000000000000000000002601470510053100172260ustar00rootroot00000000000000version=4 opts="filenamemangle=s%(?:.*?)?v?(@ANY_VERSION@@ARCHIVE_EXT@)%@PACKAGE@-$1%" \ https://github.com/zerwes/hiyapyco/tags (?:.*?/)release-@ANY_VERSION@@ARCHIVE_EXT@ hiyapyco-release-0.7.0/examples/000077500000000000000000000000001470510053100165735ustar00rootroot00000000000000hiyapyco-release-0.7.0/examples/err.yaml000066400000000000000000000000411470510053100202420ustar00rootroot00000000000000--- a: 0 b: - a - x c hiyapyco-release-0.7.0/examples/hiyapyco_example.py000077500000000000000000000032761470510053100225200ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import argparse basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco class LoggingAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): # print '%r %r %r' % (namespace, values, option_string) logger = logging.getLogger() logger.setLevel(values) setattr(namespace, self.dest, values) logger = logging.getLogger() logging.basicConfig( level=logging.WARN, format='%(levelname)s\t[%(name)s] %(funcName)s: %(message)s' ) parser = argparse.ArgumentParser() parser.add_argument( '-l', '--loglevel', help='set loglevel', type=str, choices=[k for k in logging._nameToLevel.keys() if isinstance(k, str)], action=LoggingAction ) parser.add_argument( '-y', '--usedefaultyamlloader', dest='usedefaultyamlloader', action='store_true', default=False, help='use default yaml loader' ) parser.add_argument('-f', '--file', type=str, nargs='+', required=True, help='yaml file(s) to parse') args = parser.parse_args() if args.loglevel is None: logging.disable(logging.CRITICAL) for mergemethod in hiyapyco.METHODS.keys(): print('='*10, 'method=', mergemethod, '='*10) conf = hiyapyco.load( *args.file, method=hiyapyco.METHODS[mergemethod], interpolate=True, failonmissingfiles=True, usedefaultyamlloader=args.usedefaultyamlloader ) print(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf)) if len(args.file) < 2: break # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/issue25.py000077500000000000000000000013671470510053100204560ustar00rootroot00000000000000#! /usr/bin/env python import sys import os basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco base = """ key_one: 1 key_two: 2 array_of_dicts: - dict_key_one: a dict_key_two: b dict_key_three: c - dict_key_one: a1 dict_key_two: b1 dict_key_three: c1 """ layer = """ key_two: 2222 array_of_dicts: - dict_key_one: a2 dict_key_two: b2 dict_key_three: c2 """ CONF = hiyapyco.load([base, layer], method=hiyapyco.METHOD_MERGE) print (hiyapyco.dump(CONF)) print ("... using mergelists=False ...") CONF = hiyapyco.load([base, layer], method=hiyapyco.METHOD_MERGE, mergelists=False) print (hiyapyco.dump(CONF)) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/issue33.py000077500000000000000000000013111470510053100204420ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco logger = logging.getLogger() logging.basicConfig( level=logging.INFO, format='%(levelname)s\t[%(name)s] %(funcName)s: %(message)s' ) ymlstr = """ k2: 222 k3: - done: a2 - dtwo: b2 dthree """ conf = hiyapyco.load( ymlstr, os.path.join(basepath, 'olist1.yaml'), os.path.join(basepath, 'err.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=False ) print (hiyapyco.dump(conf)) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/issue69.py000077500000000000000000000030021470510053100204520ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco logger = logging.getLogger() logging.basicConfig( level=logging.WARN, format='%(levelname)s\t[%(name)s] %(funcName)s: %(message)s' ) import yaml yaml.Dumper.ignore_aliases = lambda *args : True anchorbase = """ app-specs: &app-specs resources: requests: memory: "1" applications: app1: <<: *app-specs app2: <<: *app-specs """ noanchor = """ app-specs: &app-specs resources: requests: memory: "1" applications: app1: resources: requests: memory: "1" app2: resources: requests: memory: "1" """ anchormerge = """ applications: app2: resources: requests: memory: "2" """ CONF = hiyapyco.load([anchorbase, anchormerge], method=hiyapyco.METHOD_MERGE, dereferenceyamlanchors=False, mergelists=True, interpolate=True, failonmissingfiles=True) #print (hiyapyco.dump(CONF)) print(CONF['applications']['app1']['resources']['requests']['memory']) print(CONF['applications']['app2']['resources']['requests']['memory']) # noanchor #CONF = hiyapyco.load([noanchor, anchormerge], method=hiyapyco.METHOD_MERGE, mergelists=True, interpolate=True, failonmissingfiles=True) #print (hiyapyco.dump(CONF)) #print(CONF['applications']['app1']['resources']['requests']['memory']) #print(CONF['applications']['app2']['resources']['requests']['memory']) hiyapyco-release-0.7.0/examples/issue73compareOrderedDict.py000077500000000000000000000032521470510053100241340ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import argparse basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco class LoggingAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): # print '%r %r %r' % (namespace, values, option_string) logger = logging.getLogger() logger.setLevel(values) setattr(namespace, self.dest, values) logger = logging.getLogger() logging.basicConfig( level=logging.WARN, format='%(levelname)s\t[%(name)s] %(funcName)s: %(message)s' ) parser = argparse.ArgumentParser() parser.add_argument( '-l', '--loglevel', help='set loglevel', type=str, choices=[k for k in logging._nameToLevel.keys() if isinstance(k, str)], action=LoggingAction ) parser.add_argument('-f', '--file', type=str, nargs='+', required=True, help='yaml file(s) to parse') args = parser.parse_args() if args.loglevel is None: logging.disable(logging.INFO) # FIXME: in fact this should be the job of argparse if args.file is None or len(args.file) == 0: raise Exception('please provide at least one yaml file!') for usedefaultyamlloader in [True, False]: print('='*10, 'usedefaultyamlloader=', usedefaultyamlloader, '='*10) conf = hiyapyco.load( *args.file, method=hiyapyco.METHOD_MERGE, interpolate=True, failonmissingfiles=True, usedefaultyamlloader=usedefaultyamlloader ) print(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf, default_flow_style=False)) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/issue73compareOrderedDict.yml000066400000000000000000000000731470510053100243000ustar00rootroot00000000000000--- ooo: xyz llll: a: A z: Z b: B aaa: first ... hiyapyco-release-0.7.0/examples/list.py000077500000000000000000000021271470510053100201250ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco print('='*10, 'method=hiyapyco.METHOD_SIMPLE', '='*10) conf = hiyapyco.load( os.path.join(basepath, 'list1.yaml'), os.path.join(basepath, 'list2.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True ) print(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf)) print('='*10, 'method=hiyapyco.METHOD_MERGE', '='*10) conf = hiyapyco.load( os.path.join(basepath, 'list1.yaml'), os.path.join(basepath, 'list2.yaml'), method=hiyapyco.METHOD_MERGE, failonmissingfiles=True ) print(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf)) assert conf == {'l': {'a': ['laa', 'lab', 'lac', 'lad'], 'b': ['lba', 'lbb', 'lcc', 'lbd'], 'c': [{'csub': ['lcc1', 'lcc2', 'lcc4', 'lcc5']}, 'lcc 2 only', {'csub2': ['csub2 1', 'csub2 2']}, 'lca', 'lcb', 'lcc', 'lcd']}} # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/list1.yaml000066400000000000000000000004671470510053100205220ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent l: a: - laa - lab - lac b: - lba - lbb - lcc c: - csub: - lcc1 - lcc2 - lcc 2 only - csub2: - csub2 1 - csub2 2 hiyapyco-release-0.7.0/examples/list2.yaml000066400000000000000000000004011470510053100205070ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent l: a: - laa - lad b: - lbb - lbd c: - csub: - lcc4 - lcc5 - lca - lcb - lcc - lcd hiyapyco-release-0.7.0/examples/listl.py000077500000000000000000000014321470510053100202770ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import pprint basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco logger = logging.getLogger() logging.basicConfig( level=logging.DEBUG, format='%(levelname)s\t[%(name)s] %(funcName)s: %(message)s' ) conf = hiyapyco.load( os.path.join(basepath, 'listl1.yaml'), os.path.join(basepath, 'listl2.yaml'), method=hiyapyco.METHOD_MERGE, failonmissingfiles=True ) print('-'*10, 'DATA', '-'*10) print(conf) print('-'*10, 'PPRINT', '-'*10) pprint.PrettyPrinter(indent=4).pprint(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf)) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/listl1.yaml000066400000000000000000000005041470510053100206660ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent l1: - d0: - d0k1: only in 1 - d1: - d1k1: v1 - d1k2: v2 - d2: - d2k1: x1 - d2k2: x2 l2: d0: d0k1: only in 1 d1: d1k1: v1 d1k2: v2 d2: d2k1: x1 d2k2: x2 hiyapyco-release-0.7.0/examples/listl2.yaml000066400000000000000000000003761470510053100206760ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent l1: - d1: - d1k3: v3 - d2: - d2k1: xxx - d3: - d3k1: only in 2 l2: d1: d1k3: v3 d2: d2k1: xxx d3: d3k1: only in 2 hiyapyco-release-0.7.0/examples/listl3.py000077500000000000000000000027671470510053100203760ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import pprint basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco logger = logging.getLogger() logging.basicConfig( level=logging.DEBUG, format='%(levelname)s\t[%(name)s] %(funcName)s: %(message)s' ) print('='*10, 'method=hiyapyco.METHOD_SIMPLE', '='*10) conf = hiyapyco.load( os.path.join(basepath, 'listl31.yaml'), os.path.join(basepath, 'listl32.yaml'), failonmissingfiles=True ) print('-'*10, 'DATA', '-'*10) print(conf) print('-'*10, 'PPRINT', '-'*10) pprint.PrettyPrinter(indent=4).pprint(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf)) print('-'*10, 'EOF', '-'*10) assert conf['l3'] == [{'a': 'aaa', 'c': 'c'}, {'b': 'BBB', 'c': 'CCC'}, {'a': 'x', 'b': 'y', 'c': 'z'}] print('='*10, 'method=hiyapyco.METHOD_MERGE', '='*10) conf = hiyapyco.load( os.path.join(basepath, 'listl31.yaml'), os.path.join(basepath, 'listl32.yaml'), method=hiyapyco.METHOD_MERGE, failonmissingfiles=True ) print('-'*10, 'DATA', '-'*10) print(conf) print('-'*10, 'PPRINT', '-'*10) pprint.PrettyPrinter(indent=4).pprint(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf)) print('-'*10, 'EOF', '-'*10) assert conf['l3'] == [{'a': 'aaa', 'b': 'b', 'c': 'c'}, {'a': 'A', 'b': 'BBB', 'c': 'CCC'}, {'a': 'x', 'b': 'y', 'c': 'z'}] # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/listl31.yaml000066400000000000000000000001631470510053100207520ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent l3: - a: a b: b - a: A b: B hiyapyco-release-0.7.0/examples/listl32.yaml000066400000000000000000000002321470510053100207500ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent l3: - a: aaa c: c - b: BBB c: CCC - a: x b: y c: z hiyapyco-release-0.7.0/examples/listn.py000077500000000000000000000012641470510053100203040ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco conf = hiyapyco.load( os.path.join(basepath, 'listn1.yaml'), os.path.join(basepath, 'listn2.yaml'), method=hiyapyco.METHOD_MERGE, failonmissingfiles=True ) print(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf)) assert conf == {'l1': [{'d1': {'d1k1': 'v1', 'd1k2': 'v2', 'd1k3': 'v3'}}, {'d2': {'d2k2': 'x2', 'd2k1': 'xxx'}}, {'d0': {'d0k1': 'only in 1'}}, {'d3': {'d3k1': 'only in 2'}}]} # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/listn1.yaml000066400000000000000000000003011470510053100206630ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent l1: - d1: d1k1: v1 d1k2: v2 - d2: d2k1: x1 d2k2: x2 - d0: d0k1: only in 1 hiyapyco-release-0.7.0/examples/listn2.yaml000066400000000000000000000002401470510053100206660ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent l1: - d1: d1k3: v3 - d2: d2k1: xxx - d3: d3k1: only in 2 hiyapyco-release-0.7.0/examples/missingfilesloglevel.py000077500000000000000000000036031470510053100234000ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import pprint basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco logger = logging.getLogger() logging.basicConfig( level=logging.INFO, format='%(levelname)s\t[%(name)s] %(funcName)s: %(message)s' ) print('*'*70) print(' hiyapyco %s' % hiyapyco.version.VERSION) print('*'*70) print('-'*70) print(' loglevelmissingfiles=logging.INFO + failonmissingfiles=True ...') print('-'*70) try: conf = hiyapyco.load( os.path.join(basepath, 'olist1.yaml'), os.path.join(basepath, 'NoSuchFile.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, loglevelmissingfiles=logging.INFO ) except hiyapyco.HiYaPyCoInvocationException: pass print('-'*70) print(' loglevelmissingfiles=logging.INFO + failonmissingfiles=False ...') print('-'*70) conf = hiyapyco.load( os.path.join(basepath, 'olist1.yaml'), os.path.join(basepath, 'NoSuchFile.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=False, loglevelmissingfiles=logging.INFO ) print('-'*70) print(' loglevelmissingfiles=UNSET + failonmissingfiles=True ...') print('-'*70) try: conf = hiyapyco.load( os.path.join(basepath, 'olist1.yaml'), os.path.join(basepath, 'NoSuchFile.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True ) except hiyapyco.HiYaPyCoInvocationException: pass print('-'*70) print(' loglevelmissingfiles=UNSET + failonmissingfiles=False ...') print('-'*70) conf = hiyapyco.load( os.path.join(basepath, 'olist1.yaml'), os.path.join(basepath, 'NoSuchFile.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=False ) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/odyldocompare.py000077500000000000000000000012041470510053100220060ustar00rootroot00000000000000#! /usr/bin/env python """ PYTHONPATH=. python examples/odyldocompare.py [FILE] """ import hiyapyco.odyldo as odyldo import yaml import sys import os FILES = sys.argv[1:] if not FILES: FILES = ['test/odyl.yaml'] for F in FILES: print ('='*60) print ('-'*10, ' ORIGINAL %s ' % F, '-'*10) f = open(F, 'r') ydata = yaml.safe_load(f) print(ydata) print ('-'*60) print (yaml.safe_dump(ydata, default_flow_style = False)) print ('='*60) print ('-'*10, ' ODYLDo %s ' % F, '-'*10) f = open(F, 'r') ydata = odyldo.safe_load(f) print(ydata) print ('-'*60) print(odyldo.safe_dump(ydata, default_flow_style = False)) print ('='*60) hiyapyco-release-0.7.0/examples/olist.py000077500000000000000000000026021470510053100203020ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import pprint basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco logger = logging.getLogger() logging.basicConfig( level=logging.DEBUG, format='%(levelname)s\t[%(name)s] %(funcName)s: %(message)s' ) print('='*10, 'method=hiyapyco.METHOD_SIMPLE', '='*10) conf = hiyapyco.load( os.path.join(basepath, 'olist1.yaml'), os.path.join(basepath, 'olist2.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True ) print('-'*10, 'DATA', '-'*10) print(conf) print('-'*10, 'PPRINT', '-'*10) pprint.PrettyPrinter(indent=4).pprint(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf)) assert conf == ['A', 'b', 'C', ['da', 'DB', 'DC']] print('='*10, 'method=hiyapyco.METHOD_MERGE', '='*10) conf = hiyapyco.load( os.path.join(basepath, 'olist1.yaml'), os.path.join(basepath, 'olist2.yaml'), method=hiyapyco.METHOD_MERGE, failonmissingfiles=True ) print('-'*10, 'DATA', '-'*10) print(conf) print('-'*10, 'PPRINT', '-'*10) pprint.PrettyPrinter(indent=4).pprint(conf) print('-'*10, 'YAML', '-'*10) print(hiyapyco.dump(conf)) assert conf == ['a', 'b', 'c', ['da', 'db', 'dc'], 'A', 'C', [None, 'DB', 'DC']] # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/examples/olist1.yaml000066400000000000000000000000421470510053100206660ustar00rootroot00000000000000- a - b - c - - da - db - dc hiyapyco-release-0.7.0/examples/olist2.yaml000066400000000000000000000000361470510053100206720ustar00rootroot00000000000000- A - - C - - - DB - DC hiyapyco-release-0.7.0/examples/tags.py000077500000000000000000000021361470510053100201100ustar00rootroot00000000000000#! /usr/bin/env python # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu import sys import os basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import yaml import hiyapyco class GenericElement(yaml.YAMLObject): def __init__(self, value, tag, style=None): self._value = value self._tag = tag self._style = style def to_yaml(dumper, data): return dumper.represent_scalar(data._tag, data._value, style=data._style) def unknown_tag_handler(loader, tag_suffix, node): if isinstance(node, yaml.ScalarNode): return GenericElement(node.value, tag_suffix, style=node.style) else: raise NotImplementedError('Node: ' + str(type(node))) yaml.add_multi_constructor('', unknown_tag_handler, Loader=yaml.SafeLoader) yaml.add_representer(GenericElement, GenericElement.to_yaml, Dumper=yaml.SafeDumper) conf = hiyapyco.load( os.path.join(basepath, 'tags.yaml'), method=hiyapyco.METHOD_SIMPLE, usedefaultyamlloader=True, failonmissingfiles=True ) print(hiyapyco.dump(conf)) hiyapyco-release-0.7.0/examples/tags.yaml000066400000000000000000000007151470510053100204200ustar00rootroot00000000000000--- test: text my_encrypted_var: !vault | $ANSIBLE_VAULT;1.2;AES256;dev 30613233633461343837653833666333643061636561303338373661313838333565653635353162 3263363434623733343538653462613064333634333464660a663633623939393439316636633863 61636237636537333938306331383339353265363239643939666639386530626330633337633833 6664656334373166630a363736393262666465663432613932613036303963343263623137386239 6330 hiyapyco-release-0.7.0/examples/test_ruamel_yaml_loader.py000066400000000000000000000030421470510053100240400ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform try: from ruamel.yaml import YAML except ModuleNotFoundError: print('you need to install ruamel.yaml') sys.exit(0) basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco sys.path.insert( 0, os.path.join( os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))), "../test/lib" ), ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print( "start test %s for hiyapyco %s using python %s (loglevel:%s)" % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()), ) ) logger.info("test ruamel yaml loader ...") def ruamel_loader(stream): yaml = YAML(typ='safe') return yaml.load_all(stream) conf = hiyapyco.load(os.path.join(basepath, "../test/base.yaml"), loader_callback=ruamel_loader) expected = {'singel': 'base', 'int': 1, 'array': ['base1', 'base2'], 'hash': {'k1': 'b1', 'k2': 'b2'}, 'deeplist': [{'d1': {'d1k1': 'v1', 'd1k2': 'v2'}}, {'d2': {'d2k1': 'x1', 'd2k2': 'x2'}}, {'d31': {'a': 'A', 'b': 'B', 'c': 'C'}, 'd32': {'a': 'A2', 'b': 'B2'}}], 'deepmap': {'l1k1': {'l2k1': 'xyz', 'l2k2': 'abc'}, 'l1k2': {'l2k1': 'bli', 'l2k2': 'bla', 'l2k3': 'blub'}}, 'missing_key': 'one', 'common_key': {'common_subkey_deep': 'one', 'missing_key_base': 'val2'}} assert conf == expected print("passed test %s" % __file__) hiyapyco-release-0.7.0/hiyapyco/000077500000000000000000000000001470510053100166025ustar00rootroot00000000000000hiyapyco-release-0.7.0/hiyapyco/__init__.py000066400000000000000000000626321470510053100207240ustar00rootroot00000000000000#! /usr/bin/env python -tt # vim: set fileencoding=utf-8 """ Hierarchical Yaml Python Config =============================== A simple python lib allowing hierarchical config files in YAML syntax. License ------- (c) 2014 - 2024 Klaus Zerwes zero-sys.net This package is free software. This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE version 3 or later, as published by the Free Software Foundation. See https://www.gnu.org/licenses/gpl.html """ from __future__ import unicode_literals import os import logging import re import io import copy import yaml from jinja2 import Environment, Undefined, DebugUndefined, StrictUndefined, TemplateError from . import odyldo __all__ = [ 'load', 'dump', 'HiYaPyCo', 'HiYaPyCoInvocationException', 'HiYaPyCoImplementationException', ] from . import version __version__ = version.VERSION logger = logging.getLogger(__name__) _USEDEFAULTYAMLLOADER = False class HiYaPyCoInvocationException(Exception): """dummy Exception raised on wrong invocation""" pass class HiYaPyCoImplementationException(Exception): """dummy Exception raised if we are unable to merge some YAML stuff""" pass primitiveTypes = (int, str, bool, float) # pylint: disable=superfluous-parens strTypes = (str) listTypes = (list, tuple) # you may set this to something suitable for you jinja2env = Environment(undefined=Undefined) METHODS = { 'METHOD_SIMPLE':0x0001, 'METHOD_MERGE':0x0002, 'METHOD_SUBSTITUTE':0x0003, } METHOD_SIMPLE = METHODS['METHOD_SIMPLE'] METHOD_MERGE = METHODS['METHOD_MERGE'] METHOD_SUBSTITUTE = METHODS['METHOD_SUBSTITUTE'] NONE_BEHAVIORS = {"NONE_BEHAVIOR_DEFAULT": 0x0001, "NONE_BEHAVIOR_OVERRIDE": 0x0002} NONE_BEHAVIOR_DEFAULT = NONE_BEHAVIORS["NONE_BEHAVIOR_DEFAULT"] NONE_BEHAVIOR_OVERRIDE = NONE_BEHAVIORS["NONE_BEHAVIOR_OVERRIDE"] class HiYaPyCo: """Main class""" # pylint: disable=too-many-instance-attributes disable=too-many-branches disable=too-many-statements def __init__(self, *args, **kwargs): """ args: YAMLfile(s) kwargs: * method: one of hiyapyco.METHOD_SIMPLE | hiyapyco.METHOD_MERGE | hiyapyco.METHOD_SUBSTITUTE * mergelists: boolean (default: True) try to merge lists (only makes sense if hiyapyco.METHOD_MERGE or hiyapyco.METHOD_SUBSTITUTE) * none_behavior: one of hiyapyco.NONE_BEHAVIOR_DEFAULT | hiyapyco.NONE_BEHAVIOR_OVERRIDE * interpolate: boolean (default: False) * castinterpolated: boolean (default: False) try to cast values after interpolating * usedefaultyamlloader: boolean (default: False) * dereferenceyamlanchors: boolean (default: True) * encoding: (default: 'utf-8') encoding used to read yaml files * loglevel: one of the valid levels from the logging module * failonmissingfiles: boolean (default: True) * loglevelmissingfiles * mergeoverride: optional function to customize merge for primitive values * loader_callback: optional custom callback function to load yaml files. The callback function shall behave like `yaml.load_all`, taking a IO stream as input and returning a list of objects. Returns a representation of the merged and (if requested) interpolated config. Will mostly be a OrderedDict (dict if usedefaultyamlloader), but can be of any other type, depending on the yaml files. """ self._data = None self._files = [] self.method = None self.loader_callback = kwargs.pop("loader_callback", None) if 'method' in kwargs: logger.debug('parse kwarg method: %s ...' % kwargs['method']) if kwargs['method'] not in METHODS.values(): raise HiYaPyCoInvocationException( 'undefined method used, must be one of: %s' % ' '.join(METHODS.keys()) ) self.method = kwargs['method'] del kwargs['method'] if self.method is None: self.method = METHOD_SIMPLE self.mergelists = True if 'mergelists' in kwargs: if not isinstance(kwargs['mergelists'], bool): raise HiYaPyCoInvocationException( 'value of "mergelists" must be boolean (got: "%s" as %s)' % (kwargs['mergelists'], type(kwargs['mergelists']),) ) self.mergelists = kwargs['mergelists'] del kwargs['mergelists'] self.none_behavior = None if "none_behavior" in kwargs: logger.debug("parse kwarg method: %s ..." % kwargs["none_behavior"]) if kwargs["none_behavior"] not in NONE_BEHAVIORS.values(): raise HiYaPyCoInvocationException( "undefined method used, must be one of: %s" % " ".join(NONE_BEHAVIORS.keys()) ) self.none_behavior = kwargs["none_behavior"] del kwargs["none_behavior"] if self.none_behavior is None: self.none_behavior = NONE_BEHAVIOR_DEFAULT self.interpolate = False self.castinterpolated = False if 'interpolate' in kwargs: if not isinstance(kwargs['interpolate'], bool): raise HiYaPyCoInvocationException( 'value of "interpolate" must be boolean (got: "%s" as %s)' % (kwargs['interpolate'], type(kwargs['interpolate']),) ) self.interpolate = kwargs['interpolate'] del kwargs['interpolate'] if 'castinterpolated' in kwargs: if not isinstance(kwargs['castinterpolated'], bool): raise HiYaPyCoInvocationException( 'value of "castinterpolated" must be boolean (got: "%s" as %s)' % (kwargs['castinterpolated'], type(kwargs['castinterpolated']),) ) self.castinterpolated = kwargs['castinterpolated'] del kwargs['castinterpolated'] if 'usedefaultyamlloader' in kwargs: if not isinstance(kwargs['usedefaultyamlloader'], bool): raise HiYaPyCoInvocationException( 'value of "usedefaultyamlloader" must be boolean (got: "%s" as %s)' % (kwargs['usedefaultyamlloader'], type(kwargs['usedefaultyamlloader']),) ) global _USEDEFAULTYAMLLOADER _USEDEFAULTYAMLLOADER = kwargs['usedefaultyamlloader'] del kwargs['usedefaultyamlloader'] self.dereferenceyamlanchors = True if 'dereferenceyamlanchors' in kwargs: if not isinstance(kwargs['dereferenceyamlanchors'], bool): raise HiYaPyCoInvocationException( 'value of "dereferenceyamlanchors" must be boolean (got: "%s" as %s)' % (kwargs['dereferenceyamlanchors'], type(kwargs['dereferenceyamlanchors']),) ) self.dereferenceyamlanchors = bool(kwargs['dereferenceyamlanchors']) del kwargs['dereferenceyamlanchors'] self.failonmissingfiles = True if 'failonmissingfiles' in kwargs: if not isinstance(kwargs['failonmissingfiles'], bool): raise HiYaPyCoInvocationException( 'value of "failonmissingfiles" must be boolean (got: "%s" as %s)' % (kwargs['failonmissingfiles'], type(kwargs['failonmissingfiles']),) ) self.failonmissingfiles = bool(kwargs['failonmissingfiles']) del kwargs['failonmissingfiles'] if 'loglevelmissingfiles' in kwargs: logging.getLogger('testlevellogger').setLevel(kwargs['loglevelmissingfiles']) self.loglevelonmissingfiles = logging.getLogger('testlevellogger').getEffectiveLevel() del kwargs['loglevelmissingfiles'] else: self.loglevelonmissingfiles = logging.ERROR if not self.failonmissingfiles: self.loglevelonmissingfiles = logging.WARN if 'loglevel' in kwargs: logger.setLevel(kwargs['loglevel']) del kwargs['loglevel'] self.encoding = 'utf-8' if 'encoding' in kwargs: self.encoding = kwargs['encoding'] del kwargs['encoding'] self.mergeprimitive = None if 'mergeoverride' in kwargs: # DEBT: Compare to make sure function signature is right self.mergeprimitive = kwargs['mergeoverride'] del kwargs['mergeoverride'] if kwargs: raise HiYaPyCoInvocationException('undefined keywords: %s' % ' '.join(kwargs.keys())) if not args: raise HiYaPyCoInvocationException('no yaml files defined') for arg in args: self._updatefiles(arg) for yamlfile in self._files[:]: logger.debug('yamlfile: %s ...' % yamlfile) try: if '\n' in yamlfile: logger.debug('loading yaml doc from str ...') f = yamlfile self._load_data(_USEDEFAULTYAMLLOADER, yamlfile) else: fn = yamlfile if not os.path.isabs(yamlfile): fn = os.path.join(os.getcwd(), yamlfile) logger.debug('path extended for yamlfile: %s' % fn) try: with io.open(fn, 'r', encoding=self.encoding) as f: logger.debug('open4reading: file %s' % f) self._load_data(_USEDEFAULTYAMLLOADER, f) except IOError as e: logger.log(self.loglevelonmissingfiles, e) if not fn == yamlfile: logger.log(self.loglevelonmissingfiles, 'file not found: %s (%s)' % (yamlfile, fn,)) else: logger.log(self.loglevelonmissingfiles, 'file not found: %s' % yamlfile) if self.failonmissingfiles: raise HiYaPyCoInvocationException( 'yaml file not found: \'%s\'' % yamlfile ) self._files.remove(yamlfile) continue except yaml.parser.ParserError as e: logger.log(self.loglevelonmissingfiles, e) logger.log(self.loglevelonmissingfiles, 'error while parsing yaml %s' % f) if self.failonmissingfiles: raise HiYaPyCoInvocationException( 'error while parsing file: \'%s\'' % f ) self._files.remove(yamlfile) continue if self.interpolate: self._data = self._interpolate(self._data) def _load_data(self, _USEDEFAULTYAMLLOADER, f): if self.loader_callback is not None: ydata_generator = self.loader_callback(f) elif _USEDEFAULTYAMLLOADER: ydata_generator = yaml.safe_load_all(f) else: ydata_generator = odyldo.safe_load_all(f) for ydata in ydata_generator: if logger.isEnabledFor(logging.DEBUG): logger.debug('yaml data: %s' % ydata) if self._data is None: self._data = ydata else: if self.method == METHOD_SIMPLE: self._data = self._simplemerge(self._data, ydata) elif self.method == METHOD_MERGE: self._data = self._deepmerge(self._data, ydata) elif self.method == METHOD_SUBSTITUTE: self._data = self._substmerge(self._data, ydata) else: raise HiYaPyCoInvocationException('unknown merge method \'%s\'' % self.method) logger.debug('merged data: %s' % self._data) def _updatefiles(self, arg): if isinstance(arg, strTypes): if arg in self._files: logger.warning('ignoring duplicated file %s' % arg) return self._files.append(arg) elif isinstance(arg, listTypes): for larg in arg: self._updatefiles(larg) else: raise HiYaPyCoInvocationException( 'unable to handle arg %s of type %s' % (arg, type(arg),) ) def _interpolate(self, d): logger.debug('interpolate "%s" of type %s ...' % (d, type(d),)) if d is None: return None if isinstance(d, strTypes): return self._interpolatestr(d) if isinstance(d, primitiveTypes): return d if isinstance(d, listTypes): for k, v in enumerate(d): d[k] = self._interpolate(v) return d if isinstance(d, dict): for k in d.keys(): d[k] = self._interpolate(d[k]) return d raise HiYaPyCoImplementationException('can not interpolate "%s" of type %s' % (d, type(d),)) def _interpolatestr(self, s): try: si = jinja2env.from_string(s).render(self._data) except TemplateError as e: # FIXME: this seems to be broken for unicode str? raise HiYaPyCoImplementationException('error interpolating string "%s" : %s' % (s, e,)) if not s == si: if self.castinterpolated: if not re.match( r'^\d+\.*\d*$', si): try: si = bool(strtobool(si)) except ValueError: pass else: try: if '.' in si: si = float(si) else: si = int(si) except ValueError: pass logger.debug('interpolated "%s" to "%s" (type: %s)' % (s, si, type(si),)) return si def _simplemerge(self, a, b): if self.dereferenceyamlanchors: a = copy.deepcopy(a) b = copy.deepcopy(b) logger.debug('simplemerge %s (%s) and %s (%s)' % (a, type(a), b, type(b),)) if b is None: # override -> None replaces object, no matter what. if self.none_behavior == NONE_BEHAVIOR_OVERRIDE: logger.debug('b is None + none_behavior in use => return None') return None # default behavior is to attempt merge or fail logger.debug('pass as b is None') pass elif isinstance(b, primitiveTypes): logger.debug('simplemerge: primitiveTypes replace a "%s" w/ b "%s"' % (a, b,)) a = b elif isinstance(b, listTypes): logger.debug('simplemerge: listTypes a "%s" w/ b "%s"' % (a, b,)) if isinstance(a, listTypes): # pylint: disable=unused-variable for k, v in enumerate(b): try: a[k] = self._simplemerge(a[k], b[k]) except IndexError: a[k] = b[k] else: logger.debug('simplemerge: replace %s w/ list %s' % (a, b,)) a = b elif isinstance(b, dict): if isinstance(a, dict): logger.debug('simplemerge: update %s:"%s" by %s:"%s"' % (type(a), a, type(b), b,)) a.update(b) else: logger.debug('simplemerge: replace %s w/ dict %s' % (a, b,)) a = b else: raise HiYaPyCoImplementationException( 'can not (simple)merge %s to %s (@ "%s" try to merge "%s")' % (type(b), type(a), a, b,) ) return a def _substmerge(self, a, b): if self.dereferenceyamlanchors: a = copy.deepcopy(a) b = copy.deepcopy(b) logger.debug('>' * 30) logger.debug('substmerge %s and %s' % (a, b,)) # FIXME: make None usage configurable if b is None: logger.debug('pass as b is None') # override -> None replaces object, no matter what. if self.none_behavior == NONE_BEHAVIOR_OVERRIDE: logger.debug('b is None + none_behavior in use => return None') return None # default behavior is to attempt merge or fail logger.debug('pass as b is None') pass # treat listTypes as primitiveTypes in merge # subsititues list, don't merge them if a is None or isinstance(b, primitiveTypes) or isinstance(b, listTypes): logger.debug('substmerge: replace a "%s" w/ b "%s"' % (a, b,)) a = b elif isinstance(a, dict): if isinstance(b, dict): logger.debug('substmerge: dict ... "%s" and "%s"' % (a, b,)) for k in b: if k in a: logger.debug( 'substmerge dict: loop for key "%s": "%s" and "%s"' % (k, a[k], b[k],) ) a[k] = self._substmerge(a[k], b[k]) else: logger.debug('substmerge dict: set key %s' % k) a[k] = b[k] elif isinstance(b, listTypes): logger.debug('substmerge: dict <- list ... "%s" <- "%s"' % (a, b,)) for bd in b: if isinstance(bd, dict): a = self._substmerge(a, bd) else: raise HiYaPyCoImplementationException( 'can not merge element from list of type %s to dict ' '(@ "%s" try to merge "%s")' % (type(b), a, b,) ) else: raise HiYaPyCoImplementationException( 'can not merge %s to %s (@ "%s" try to merge "%s")' % (type(b), type(a), a, b,) ) logger.debug('end substmerge part: return: "%s"' % a) logger.debug('<' * 30) return a def _deepmerge(self, a, b, context = None): if context is None: # DEBT: May be better to make this a class from the get go # for better forward compatibility if we add things like file # name, etc. context = [] logger.debug('>'*30) if self.dereferenceyamlanchors: a = copy.deepcopy(a) b = copy.deepcopy(b) logger.debug('deepmerge %s and %s' % (a, b,)) # FIXME: make None usage configurable if b is None: logger.debug('pass as b is None') # override -> None replaces object, no matter what. if self.none_behavior == NONE_BEHAVIOR_OVERRIDE: return None # default behavior is to attempt merge or fail logger.debug('pass as b is None') pass if a is None or isinstance(b, primitiveTypes): if self.mergeprimitive is None: logger.debug('deepmerge: replace a "%s" w/ b "%s"' % (a, b,)) a = b else: logger.debug( 'deepmerge: call mergeprimitive for a "%s", b "%s" with context' % (a, b,) ) a = self.mergeprimitive(a, b, context) elif isinstance(a, listTypes): if isinstance(b, listTypes): logger.debug( 'deepmerge: lists extend %s:"%s" by %s:"%s"' % (type(a), a, type(b), b,) ) a.extend(be for be in b if be not in a and (isinstance(be, primitiveTypes) or isinstance(be, listTypes)) ) srcdicts = {} for k, bd in enumerate(b): if isinstance(bd, dict): srcdicts.update({k:bd}) logger.debug('srcdicts: %s' % srcdicts) for k, ad in enumerate(a): logger.debug('deepmerge ad "%s" w/ k "%s" of type %s' % (ad, k, type(ad))) if isinstance(ad, dict): if k in srcdicts: # we merge only if at least one key in dict is matching merge = False if self.mergelists: for ak in ad.keys(): if ak in srcdicts[k].keys(): merge = True break if merge: # pylint: disable=undefined-loop-variable # FIXME undefined-loop-variable : this is not well readable !!! logger.debug( 'deepmerge ad: deep merge list dict elem w/ ' 'key:%s: "%s" and "%s"' % (ak, ad, srcdicts[k],) ) a[k] = self._deepmerge(ad, srcdicts[k], context) del srcdicts[k] logger.debug('deepmerge list: remaining srcdicts elems: %s' % srcdicts) for k, v in srcdicts.items(): logger.debug('deepmerge list: new dict append %s:%s' % (k, v)) a.append(v) else: raise HiYaPyCoImplementationException( 'can not merge %s to %s (@ "%s" try to merge "%s")' % (type(b), type(a), a, b,) ) elif isinstance(a, dict): if isinstance(b, dict): logger.debug('deepmerge: dict ... "%s" and "%s"' % (a, b,)) for k in b: if k in a: logger.debug( 'deepmerge dict: loop for key "%s": "%s" and "%s"' % (k, a[k], b[k],) ) context.append(k) a[k] = self._deepmerge(a[k], b[k], context) context.pop() else: logger.debug('deepmerge dict: set key %s' % k) a[k] = b[k] elif isinstance(b, listTypes): logger.debug('deepmerge: dict <- list ... "%s" <- "%s"' % (a, b,)) for bd in b: if isinstance(bd, dict): a = self._deepmerge(a, bd, context) else: raise HiYaPyCoImplementationException( 'can not merge element from list of type %s to dict ' '(@ "%s" try to merge "%s")' % (type(b), a, b,) ) else: raise HiYaPyCoImplementationException( 'can not merge %s to %s (@ "%s" try to merge "%s")' % (type(b), type(a), a, b,) ) logger.debug('end deepmerge part: return: "%s"' % a) logger.debug('<'*30) return a def yamlfiles(self): """returns the list of parsed yaml files / strings""" return self._files def __str__(self): """String representation of the class""" return '%s [%s]' % (__name__, os.pathsep.join(self._files)) def data(self): """return the data, merged and interpolated if required""" return self._data def dump(self, **kwds): """dump the data as YAML""" return dump(self._data, **kwds) def dump(data, **kwds): """dump the data as YAML""" if _USEDEFAULTYAMLLOADER: return yaml.safe_dump(data, **kwds) return odyldo.safe_dump(data, **kwds) def load(*args, **kwargs): """ Load a Hierarchical Yaml Python Config -------------------------------------- args: YAMLfile(s) kwargs: * method: one of hiyapyco.METHOD_SIMPLE | hiyapyco.METHOD_MERGE | hiyapyco.METHOD_SUBSTITUTE * mergelists: boolean (default: True) try to merge lists (only makes sense if hiyapyco.METHOD_MERGE or hiyapyco.METHOD_SUBSTITUTE) * interpolate: boolean (default: False) * castinterpolated: boolean (default: False) try to cast values after interpolating * usedefaultyamlloader: boolean (default: False) * encoding: (default: 'utf-8') encoding used to read yaml files * loglevel: one of the valid levels from the logging module * failonmissingfiles: boolean (default: True) * loglevelmissingfiles Returns a representation of the merged and (if requested) interpolated config. Will mostly be a OrderedDict (dict if usedefaultyamlloader), but can be of any other type, depending on the yaml files. """ hiyapyco = HiYaPyCo(*args, **kwargs) return hiyapyco.data() def strtobool(val): """ minimal implementation of the strtobool function (replaces deprecated distutils) """ val = val.lower() if val in ("y", "yes", "t", "true", "on", "1"): return 1 if val in ("n", "no", "f", "false", "off", "0"): return 0 raise ValueError("invalid truth value %r" % (val,)) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/hiyapyco/odyldo.py000066400000000000000000000050541470510053100204520ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu fileencoding=utf-8 from __future__ import unicode_literals """ ODYLDo - Ordered Dict Yaml Loader / Dumper ------------------------------------------ a simple implementation of a Ordered Dict Loader for PyYAML; because chaos is fun but order matters on loading dicts from a yaml file; (c) 2014 - 2024 Klaus Zerwes zero-sys.net This package is free software. This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE version 3 or later, as published by the Free Software Foundation. See https://www.gnu.org/licenses/gpl.html """ import yaml import yaml.loader import yaml.dumper import yaml.representer from collections import OrderedDict # @see: yaml.resolver.DEFAULT_MAPPING_TAG ODYLDoYAMLMAPS = [ 'tag:yaml.org,2002:map', 'tag:yaml.org,2002:omap', ] class ODYL(yaml.SafeLoader): """Ordered Dict Yaml Loader""" def __init__(self, *args, **kwargs): yaml.SafeLoader.__init__(self, *args, **kwargs) for mapping in ODYLDoYAMLMAPS: self.add_constructor(mapping, type(self)._odyload) # see pyyaml constructors construct_* def _odyload(self, node): if node.tag not in ODYLDoYAMLMAPS: raise Exception('called ODYLoad for unregistered mapping mode "%s" aka. "%s"' % (node.tag, node.id,)) data = OrderedDict() yield data data.update(self.construct_mapping(node)) # see pyyaml construct_mapping def construct_mapping(self, node, deep=False): self.flatten_mapping(node) m = OrderedDict() for k, v in node.value: m[self.construct_object(k, deep=deep)] = self.construct_object(v, deep=deep) return m class ODYD(yaml.SafeDumper): """Ordered Dict Yaml Dumper""" def __init__(self, *args, **kwargs): yaml.SafeDumper.__init__(self, *args, **kwargs) yaml.representer.SafeRepresenter.add_representer(OrderedDict, type(self)._odyrepr) def _odyrepr(self, data): """see: yaml.representer.represent_mapping""" return self.represent_mapping('tag:yaml.org,2002:map', data.items()) def safe_load(stream): """implementation of safe loader using Ordered Dict Yaml Loader""" return yaml.load(stream, ODYL) def safe_load_all(stream): """safe parse all YAML documents in a stream using Ordered Dict Yaml Loader""" return yaml.load_all(stream, ODYL) def safe_dump(data, stream=None, **kwds): """implementation of safe dumper using Ordered Dict Yaml Dumper""" return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds) hiyapyco-release-0.7.0/hiyapyco/version.py000066400000000000000000000000201470510053100206310ustar00rootroot00000000000000VERSION='0.7.0' hiyapyco-release-0.7.0/setup.cfg000066400000000000000000000001051470510053100165720ustar00rootroot00000000000000[bdist_wheel] universal=1 [metadata] description_file = README.rst hiyapyco-release-0.7.0/setup.py000066400000000000000000000025151470510053100164720ustar00rootroot00000000000000#!/usr/bin/env python import sys import os from setuptools import setup basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) HIYAPYCOVERSION='0.7.0' long_description = open('README.rst').read() installrequires = [ 'PyYAML<7', 'Jinja2>3,<4', 'MarkupSafe<4' ] setup(name='HiYaPyCo', version=HIYAPYCOVERSION, description='Hierarchical Yaml Python Config', long_description="%s" % long_description, long_description_content_type='text/x-rst', author='Klaus Zerwes zero-sys.net', author_email='zerwes@users.noreply.github.com', url='https://github.com/zerwes/hiyapyco', license='GPLv3', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.11', ], packages=['hiyapyco'], keywords='configuration parser yaml', install_requires = installrequires, platforms = 'any', ) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/000077500000000000000000000000001470510053100157345ustar00rootroot00000000000000hiyapyco-release-0.7.0/test/anchoralias.yaml000066400000000000000000000004611470510053100211050ustar00rootroot00000000000000--- anchorsimple: &as "anchor - string" anchorlist: &al - alist1key: alist1val - alist2key: alist2val - alist3key: alist3val anchordict: &ad adkey1: "ad value 1" adkey2: "ad value 2" testvar: simple: *as list: *al listwithmerge: <<: *al dict: *ad dictwithmerge: <<: *ad ... hiyapyco-release-0.7.0/test/anchoralias2.yaml000066400000000000000000000003621470510053100211670ustar00rootroot00000000000000--- testvar: simple: new text list: - alist1key: another value for alistkey1 listwithmerge: - alist1key: alist1val now updated dict: adkey1: aaa1aa adkey3: xxx dictwithmerge: adkey2: bb2bb adkey3: yyy ... hiyapyco-release-0.7.0/test/base.yaml000066400000000000000000000010301470510053100175240ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent singel: base int: 1 array: - base1 - base2 hash: k1: b1 k2: b2 deeplist: - d1: d1k1: v1 d1k2: v2 - d2: d2k1: x1 d2k2: x2 - d31: a: A b: B c: C d32: a: A2 b: B2 deepmap: l1k1: l2k1: xyz l2k2: abc l1k2: l2k1: bli l2k2: bla l2k3: blub missing_key: one common_key: common_subkey_deep: one missing_key_base: val2 hiyapyco-release-0.7.0/test/base_none_behavior.yaml000066400000000000000000000003761470510053100224360ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent singel: null int: null array: null hash: null deeplist: - d1: null - d2: d2k1: null d2k2: x2 deepmap: l1k1: l2k1: null l2k2: abc l1k2: null hiyapyco-release-0.7.0/test/baseext.yaml000066400000000000000000000010151470510053100202500ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent singel: ext int: 10 array: - baseext1 - baseext2 hash: ek1: be1 ek2: be2 deeplist: - d1: d1ext: vext - dext1: d1k1ext: v1ext - d31: a: AAA d32: a: A2A2 c: CCC deepmap: l1k1: l2k1: overwr l2k3: new val l1k1ext: l2k1ext: ext ext: extendet only missing_key_parent: a: b common_key: common_subkey_deep: oneext missing_key_ext: val2missingInBase hiyapyco-release-0.7.0/test/castinterpolated.yaml000066400000000000000000000001561470510053100221670ustar00rootroot00000000000000--- one: 1 two: 2 three: "{{ one + two }}" a: 2.1 b: 3.8 c: "{{ a + b }}" b1: a b2: a bool: "{{ b1 == b2 }}" hiyapyco-release-0.7.0/test/interpolate.yaml000066400000000000000000000014371470510053100211530ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent first: first element firstcopy: "{{ first }}" second: again {{ first }} list: - abc - bcd - "cde" - "{{ list[0] }}" elist: deep: k1: - 10 - 11 - 12 k2: - 22 - 23 k3: - ali - baba - and - the - 40 - thieves interp: str: "{{ deep['k1'][0] }} + {{ deep.k2.1 }}" sum: "{{ deep['k1'][0] + deep.k2.1 }}" join: "{{ deep.k3|join(' ') }}" m: - a: A b: "{{ undefined }}" c: "{{ deep.k3[0:2]|join(' ')|upper }}" - a: B b: "{{ second }}" c: "{{ m.2.a }}" #this is not working because m.2.a must be interpolated too - a: "C & {{ m.0.a }}" b: cc c: ccc hiyapyco-release-0.7.0/test/interpolateunicode.yaml000066400000000000000000000005361470510053100225210ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent # vim: set fileencoding=utf-8 one: Öns oneKorean: 하나 t: 40 Zwö: ölybaba {{ one }} zwö ... {{ t }} UnicoDict: Umlkäy: Umlwäl umlinterploate: "UnIcöDe {{ UnicoDict['Umlkäy'] }}" # UnicoDict.Umlkäy will NOT work! Röm: pîine prăjită şi ţuică kor: 韓國語똥 hiyapyco-release-0.7.0/test/lib/000077500000000000000000000000001470510053100165025ustar00rootroot00000000000000hiyapyco-release-0.7.0/test/lib/testsetup.py000066400000000000000000000022501470510053100211130ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu import logging import argparse class LoggingAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): # print '%r %r %r' % (namespace, values, option_string) logger = logging.getLogger() logger.setLevel(values) setattr(namespace, self.dest, values) def setup_parser(args): try: # python 3.4 up ... loggingchoices = logging._nameToLevel.keys() except AttributeError: loggingchoices = [k for k in logging._levelNames.keys() if isinstance(k, str)] parser = argparse.ArgumentParser() parser.add_argument( '-l', '--loglevel', help='set loglevel', type=str, choices=loggingchoices, action=LoggingAction ) return parser.parse_args(args) def setup(args): logger = logging.getLogger() logging.basicConfig( level=logging.WARN, format='%(levelname)s\t[%(name)s] %(funcName)s: %(message)s' ) args = setup_parser(args) if args.loglevel is None: logging.disable(logging.CRITICAL) return logger hiyapyco-release-0.7.0/test/m.yaml000066400000000000000000000000471470510053100170550ustar00rootroot00000000000000m: - a - b - c hiyapyco-release-0.7.0/test/m1.yaml000066400000000000000000000000101470510053100171240ustar00rootroot00000000000000m1: abc hiyapyco-release-0.7.0/test/m2.yaml000066400000000000000000000000101470510053100171250ustar00rootroot00000000000000m2: xyz hiyapyco-release-0.7.0/test/m3.yaml000066400000000000000000000000101470510053100171260ustar00rootroot00000000000000m3: 123 hiyapyco-release-0.7.0/test/m4.yaml000066400000000000000000000000501470510053100171330ustar00rootroot00000000000000m: - d - e - f hiyapyco-release-0.7.0/test/mo1.yaml000066400000000000000000000001311470510053100173070ustar00rootroot00000000000000depends: lib2: "2.0.0" #lib3: ">3" lib4: ">2" not_semver: a bypass: lib1: "2.0.0"hiyapyco-release-0.7.0/test/mo2.yaml000066400000000000000000000001541470510053100173150ustar00rootroot00000000000000depends: lib1: ">=2.0.0" lib2: "1.3.4" #lib3: "2.7" lib4: ">1" not_semver: b bypass: lib1: "1.0.0"hiyapyco-release-0.7.0/test/multiple.yaml000066400000000000000000000001611470510053100204510ustar00rootroot00000000000000--- a: aaa b: bbb d: a: a b: b c: c ... --- a: xxx d: a: x z: z ... hiyapyco-release-0.7.0/test/odict.yaml000066400000000000000000000007371470510053100177310ustar00rootroot00000000000000# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent source: domain: nowhere.example.net domainDN: dc={{ source.domain.split('.')|join(',dc=') }} baseDN: ou=Users,{{ source.domainDN }} bindDN: cn=Administrator,{{ source.baseDN }} destination: domain: somewhere.example.net domainDN: dc={{ destination.domain.split('.')|join(',dc=') }} baseDN: ou=Users,{{ destination['domainDN'] }} bindDN: cn=Administrator,{{ destination.baseDN }} hiyapyco-release-0.7.0/test/odyl.yaml000066400000000000000000000006211470510053100175660ustar00rootroot00000000000000eins: a: xxx b: zzz z: yyy c: aaa zwo: x: one y: two a: 3 deep: X: x: 1 a: 2 z: 3 b: 4 Y: False A: z: 1 a: 2 deep: XXX: 1 AAA: 2 ZZZ: 3 hiyapyco-release-0.7.0/test/requirements.txt000066400000000000000000000000601470510053100212140ustar00rootroot00000000000000# test/test_mergeoverride.py semantic-version>2 hiyapyco-release-0.7.0/test/test_anchoralias.py000077500000000000000000000035731470510053100216440ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco import yaml sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) logger.info('test anchoralias merge ...') conf = hiyapyco.load( os.path.join(basepath, 'anchoralias.yaml'), os.path.join(basepath, 'anchoralias2.yaml'), method=hiyapyco.METHOD_MERGE, failonmissingfiles=True, usedefaultyamlloader=True ) #print(hiyapyco.dump(conf)) t = conf['testvar']['simple'] logger.info('test simple ... %s' % t) assert t == 'new text' #print(conf['testvar']['list']) t = conf['testvar']['list'] logger.info('test list ... %s' % t) assert t == [{'alist1key': 'another value for alistkey1'}, {'alist2key': 'alist2val'}, {'alist3key': 'alist3val'}] #print(conf['testvar']['listwithmerge']) t = conf['testvar']['listwithmerge'] logger.info('test listwithmerge ... %s' % t) assert t == {'alist1key': 'alist1val now updated', 'alist3key': 'alist3val', 'alist2key': 'alist2val'} #print(conf['testvar']['dict']) t = conf['testvar']['dict'] logger.info('test dict ... %s' % t) assert t == {'adkey1': 'aaa1aa', 'adkey2': 'ad value 2', 'adkey3': 'xxx'} #print(conf['testvar']['dictwithmerge']) t = conf['testvar']['dictwithmerge'] logger.info('test dictwithmerge ... %s' % t) assert t == {'adkey1': 'ad value 1', 'adkey2': 'bb2bb', 'adkey3': 'yyy'} print('passed test %s' % __file__) hiyapyco-release-0.7.0/test/test_castinterpolated.py000077500000000000000000000033131470510053100227150ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) yamlfile = os.path.join(basepath, 'castinterpolated.yaml') logger.info('test uncasted ...') conf = hiyapyco.load( yamlfile, method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, interpolate=True, ) v = conf['three'] logger.info('test uncasted: %s (type: %s) ... ' % (v, type(v),)) assert v == '3' v = conf['c'] logger.info('test uncasted: %s (type: %s) ... ' % (v, type(v),)) assert v == '5.9' v = conf['bool'] logger.info('test uncasted: %s (type: %s) ... ' % (v, type(v),)) assert v == 'True' conf = hiyapyco.load( yamlfile, method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, interpolate=True, castinterpolated=True, ) v = conf['three'] logger.info('test casted: %s (type: %s) ... ' % (v, type(v),)) assert v == 3 v = conf['c'] logger.info('test casted: %s (type: %s) ... ' % (v, type(v),)) assert v == 5.9 v = conf['bool'] logger.info('test casted: %s (type: %s) ... ' % (v, type(v),)) assert v == True # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/test_custom_yaml_loader.py000066400000000000000000000017511470510053100232330ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.dirname(basepath)) import hiyapyco sys.path.insert( 0, os.path.join( os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))), "lib" ), ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print( "start test %s for hiyapyco %s using python %s (loglevel:%s)" % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()), ) ) logger.info("test custom yaml loader ...") def custom_loader(stream): """Mock loader that doesn't actually read the yaml file""" return [{"custom_yaml": 42}] conf = hiyapyco.load(os.path.join(basepath, "base.yaml"), loader_callback=custom_loader) assert conf == {"custom_yaml": 42} print("passed test %s" % __file__) hiyapyco-release-0.7.0/test/test_interpolation.py000077500000000000000000000057151470510053100222470ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco from jinja2 import Environment, Undefined, DebugUndefined, StrictUndefined, UndefinedError sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) logger.info('test simple vals ...') conf = hiyapyco.load( os.path.join(basepath, 'interpolate.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, interpolate=True ) t1 = conf.get('first') t2 = conf.get('firstcopy') t3 = conf['second'] logger.info('test first interpolation ... %s : %s' % (t1, t2,)) assert t1 == t2 logger.info('test second interpolation ... %s : %s' % (t1, t3,)) assert t3 == 'again %s' % t1 t = conf.get('list') logger.info('test interpolation in list ... %s' % t) assert t == ['abc', 'bcd', 'cde', 'abc'] t = conf['elist'] logger.info('test elist ... %s' % t) assert t is None t = conf['deep']['interp'] logger.info('test deep interpolation ... %s' % t) assert t == {'str': '10 + 23', 'sum': '33', 'join': 'ali baba and the 40 thieves'} t = conf['m'] logger.info('test more interpolation ... %s' % t) assert t == [{'a': 'A', 'b': '', 'c': 'ALI BABA'}, {'a': 'B', 'b': 'again first element', 'c': 'C & {{ m.0.a }}'}, {'a': 'C & A', 'b': 'cc', 'c': 'ccc'}] logger.info('test StrictUndefined ...') hiyapyco.jinja2env = Environment(undefined=StrictUndefined) try: conf = hiyapyco.HiYaPyCo( os.path.join(basepath, 'interpolate.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, interpolate=True ) except hiyapyco.HiYaPyCoImplementationException as e: logger.info('test UndefinedError: "%s"' % e) undefmsg = '\'undefined\' is undefined' hiyapmsg = 'error interpolating string "{{ undefined }}"' assert '%s' % e == '%s : %s' % (hiyapmsg, undefmsg,) or '%s' % e == '%s : b"%s"' % (hiyapmsg, undefmsg,) logger.info('test DebugUndefined ...') hiyapyco.jinja2env = Environment(undefined=DebugUndefined) conf = hiyapyco.load( os.path.join(basepath, 'interpolate.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, interpolate=True ) t = conf['m'] logger.info('test debugundefined interpolation ... %s' % t) assert t == [{'a': 'A', 'b': '{{ undefined }}', 'c': 'ALI BABA'}, {'a': 'B', 'b': 'again first element', 'c': 'C & {{ m.0.a }}'}, {'a': 'C & A', 'b': 'cc', 'c': 'ccc'}] print('passed test %s' % __file__) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/test_interpolationunicode.py000077500000000000000000000033061470510053100236100ustar00rootroot00000000000000#! /usr/bin/env python # vim: set fileencoding=utf-8 from __future__ import unicode_literals import sys import os import logging import platform import hiyapyco from jinja2 import Environment, Undefined, DebugUndefined, StrictUndefined, UndefinedError sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) logger.info('test simple vals ...') conf = hiyapyco.load( os.path.join(basepath, 'interpolateunicode.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, interpolate=True ) t = conf['one'] logger.info('test unicode val ... %s' % t) assert t == 'Öns' t = conf['oneKorean'] logger.info('test unicode val ... %s' % t) assert t == '하나' t = conf['Zwö'] logger.info('test unicode key ... %s' % t) assert t == 'ölybaba Öns zwö ... 40' t = conf['UnicoDict'] logger.info('test unicode dict ... %s' % t) assert t == { 'Umlkäy': 'Umlwäl', 'umlinterploate': 'UnIcöDe Umlwäl'} t = conf['Röm'] logger.info('test Röm: \'%s\'' % t) assert t == 'pîine prăjită şi ţuică' t = conf['kor'] logger.info('test kor: \'%s\'' % t) assert t == '韓國語똥' print('passed test %s' % __file__) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/test_invocation.py000077500000000000000000000114511470510053100215230ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) logger.info('basic invocation test ...') conf = hiyapyco.HiYaPyCo( os.path.join(basepath, 'base.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True ) logger.info('test kwarg nonbool ...') try: conf = hiyapyco.HiYaPyCo( os.path.join(basepath, 'base.yaml'), interpolate='ABC' ) raise Exception('we should newer get here: missing exception') except hiyapyco.HiYaPyCoInvocationException as e: assert str(e).startswith('value of "interpolate" must be boolean') try: conf = hiyapyco.HiYaPyCo( os.path.join(basepath, 'base.yaml'), usedefaultyamlloader='ABC' ) raise Exception('we should newer get here: missing exception') except hiyapyco.HiYaPyCoInvocationException as e: assert str(e).startswith('value of "usedefaultyamlloader" must be boolean') try: conf = hiyapyco.HiYaPyCo( os.path.join(basepath, 'base.yaml'), failonmissingfiles='ABC' ) raise Exception('we should newer get here: missing exception') except hiyapyco.HiYaPyCoInvocationException as e: assert str(e).startswith('value of "failonmissingfiles" must be boolean') logger.info('test undef kwarg ...') try: conf = hiyapyco.HiYaPyCo(x=1) raise Exception('we should newer get here: missing exception') except hiyapyco.HiYaPyCoInvocationException as e: assert '%s' % e == 'undefined keywords: x' logger.info('test methods ...') try: conf = hiyapyco.HiYaPyCo(method=666) raise Exception('we should newer get here: missing exception') except hiyapyco.HiYaPyCoInvocationException as e: assert '%s' % e == 'undefined method used, must be one of: %s' % ' '.join(hiyapyco.METHODS.keys()) logger.info('test no yaml defined ...') try: conf = hiyapyco.HiYaPyCo() raise Exception('we should newer get here: missing exception') except hiyapyco.HiYaPyCoInvocationException as e: assert '%s' % e == 'no yaml files defined' logger.info('test normal file list ...') conf = hiyapyco.load( os.path.join(basepath, 'base.yaml'), os.path.join(basepath, 'baseext.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True ) logger.info('test files as list ...') conf = hiyapyco.load( [ os.path.join(basepath, 'base.yaml'), os.path.join(basepath, 'baseext.yaml') ], method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True ) logger.info('test yaml doc as str ...') y1 = """ --- yaml: from str 1 h: y1: abc y2: xyz l: - l1 - l2 """ y2 = """ --- yaml: from str 2 h: y1: ABC y3: DEF l: - lll """ conf = hiyapyco.load( y1, method=hiyapyco.METHOD_MERGE, failonmissingfiles=True ) assert conf == {'yaml': 'from str 1', 'h': {'y1': 'abc', 'y2': 'xyz'}, 'l': ['l1', 'l2']} conf = hiyapyco.load( y1, y2, method=hiyapyco.METHOD_MERGE, failonmissingfiles=True ) assert conf == {'yaml': 'from str 2', 'h': {'y1': 'ABC', 'y2': 'xyz', 'y3': 'DEF'}, 'l': ['l1', 'l2', 'lll']} conf = hiyapyco.load( [y1, y2,], method=hiyapyco.METHOD_MERGE, failonmissingfiles=True ) assert conf == {'yaml': 'from str 2', 'h': {'y1': 'ABC', 'y2': 'xyz', 'y3': 'DEF'}, 'l': ['l1', 'l2', 'lll']} logger.info('test default yaml loader ...') conf = hiyapyco.load( y1, method=hiyapyco.METHOD_MERGE, usedefaultyamlloader=True, failonmissingfiles=True ) assert conf == {'yaml': 'from str 1', 'h': {'y1': 'abc', 'y2': 'xyz'}, 'l': ['l1', 'l2']} conf = hiyapyco.load( y1, y2, method=hiyapyco.METHOD_MERGE, usedefaultyamlloader=True, failonmissingfiles=True ) assert conf == {'yaml': 'from str 2', 'h': {'y1': 'ABC', 'y2': 'xyz', 'y3': 'DEF'}, 'l': ['l1', 'l2', 'lll']} conf = hiyapyco.load( [y1, y2,], method=hiyapyco.METHOD_MERGE, usedefaultyamlloader=True, failonmissingfiles=True ) assert conf == {'yaml': 'from str 2', 'h': {'y1': 'ABC', 'y2': 'xyz', 'y3': 'DEF'}, 'l': ['l1', 'l2', 'lll']} print('passed test %s' % __file__) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/test_merge.py000077500000000000000000000151021470510053100204460ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) logger.info('test substitute vals ...') conf = hiyapyco.load( os.path.join(basepath, 'base.yaml'), os.path.join(basepath, 'baseext.yaml'), method=hiyapyco.METHOD_SUBSTITUTE, failonmissingfiles=True ) t = conf['singel'] logger.info('test single val ... %s' % t) assert t == 'ext' t = conf['int'] logger.info('test int val ... %s' % t) assert t == 10 t = conf['array'] logger.info('test list val ... %s' % t) assert t == ['baseext1', 'baseext2'] t = conf['hash'] logger.info('test simple dict ... %s' % t) assert t == {'k1': 'b1', 'k2': 'b2', 'ek1': 'be1', 'ek2': 'be2'} t = conf['deeplist'] logger.info('test deeplist ... %s' % t) assert t == [{'d1': {'d1ext': 'vext'}}, {'dext1': {'d1k1ext': 'v1ext'}}, {'d31': {'a': 'AAA'}, 'd32': {'a': 'A2A2', 'c': 'CCC'}}] t = conf.get('deepmap') logger.info('test deepmap ... %s' % t) assert t == {'l1k1' : {'l2k1': 'overwr', 'l2k2': 'abc', 'l2k3': 'new val'}, 'l1k2': {'l2k1': 'bli', 'l2k2': 'bla', 'l2k3': 'blub'}, 'l1k1ext': {'l2k1ext': 'ext'}} t = conf['ext'] logger.info('test extonly ... %s' % t) assert t == 'extendet only' t = conf['missing_key'] logger.info('test missing_key ... %s' % t) assert t == 'one' t = conf['missing_key_parent'] logger.info('test missing_key_parent ... %s' % t) assert t == {'a': 'b'} t = conf['common_key'] logger.info('test common_key ... %s' % t) assert t == {'common_subkey_deep': 'oneext', 'missing_key_base': 'val2', 'missing_key_ext': 'val2missingInBase'} logger.info('test simple vals ...') conf = hiyapyco.load( os.path.join(basepath, 'base.yaml'), os.path.join(basepath, 'baseext.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True ) t = conf['singel'] logger.info('test single val ... %s' % t) assert t == 'ext' t = conf['int'] logger.info('test int val ... %s' % t) assert t == 10 t = conf['array'] logger.info('test list val ... %s' % t) assert t == ['baseext1', 'baseext2'] t = conf['hash'] logger.info('test simple dict ... %s' % t) assert t == {'ek1': 'be1', 'ek2': 'be2'} t = conf['deeplist'] logger.info('test deeplist ... %s' % t) assert t == [{'d1': {'d1ext': 'vext'}}, {'dext1': {'d1k1ext': 'v1ext'}}, {'d32': {'a': 'A2A2', 'c': 'CCC'}, 'd31': {'a': 'AAA'}}] t = conf['deepmap'] logger.info('test deepmap ... %s' % t) assert t == {'l1k1': {'l2k1': 'overwr', 'l2k3': 'new val'}, 'l1k1ext': {'l2k1ext': 'ext'}} t = conf['ext'] logger.info('test extonly ... %s' % t) assert t == 'extendet only' try: conf['nosuchelement'] raise Error except KeyError as e: assert '%s' % e == '\'nosuchelement\'' logger.info('test merged vals ...') conf = hiyapyco.load( os.path.join(basepath, 'base.yaml'), os.path.join(basepath, 'baseext.yaml'), method=hiyapyco.METHOD_MERGE, failonmissingfiles=True ) t = conf['singel'] logger.info('test single val ... %s' % t) assert t == 'ext' t = conf['int'] logger.info('test int val ... %s' % t) assert t == 10 t = conf['array'] logger.info('test list val ... %s' % t) assert t == ['base1', 'base2', 'baseext1', 'baseext2'] t = conf['hash'] logger.info('test simple dict ... %s' % t) assert t == {'k1': 'b1', 'k2': 'b2', 'ek1': 'be1', 'ek2': 'be2'} t = conf['deeplist'] logger.info('test deeplist ... %s' % t) assert t == [{'d1': {'d1k1': 'v1', 'd1k2': 'v2', 'd1ext': 'vext'}}, {'d2': {'d2k2': 'x2', 'd2k1': 'x1'}}, {'d32': {'a': 'A2A2', 'c': 'CCC', 'b': 'B2'}, 'd31': {'a': 'AAA', 'c': 'C', 'b': 'B'}}, {'dext1': {'d1k1ext': 'v1ext'}}] t = conf.get('deepmap') logger.info('test deepmap ... %s' % t) assert t == {'l1k1' : {'l2k1': 'overwr', 'l2k2': 'abc', 'l2k3': 'new val'}, 'l1k2': {'l2k1': 'bli', 'l2k2': 'bla', 'l2k3': 'blub'}, 'l1k1ext': {'l2k1ext': 'ext'}} t = conf['ext'] logger.info('test extonly ... %s' % t) assert t == 'extendet only' t = conf['missing_key'] logger.info('test missing_key ... %s' % t) assert t == 'one' t = conf['missing_key_parent'] logger.info('test missing_key_parent ... %s' % t) assert t == {'a': 'b'} t = conf['common_key'] logger.info('test common_key ... %s' % t) assert t == {'common_subkey_deep': 'oneext', 'missing_key_base': 'val2', 'missing_key_ext': 'val2missingInBase'} try: conf['nosuchelement'] raise Error except KeyError as e: assert '%s' % e == '\'nosuchelement\'' logger.info("test none behavior DEFAULT ...") for method in [hiyapyco.METHOD_MERGE, hiyapyco.METHOD_SUBSTITUTE]: try: conf = hiyapyco.load( os.path.join(basepath, "base.yaml"), os.path.join(basepath, "base_none_behavior.yaml"), method=method, failonmissingfiles=True, ) except hiyapyco.HiYaPyCoImplementationException: pass else: raise AssertionError("Default None behavior is expected to fail on this merge") logger.info("test none behavior OVERRIDE ...") for method in hiyapyco.METHODS.values(): conf = hiyapyco.load( os.path.join(basepath, "base.yaml"), os.path.join(basepath, "base_none_behavior.yaml"), none_behavior=hiyapyco.NONE_BEHAVIOR_OVERRIDE, method=hiyapyco.METHOD_MERGE, failonmissingfiles=True, ) t = conf["singel"] logger.info("test single val ... %s" % t) assert t is None t = conf["int"] logger.info("test int val ... %s" % t) assert t is None t = conf["array"] logger.info("test list val ... %s" % t) assert t is None t = conf["hash"] logger.info("test simple dict ... %s" % t) assert t is None t = conf["deeplist"] logger.info("test deeplist ... %s" % t) assert t == [ {"d1": None}, {"d2": {"d2k2": "x2", "d2k1": None}}, { "d32": {"a": "A2", "b": "B2"}, "d31": {"a": "A", "c": "C", "b": "B"}, }, ] t = conf["deepmap"] logger.info("test deepmap ... %s" % t) assert t == { "l1k1": {"l2k1": None, "l2k2": "abc"}, "l1k2": None, } print("passed test %s" % __file__) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/test_mergeoverride.py000077500000000000000000000043171470510053100222140ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco import semantic_version as semver sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) def semver_merge(a, b, context): if context[0] == 'bypass': return b if a is None or b is None: return b try: # We have to manually decompose these since lib doesn't appear to # have built in comparisons for one Spec against another (only Version) lhs = semver.SimpleSpec(a) rhs = semver.SimpleSpec(b) # TODO: Not always a Range clause lhs_target = lhs.clause.target rhs_target = rhs.clause.target if lhs_target > rhs_target: return a # DEBT: Crude elif (lhs.clause.operator == lhs.clause.OP_GT or lhs.clause.operator == lhs.clause.OP_GTE and rhs.clause.operator == rhs.clause.OP_EQ): return a return b except ValueError: return b logger.info('test merge override vals ...') h = hiyapyco.HiYaPyCo( os.path.join(basepath, 'mo1.yaml'), os.path.join(basepath, 'mo2.yaml'), method=hiyapyco.METHOD_MERGE, failonmissingfiles=True, mergeoverride=semver_merge ) conf = h.data() assert h.mergeprimitive is not None t = conf['depends'] t = t['lib1'] logger.info('test single val ... %s' % t) #assert t == { 'lib1': '>=2.0.0' } assert t == '>=2.0.0' t = conf['depends']['lib2'] assert t == '2.0.0' t = conf['bypass']['lib1'] assert t == '1.0.0' try: conf['nosuchelement'] raise Error except KeyError as e: assert '%s' % e == '\'nosuchelement\'' print('passed test %s' % __file__) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/test_missingfiles.py000077500000000000000000000103311470510053100220420ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) logger.info('test missing file w/ default value for failonmissingfiles ...') try: conf = hiyapyco.HiYaPyCo( os.path.join(basepath, 'base.yaml'), 'nosuchfile.yaml' ) raise Exception('we should newer get here: missing exception') except hiyapyco.HiYaPyCoInvocationException as e: assert '%s' % e == 'yaml file not found: \'nosuchfile.yaml\'' logger.info('test missing file as list w/ default value for failonmissingfiles ...') try: conf = hiyapyco.HiYaPyCo([ os.path.join(basepath, 'base.yaml'), 'nosuchfile.yaml', ]) raise Exception('we should newer get here: missing exception') except hiyapyco.HiYaPyCoInvocationException as e: assert '%s' % e == 'yaml file not found: \'nosuchfile.yaml\'' logger.info('test missing file w/ failonmissingfiles=False ...') conf = hiyapyco.HiYaPyCo( os.path.join(basepath, 'm.yaml'), 'nosuchfile.yaml', os.path.join(basepath, 'm1.yaml'), os.path.join(basepath, 'm2.yaml'), os.path.join(basepath, 'm3.yaml'), failonmissingfiles=False ) assert conf.yamlfiles() == [ os.path.join(basepath, 'm.yaml'), os.path.join(basepath, 'm1.yaml'), os.path.join(basepath, 'm2.yaml'), os.path.join(basepath, 'm3.yaml'), ] assert '%s' % conf == 'hiyapyco [%s]' % os.pathsep.join([ os.path.join(basepath, 'm.yaml'), os.path.join(basepath, 'm1.yaml'), os.path.join(basepath, 'm2.yaml'), os.path.join(basepath, 'm3.yaml'), ]) assert conf.data() == {'m': ['a', 'b', 'c'], 'm1': 'abc', 'm2': 'xyz', 'm3': 123} logger.info('test missing file as list w/ failonmissingfiles=False ...') conf = hiyapyco.HiYaPyCo( [ os.path.join(basepath, 'm.yaml'), 'nosuchfile.yaml', os.path.join(basepath, 'm1.yaml'), os.path.join(basepath, 'm2.yaml'), os.path.join(basepath, 'm3.yaml'), ], failonmissingfiles=False ) assert conf.yamlfiles() == [ os.path.join(basepath, 'm.yaml'), os.path.join(basepath, 'm1.yaml'), os.path.join(basepath, 'm2.yaml'), os.path.join(basepath, 'm3.yaml'), ] assert '%s' % conf == 'hiyapyco [%s]' % os.pathsep.join([ os.path.join(basepath, 'm.yaml'), os.path.join(basepath, 'm1.yaml'), os.path.join(basepath, 'm2.yaml'), os.path.join(basepath, 'm3.yaml'), ]) assert conf.data() == {'m': ['a', 'b', 'c'], 'm1': 'abc', 'm2': 'xyz', 'm3': 123} logger.info('test deep merge w/ missing file as list w/ failonmissingfiles=False ...') conf = hiyapyco.HiYaPyCo( [ os.path.join(basepath, 'm.yaml'), 'nosuchfile.yaml', os.path.join(basepath, 'm1.yaml'), os.path.join(basepath, 'm2.yaml'), os.path.join(basepath, 'm3.yaml'), os.path.join(basepath, 'm4.yaml'), ], failonmissingfiles=False, method=hiyapyco.METHOD_MERGE ) assert conf.yamlfiles() == [ os.path.join(basepath, 'm.yaml'), os.path.join(basepath, 'm1.yaml'), os.path.join(basepath, 'm2.yaml'), os.path.join(basepath, 'm3.yaml'), os.path.join(basepath, 'm4.yaml'), ] assert '%s' % conf == 'hiyapyco [%s]' % os.pathsep.join([ os.path.join(basepath, 'm.yaml'), os.path.join(basepath, 'm1.yaml'), os.path.join(basepath, 'm2.yaml'), os.path.join(basepath, 'm3.yaml'), os.path.join(basepath, 'm4.yaml'), ]) assert conf.data() == {'m': ['a', 'b', 'c', 'd', 'e', 'f'], 'm1': 'abc', 'm2': 'xyz', 'm3': 123} print('passed test %s' % __file__) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/test_multiple.py000077500000000000000000000033311470510053100212030ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) logger.info('test multiple yaml in one file w/ original yaml loader ...') conf = hiyapyco.load( os.path.join(basepath, 'multiple.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, usedefaultyamlloader=True ) t = conf['a'] logger.info('test single val ... %s' % t) assert t == 'xxx' t = conf['b'] logger.info('test single val ... %s' % t) assert t == 'bbb' t = conf['d'] logger.info('test dict val ... %s' % t) assert t == {'a' : 'x', 'z' : 'z'} logger.info('test multiple yaml in one file w/ odyldo ...') conf = hiyapyco.load( os.path.join(basepath, 'multiple.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, usedefaultyamlloader=False ) t = conf['a'] logger.info('test single val ... %s' % t) assert t == 'xxx' t = conf['b'] logger.info('test single val ... %s' % t) assert t == 'bbb' t = conf['d'] logger.info('test dict val ... %s' % t) assert t == {'a' : 'x', 'z' : 'z'} print('passed test %s' % __file__) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/test_odict.py000077500000000000000000000054241470510053100204570ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco from jinja2 import Environment, Undefined, DebugUndefined, StrictUndefined, UndefinedError sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) logger.info('test odict interploation using ODYLDo ...') conf = hiyapyco.load( os.path.join(basepath, 'odict.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, interpolate=True ) source_domain = conf['source']['domain'] source_domainDN = conf['source']['domainDN'] logger.info('test interpolation source_domainDN and source_domain ... %s : %s' % (source_domainDN, source_domain)) assert source_domainDN == 'dc=%s' % ',dc='.join(source_domain.split('.')) source_baseDN = conf['source']['baseDN'] logger.info('test interpolation source_baseDN ... %s' % source_baseDN) assert source_baseDN == 'ou=Users,%s' % source_domainDN source_bindDN = conf['source']['bindDN'] logger.info('test interpolation source_bindDN ... %s' % source_bindDN) assert source_bindDN == 'cn=Administrator,%s' % source_baseDN logger.info('test odict interploation using default yaml and StrictUndefined ...') hiyapyco.jinja2env = Environment(undefined=StrictUndefined) # this should NOT raise a UndefinedError, but interpolation will fail! conf = hiyapyco.load( os.path.join(basepath, 'odict.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True, interpolate=True, usedefaultyamlloader=True ) source_domain = conf['source']['domain'] source_domainDN = conf['source']['domainDN'] logger.info('test interpolation source_domainDN and source_domain ... %s : %s' % (source_domainDN, source_domain)) assert source_domainDN == 'dc=%s' % ',dc='.join(source_domain.split('.')) # FIXME: yaml loader seems to have changed ... """ source_baseDN = conf['source']['baseDN'] logger.info('test interpolation source_baseDN ... %s' % source_baseDN) assert source_baseDN == 'ou=Users,%s' % "dc={{ source.domain.split('.')|join(',dc=') }}" source_bindDN = conf['source']['bindDN'] logger.info('test interpolation source_bindDN ... %s' % source_bindDN) assert source_bindDN == 'cn=Administrator,%s' % 'ou=Users,{{ source.domainDN }}' """ print('passed test %s' % __file__) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu hiyapyco-release-0.7.0/test/test_simple.py000077500000000000000000000035711470510053100206470ustar00rootroot00000000000000#! /usr/bin/env python import sys import os import logging import platform import hiyapyco sys.path.insert( 0, os.path.join( os.path.dirname( os.path.realpath(os.path.abspath(sys.argv[0])) ), 'lib' ) ) import testsetup logger = testsetup.setup(sys.argv[1:]) basepath = os.path.dirname(os.path.realpath(__file__)) print('start test %s for hiyapyco %s using python %s (loglevel:%s)' % ( __file__, hiyapyco.__version__, platform.python_version(), logging.getLevelName(logger.getEffectiveLevel()) ) ) logger.info('test simple vals ...') conf = hiyapyco.load( os.path.join(basepath, 'base.yaml'), method=hiyapyco.METHOD_SIMPLE, failonmissingfiles=True ) t = conf['singel'] logger.info('test single val ... %s' % t) assert t == 'base' t = conf['int'] logger.info('test int val ... %s' % t) assert t == 1 t = conf['array'] logger.info('test list val ... %s' % t) assert t == ['base1', 'base2'] t = conf['hash'] logger.info('test simple dict ... %s' % t) assert t == {'k1': 'b1', 'k2': 'b2'} t = conf['deeplist'] logger.info('test deeplist ... %s' % t) assert t == [{'d1': {'d1k1': 'v1', 'd1k2': 'v2'}}, {'d2': {'d2k2': 'x2', 'd2k1': 'x1'}}, {'d32': {'a': 'A2', 'b': 'B2'}, 'd31': {'a': 'A', 'c': 'C', 'b': 'B'}}] t = conf['deepmap'] logger.info('test deepmap ... %s' % t) assert t == {'l1k1' : {'l2k1': 'xyz', 'l2k2': 'abc'}, 'l1k2': {'l2k1': 'bli', 'l2k2': 'bla', 'l2k3': 'blub'}} t = conf.get('nosuchelement', 'default value') logger.info('test default value ... %s' % t) assert t == 'default value' try: conf['nosuchelement'] raise Error except KeyError as e: assert '%s' % e == '\'nosuchelement\'' print('passed test %s' % __file__) # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smartindent nu