Compare commits
61 commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9f831f56ac | |||
| c317792292 | |||
| a051c1e713 | |||
| 3fa7beafd6 | |||
| 8ac603100d | |||
| 2f7711d989 | |||
| be491bfdb2 | |||
| dcc42a4ea0 | |||
| d90a0c0066 | |||
| ad1928bc88 | |||
| f65b168c21 | |||
| 5f9c79664f | |||
| 3986026f3b | |||
| 406f2121db | |||
| a6dfcbde4c | |||
| 00c4391ac6 | |||
| 6670aa64a2 | |||
| 2d9298eb8e | |||
| 7c69ac9557 | |||
| 22348f71e6 | |||
| 6830437805 | |||
| 06fcd1cef7 | |||
| a1dedb1c12 | |||
| 4da9a50265 | |||
| cdb62e5509 | |||
| 086667d7a4 | |||
| 7d77da836a | |||
| c4d1f6853c | |||
| 04bf6a1d38 | |||
| e518abb734 | |||
| d2195d31a9 | |||
| f4503f3b10 | |||
| 8550a125a1 | |||
| e99d0fde3c | |||
| aaf832c12d | |||
| d360203bf8 | |||
| 29cabb37c2 | |||
| ee9d0b388a | |||
| 3177d11f13 | |||
| b4b058afd8 | |||
| 3741a0b548 | |||
| 4017bf7840 | |||
| db565527ec | |||
|
|
6eafc16adb | ||
| 7fcf5d6fc9 | |||
| b112503def | |||
| cd0187d328 | |||
| 560deb52b6 | |||
| 085840449c | |||
|
|
d5661511da | ||
|
|
b6a814fbc0 | ||
|
|
ad0e809bc9 | ||
|
|
d2527f6353 | ||
| 5668520a31 | |||
| e0e6597955 | |||
| 13aedef773 | |||
| 59d12a3624 | |||
|
|
bc4420bdea | ||
| 0d66bffd2f | |||
| 887f8aea9d | |||
| f1a8f61347 |
4099 changed files with 22935 additions and 45764 deletions
47
.pre-commit-config.yaml
Normal file
47
.pre-commit-config.yaml
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v2.3.0
|
||||
hooks:
|
||||
- id: check-yaml
|
||||
- id: end-of-file-fixer
|
||||
- id: trailing-whitespace
|
||||
- id: check-ast
|
||||
- id: check-added-large-files
|
||||
- id: check-json
|
||||
- id: check-executables-have-shebangs
|
||||
- id: check-symlinks
|
||||
|
||||
- repo: https://github.com/psf/black
|
||||
rev: 22.10.0
|
||||
hooks:
|
||||
- id: black
|
||||
|
||||
# - repo: https://github.com/hhatto/autopep8
|
||||
# rev: v2.0.4
|
||||
# hooks:
|
||||
# - id: autopep8
|
||||
|
||||
# - repo: https://github.com/pre-commit/mirrors-mypy
|
||||
# rev: v1.6.1
|
||||
# hooks:
|
||||
# - id: mypy
|
||||
|
||||
# - repo: https://github.com/PyCQA/pylint
|
||||
# rev: v3.0.2
|
||||
# hooks:
|
||||
# - id: pylint
|
||||
|
||||
# - repo: https://github.com/PyCQA/isort
|
||||
# rev: 5.11.5
|
||||
# hooks:
|
||||
# - id: isort
|
||||
|
||||
# - repo: https://github.com/motet-a/jinjalint
|
||||
# rev: 0.5
|
||||
# hooks:
|
||||
# - id: jinjalint
|
||||
|
||||
# - repo: https://github.com/rstcheck/rstcheck
|
||||
# rev: v6.2.0
|
||||
# hooks:
|
||||
# - id: rstcheck
|
||||
57
CHANGELOG.md
57
CHANGELOG.md
|
|
@ -1,3 +1,60 @@
|
|||
## 1.1.1 (2024-11-06)
|
||||
|
||||
### Fix
|
||||
|
||||
- upgrade tests
|
||||
|
||||
## 1.1.1rc0 (2024-11-06)
|
||||
|
||||
### Fix
|
||||
|
||||
- update tiramisu dependency
|
||||
- better user information if a needed package is not installed
|
||||
- **37**: import doesn't works for some python version
|
||||
- **36**: format 1.0: suffix attribut must works
|
||||
- update fr/rougail.mo
|
||||
|
||||
## 1.1.0 (2024-11-01)
|
||||
|
||||
### Fix
|
||||
|
||||
- black
|
||||
- add changelog_merge_prerelease to commitizen
|
||||
|
||||
## 1.1.0rc0 (2024-11-01)
|
||||
|
||||
### Feat
|
||||
|
||||
- update dependencies
|
||||
- translation
|
||||
- in calculation better debugging
|
||||
- can sort dictionaries in different directories
|
||||
- suffix to identifier
|
||||
- better errors messages and improvement
|
||||
- better debugging
|
||||
- update upgrade module
|
||||
- auto add multi for leader
|
||||
- use suffix in property calculation
|
||||
- in structural commandline very is there is conflict alternative name
|
||||
- **#21**: add examples attributes
|
||||
- **#23**: define easily a regexoption
|
||||
- add relative path support
|
||||
- add default inference for basic types
|
||||
- suffixes in dynamic family should be a jinja function (#5)
|
||||
- we should be able to customize a new variable type
|
||||
|
||||
### Fix
|
||||
|
||||
- support for unknown language
|
||||
- license
|
||||
- README
|
||||
- use black
|
||||
- valid mode even if there is no mode configured
|
||||
- valid mode if no mode defined
|
||||
- update tests
|
||||
- type is not always mandatory
|
||||
- auto_save in follower is now allowed in tiramisu
|
||||
|
||||
## 1.0.2 (2024-01-28)
|
||||
|
||||
### Fix
|
||||
|
|
|
|||
388
LICENSE
388
LICENSE
|
|
@ -1,235 +1,165 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||
0. Additional Definitions.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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.
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||
|
||||
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 AGPL, see <http://www.gnu.org/licenses/>.
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser 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
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
|
|
|
|||
37
README.md
37
README.md
|
|
@ -28,20 +28,27 @@ Create the file `dict/dictionary.yml`:
|
|||
|
||||
```yml
|
||||
---
|
||||
version: '1.0'
|
||||
version: 1.1
|
||||
# describe a variable my_first_variable
|
||||
# and a family with a variable my_second_variable
|
||||
my_first_variable:
|
||||
default: my_value
|
||||
my_first_variable: my_value
|
||||
my_family:
|
||||
my_second_variable:
|
||||
type: number
|
||||
mandatory: true
|
||||
value: 1
|
||||
my_second_variable: 1
|
||||
```
|
||||
|
||||
## Generate variable
|
||||
|
||||
### With commandline:
|
||||
|
||||
```bash
|
||||
# rougail -m dict
|
||||
Variables:
|
||||
┣━━ 📓 my_first_variable: my_value
|
||||
┗━━ 📂 my_family
|
||||
┗━━ 📓 my_second_variable: 1
|
||||
|
||||
```
|
||||
|
||||
### With default value:
|
||||
|
||||
Here is a python3 example file:
|
||||
|
|
@ -51,19 +58,16 @@ from rougail import Rougail, RougailConfig
|
|||
from pprint import pprint
|
||||
|
||||
RougailConfig['dictionaries_dir'] = ['dict']
|
||||
RougailConfig['templates_dir'] = ['tmpl']
|
||||
RougailConfig['tmp_dir'] = 'tmp'
|
||||
RougailConfig['destinations_dir'] = 'dest'
|
||||
rougail = Rougail()
|
||||
config = rougail.get_config()
|
||||
config = rougail.run()
|
||||
pprint(config.value.get(), sort_dicts=False)
|
||||
```
|
||||
|
||||
The result is:
|
||||
|
||||
```json
|
||||
{'rougail.my_first_variable': 'my_value',
|
||||
'rougail.my_family.my_second_variable': 1}
|
||||
{<TiramisuOption path="rougail">: {<TiramisuOption path="rougail.my_first_variable">: 'my_value',
|
||||
<TiramisuOption path="rougail.my_family">: {<TiramisuOption path="rougail.my_family.my_second_variable">: 1}}}
|
||||
```
|
||||
|
||||
### With modified value
|
||||
|
|
@ -76,9 +80,6 @@ from rougail import Rougail, RougailConfig
|
|||
from pprint import pprint
|
||||
|
||||
RougailConfig['dictionaries_dir'] = ['dict']
|
||||
RougailConfig['templates_dir'] = ['tmpl']
|
||||
RougailConfig['tmp_dir'] = 'tmp'
|
||||
RougailConfig['destinations_dir'] = 'dest'
|
||||
rougail = Rougail()
|
||||
config = rougail.get_config()
|
||||
config.option('rougail.my_first_variable').value.set('modified_value')
|
||||
|
|
@ -89,8 +90,8 @@ pprint(config.value.get(), sort_dicts=False)
|
|||
The destination file is generated with new values:
|
||||
|
||||
```json
|
||||
{'rougail.my_first_variable': 'modified_value',
|
||||
'rougail.my_family.my_second_variable': 2}
|
||||
{<TiramisuOption path="rougail">: {<TiramisuOption path="rougail.my_first_variable">: 'modified_value',
|
||||
<TiramisuOption path="rougail.my_family">: {<TiramisuOption path="rougail.my_family.my_second_variable">: 2}}}
|
||||
```
|
||||
|
||||
# Link
|
||||
|
|
|
|||
|
|
@ -117,7 +117,7 @@ Here is a simple example of validating values:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
validators:
|
||||
- type: jinja
|
||||
|
|
@ -142,7 +142,7 @@ In the constraint, it is possible to specify the error level and put it as a war
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
validators:
|
||||
- type: jinja
|
||||
|
|
@ -161,7 +161,7 @@ Verification with parameters
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_hidden_variable:
|
||||
disabled: true
|
||||
my_variable:
|
||||
|
|
@ -189,7 +189,7 @@ An example with a suffix type parameter:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
varname:
|
||||
multi: true
|
||||
default:
|
||||
|
|
@ -221,7 +221,7 @@ An example with an index type parameter:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
family:
|
||||
type: leadership
|
||||
leader:
|
||||
|
|
@ -249,7 +249,7 @@ In a first dictionary, let's declare our variable and its verification function:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
validators:
|
||||
- type: jinja
|
||||
|
|
@ -263,7 +263,7 @@ In a second dictionary it is possible to redefine the calculation:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
redefine: true
|
||||
validators:
|
||||
|
|
@ -280,7 +280,7 @@ Here is a third dictionary in which we remove the validation:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
redefine: true
|
||||
validators:
|
||||
|
|
|
|||
|
|
@ -177,7 +177,7 @@ It is possible to write the condition in Jinja:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
condition:
|
||||
default: 'do not hide!'
|
||||
my_variable:
|
||||
|
|
@ -213,7 +213,7 @@ A variable can therefore be calculated via the result of another variable. Pleas
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
condition:
|
||||
type: boolean
|
||||
my_variable:
|
||||
|
|
@ -233,7 +233,7 @@ To delete the calculation from a variable, simply do in a new dictionary:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
redefine: true
|
||||
hidden:
|
||||
|
|
|
|||
|
|
@ -14,3 +14,47 @@ This process describes how to install and run the project locally, e.g. for deve
|
|||
*Nota*: command is to be executed through the terminal
|
||||
|
||||
`pip install rougail`
|
||||
|
||||
Code quality
|
||||
---------------
|
||||
|
||||
We are using `pre-commit <https://pre-commit.com/>`_, there is a :file:`.pre-commit-config.yaml`
|
||||
pre-commit config file in the root's project.
|
||||
|
||||
You need to:
|
||||
|
||||
- install the pre-commit library::
|
||||
|
||||
pip install pre-commit
|
||||
|
||||
- registrer the pre-commit git hooks with this command::
|
||||
|
||||
pre-commit install
|
||||
|
||||
- launch the quality code procedure with::
|
||||
|
||||
pre-commit
|
||||
|
||||
or simply just commit your changes, pre-commit will automatically be launched.
|
||||
|
||||
.. attention:: If an error is found, the commit will not happen.
|
||||
You must resolve all errors that pre-commit that pre-commit points out to you before.
|
||||
|
||||
.. note:: If you need for some reason to disable `pre-commit`, just set
|
||||
the `PRE_COMMIT_ALLOW_NO_CONFIG` environment variable before commiting::
|
||||
|
||||
PRE_COMMIT_ALLOW_NO_CONFIG=1 git commit
|
||||
|
||||
Coding standard
|
||||
------------------
|
||||
|
||||
We use black
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
- repo: https://github.com/psf/black
|
||||
rev: 22.10.0
|
||||
hooks:
|
||||
- id: black
|
||||
|
||||
And some YAML and JSON validators.
|
||||
|
|
|
|||
119
docs/family.rst
119
docs/family.rst
|
|
@ -15,35 +15,52 @@ It is with this name that we will be able to interact with the family.
|
|||
|
||||
It's best to follow the :ref:`convention on variable names`.
|
||||
|
||||
Shorthand declaration
|
||||
----------------------------
|
||||
|
||||
Shorthand declaration is a way to declare a family in a single line. But you can only define family name and description.
|
||||
|
||||
To create a family, just add a key with it's name and variables as values. Attention, do not declare any other attributs.
|
||||
|
||||
By default, the description of the variable is the family name.
|
||||
If you add comment in same line of name, this comment is use as description:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.1'
|
||||
my_family: # This is a great family
|
||||
variable:
|
||||
|
||||
Parameters
|
||||
---------------
|
||||
|
||||
.. FIXME: faire une page sur la "convention on variable names"
|
||||
|
||||
.. list-table::
|
||||
.. list-table::
|
||||
:widths: 15 45
|
||||
:header-rows: 1
|
||||
|
||||
* - Parameter
|
||||
- Comments
|
||||
|
||||
|
||||
* - type, _type
|
||||
|
||||
`string`
|
||||
|
||||
|
||||
- possile values:
|
||||
|
||||
|
||||
- `family` (**default value**)
|
||||
- `leadership`
|
||||
- `dynamic`
|
||||
|
||||
|
||||
.. note:: If a subfamily or a subvariable already has the name `"type"`, it is possible to use the `"_type"` attribute.
|
||||
|
||||
* - description, _description
|
||||
|
||||
`string`
|
||||
- Description of the family.
|
||||
|
||||
|
||||
User information to understand the usefulness of the family.
|
||||
|
||||
..note:: If a subfamily or subvariable already has the name "description" it is possible to use the "_description" attribute.
|
||||
|
|
@ -53,7 +70,7 @@ Parameters
|
|||
`string`
|
||||
- Additional help associated with the family.
|
||||
|
||||
.. note:: If a subfamily or a subvariable already has the name "help" it is possible to use the "_help" attribute.
|
||||
.. note:: If a subfamily or a subvariable already has the name "help" it is possible to use the "_help" attribute.
|
||||
|
||||
* - mode, _mode
|
||||
|
||||
|
|
@ -61,30 +78,30 @@ Parameters
|
|||
- Family mode.
|
||||
|
||||
The default mode of a family is the smallest mode of the parent families, child variables, or child families that are contained in that family.
|
||||
|
||||
|
||||
This mode also allows you to define the default mode for variables or families included in this family.
|
||||
|
||||
|
||||
.. note:: If a subfamily or a subvariable already has the name "mode" it is possible to add the "_mode" attribute.
|
||||
|
||||
* - hidden, _hidden
|
||||
|
||||
`string`
|
||||
- Invisible family.
|
||||
|
||||
|
||||
Allows you to hide a family as well as the variables or families included in this family.
|
||||
|
||||
This means that the family will no longer be visible in `read-write` mode, but only for calculations or in `read-only` mode.
|
||||
|
||||
.. note:: If a subfamily or a subvariable already has the name "hidden" it is possible to add the "_hidden" attribute.
|
||||
.. note:: If a subfamily or a subvariable already has the name "hidden" it is possible to add the "_hidden" attribute.
|
||||
|
||||
* - disabled, _disabled
|
||||
|
||||
`string`
|
||||
|
||||
- Disabled family.
|
||||
|
||||
|
||||
Allows you to deactivate a family as well as the variables or families included in this family.
|
||||
|
||||
|
||||
This means that the family will no longer be visible to the user but also to a :term:`calculation`.
|
||||
|
||||
.. note:: If a subfamily or a subvariable already has the name "disabled" it is possible to use the "_disabled" attribute.
|
||||
|
|
@ -92,25 +109,18 @@ Parameters
|
|||
Dynamically created family
|
||||
-----------------------------
|
||||
|
||||
To create a family dynamically, you must create a fictitious family linked to a variable.
|
||||
The family name and description will actually be the prefix of the new name / description.
|
||||
The suffix will come from the value of the bound variable.
|
||||
The name of the families and variables it contains will be preserved, however, the description will be the prefix of the real description.
|
||||
To create a family dynamically, you must create a fictitious family linked to a calculation.
|
||||
The family name will actually be the prefix of the new name. Alternativly you can specify the suffix in the name, ie `my_{{ suffix }}_name`.
|
||||
The suffix will come from the calculation.
|
||||
|
||||
Obviously if the content of the linked variable were to evolve, new dynamic families will appear or disappear.
|
||||
Obviously if the result of calculation were to evolve, new dynamic families will appear or disappear.
|
||||
|
||||
To note that:
|
||||
|
||||
- the variable linked to the family must be a multiple variable
|
||||
- it is not possible to put a simple family into a dynamic family
|
||||
- it is possible to put a leading family into a dynamic family
|
||||
|
||||
Leader or foller variable
|
||||
Leader or follower variable
|
||||
-----------------------------
|
||||
|
||||
A leader family has a typical attribute of “leadership”. The type is required.
|
||||
|
||||
A leader family
|
||||
A leader family
|
||||
----------------
|
||||
|
||||
The leader and follower variables are placed in a leader family.
|
||||
|
|
@ -150,25 +160,25 @@ If a leader variable is hidden or disabled, the follower variables will be hidde
|
|||
Examples
|
||||
----------
|
||||
|
||||
Simple family
|
||||
Simple family:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_family:
|
||||
type: family
|
||||
description: This is a great family
|
||||
help: This is the help of a great family
|
||||
mode: expert
|
||||
|
||||
Dynamically created family
|
||||
Dynamically created family
|
||||
----------------------------
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
varname:
|
||||
multi: true
|
||||
default:
|
||||
|
|
@ -176,20 +186,50 @@ Dynamically created family
|
|||
- val2
|
||||
my_dyn_family_:
|
||||
type: dynamic
|
||||
variable: rougail.varname
|
||||
description: 'Describe '
|
||||
dynamic:
|
||||
type: variable
|
||||
variable: rougail.varname
|
||||
description: 'Describe'
|
||||
my_dyn_var:
|
||||
type: string
|
||||
description: 'Variable description for '
|
||||
description: 'Variable description'
|
||||
|
||||
This will dynamically create two families:
|
||||
|
||||
- "rougail.my_dyn_family_val1" with the description "Describe val1"
|
||||
- "rougail.my_dyn_family_val2" with the description "Describe val2"
|
||||
- "rougail.my_dyn_family_val1"
|
||||
- "rougail.my_dyn_family_val2"
|
||||
|
||||
In the dynamic family "rougail.my_dyn_family_val1" we will find a variable "my_dyn_var" with the description "Variable description for val1".
|
||||
In the dynamic family "rougail.my_dyn_family_val1" we will find a variable "my_dyn_var".
|
||||
|
||||
Leader or follower variable
|
||||
Here is a second example:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.1'
|
||||
varname:
|
||||
multi: true
|
||||
default:
|
||||
- val1
|
||||
- val2
|
||||
my_dyn_{{ suffix }}_family:
|
||||
type: dynamic
|
||||
dynamic:
|
||||
type: variable
|
||||
variable: rougail.varname
|
||||
description: 'Describe'
|
||||
my_dyn_var:
|
||||
type: string
|
||||
description: 'Variable description'
|
||||
|
||||
This will dynamically create two families:
|
||||
|
||||
- "rougail.my_dyn_val1_family"
|
||||
- "rougail.my_dyn_val2_family"
|
||||
|
||||
In the dynamic family "rougail.my_dyn_val1_family" we will find a variable "my_dyn_var".
|
||||
|
||||
Leader or follower variable
|
||||
-------------------------------
|
||||
|
||||
Definition of leader and follower variables
|
||||
|
|
@ -200,7 +240,7 @@ Here is an example of defining a leading variable and two following variables:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
family:
|
||||
type: leadership
|
||||
leader:
|
||||
|
|
@ -217,7 +257,6 @@ To add a new follower variable, in a new dictionary, simply define one or more n
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
family:
|
||||
follower3:
|
||||
|
||||
|
|
|
|||
167
docs/fill.rst
167
docs/fill.rst
|
|
@ -155,7 +155,88 @@ There are two types of parameter:
|
|||
`mandatory`
|
||||
- Name of the information whose value we want to retrieve.
|
||||
- doc
|
||||
|
||||
|
||||
The variable path
|
||||
-----------------
|
||||
|
||||
Normal family
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
The default namespace is defined in RougailConfig["variable_namespace"] with the default value "rougail".
|
||||
In addition, there are extras namespaces defined with in RougailConfig["extra_dictionaries"].
|
||||
|
||||
Inside those namespaces we can add families and variables.
|
||||
|
||||
Here is an hierarchic examples:
|
||||
|
||||
.. code-block::
|
||||
rougail
|
||||
├── variable1
|
||||
├── family1
|
||||
│ ├── variable2
|
||||
│ └── variable3
|
||||
└── family2
|
||||
└── subfamily1
|
||||
└── variable4
|
||||
extra1
|
||||
└── family3
|
||||
├── variable5
|
||||
└── variable6
|
||||
|
||||
In `calculation` we can use other variables.
|
||||
|
||||
Here is all paths:
|
||||
|
||||
- rougail.variable1
|
||||
- rougail.family1.variable2
|
||||
- rougail.family1.variable3
|
||||
- rougail.family2.subfamily1.variable4
|
||||
- extra1.family3.variable5
|
||||
- extra1.family3.variable6
|
||||
|
||||
Inside a variable's `calculation` we can use relative path. "_" means that other variable is in same family. "__" means that other variables are in parent family, and so on...
|
||||
|
||||
For example, in variable2's `calculation`, we can use relative path:
|
||||
|
||||
- __.variable1
|
||||
- _.variable3
|
||||
- __.family2.subfamily1.variable4
|
||||
|
||||
But we cannot access to extra1 variables with relative path.
|
||||
|
||||
Dynamic family
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Hire is a dynamic family "{{ suffix }}":
|
||||
|
||||
.. code-block::
|
||||
rougail
|
||||
├── variable1: ["val1", "val2"]
|
||||
├── {{ suffix }}
|
||||
│ ├── variable2
|
||||
│ └── variable3
|
||||
└── family
|
||||
└── variable4
|
||||
|
||||
For variable2's calculation, we can use:
|
||||
|
||||
- rougail.{{ suffix }}.variable3
|
||||
- _.variable3
|
||||
|
||||
In this case, we get value for "variable3" with the same suffix as "variable2".
|
||||
|
||||
For variable4's calculation, we have two possibility:
|
||||
|
||||
- retrieves all values with all suffixes:
|
||||
|
||||
- rougail.{{ suffix }}.variable3
|
||||
- __.{{ suffix }}.variable3
|
||||
|
||||
- retrieves a value for a specified suffix:
|
||||
|
||||
- rougail.val1.variable3
|
||||
- __.val1.variable3
|
||||
|
||||
Examples
|
||||
-----------
|
||||
|
||||
|
|
@ -167,7 +248,7 @@ Let's start with an example from a simple Jinja template:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_calculated_variable:
|
||||
default:
|
||||
type: jinja
|
||||
|
|
@ -178,7 +259,7 @@ Here is a second example with a boolean variable:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_calculated_variable:
|
||||
type: boolean
|
||||
default:
|
||||
|
|
@ -190,7 +271,7 @@ And a multiple value of the number type:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_calculated_variable:
|
||||
type: number
|
||||
multi: true
|
||||
|
|
@ -206,7 +287,7 @@ Let's create a variable whose value is returned by a python function:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_calculated_variable:
|
||||
default:
|
||||
type: jinja
|
||||
|
|
@ -224,7 +305,7 @@ An example with parameters:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_calculated_variable:
|
||||
description: my description
|
||||
default:
|
||||
|
|
@ -235,19 +316,19 @@ An example with parameters:
|
|||
param1: value
|
||||
param2:
|
||||
type: variable
|
||||
variable: rougail.unknown_variable
|
||||
variable: _.unknown_variable
|
||||
optional: true
|
||||
param3:
|
||||
type: information
|
||||
information: doc
|
||||
variable: rougail.my_calculated_variable
|
||||
variable: _.my_calculated_variable
|
||||
|
||||
An example with a `suffix` type parameter:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
varname:
|
||||
multi: true
|
||||
default:
|
||||
|
|
@ -255,7 +336,9 @@ An example with a `suffix` type parameter:
|
|||
- val2
|
||||
my_dyn_family_:
|
||||
type: dynamic
|
||||
variable: rougail.varname
|
||||
dynamic:
|
||||
type: variable
|
||||
variable: _.varname
|
||||
description: 'Describe '
|
||||
my_dyn_var:
|
||||
type: string
|
||||
|
|
@ -275,7 +358,7 @@ An example with an index type parameter:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
family:
|
||||
type: leadership
|
||||
leader:
|
||||
|
|
@ -299,7 +382,7 @@ Copy a variable in another:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
multi: true
|
||||
default:
|
||||
|
|
@ -309,14 +392,32 @@ Copy a variable in another:
|
|||
multi: true
|
||||
default:
|
||||
type: variable
|
||||
variable: rougail.my_variable
|
||||
variable: _.my_variable
|
||||
|
||||
Copy the default value from a variable, means copy type, params and multi attribute too if not define in second variable.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: 1.1
|
||||
my_variable:
|
||||
multi: true
|
||||
type: domainname
|
||||
params:
|
||||
allow_ip: true
|
||||
my_calculated_variable:
|
||||
default:
|
||||
type: variable
|
||||
variable: _.var1
|
||||
|
||||
Here my_calculated_variable is a domainname variable with parameter allow_ip=True and multi to true.
|
||||
|
||||
Copy one variable to another if the source has no `property` problem:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
default: val1
|
||||
disabled: true
|
||||
|
|
@ -324,7 +425,7 @@ Copy one variable to another if the source has no `property` problem:
|
|||
multi: true
|
||||
default:
|
||||
type: variable
|
||||
variable: rougail.my_variable
|
||||
variable: _.my_variable
|
||||
propertyerror: false
|
||||
|
||||
Copy two non-multiple variables into a multiple variable:
|
||||
|
|
@ -332,7 +433,7 @@ Copy two non-multiple variables into a multiple variable:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable_1:
|
||||
default: val1
|
||||
my_variable_2:
|
||||
|
|
@ -341,9 +442,9 @@ Copy two non-multiple variables into a multiple variable:
|
|||
multi: true
|
||||
default:
|
||||
- type: variable
|
||||
variable: rougail.my_variable_1
|
||||
variable: _.my_variable_1
|
||||
- type: variable
|
||||
variable: rougail.my_variable_2
|
||||
variable: _.my_variable_2
|
||||
|
||||
A variable in a dynamic family can also be used in a calculation.
|
||||
|
||||
|
|
@ -352,7 +453,7 @@ For example using the variable for a particular suffix:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
varname:
|
||||
multi: true
|
||||
default:
|
||||
|
|
@ -360,7 +461,9 @@ For example using the variable for a particular suffix:
|
|||
- val2
|
||||
my_dyn_family_:
|
||||
type: dynamic
|
||||
variable: rougail.varname
|
||||
dynamic:
|
||||
type: variable
|
||||
variable: _.varname
|
||||
description: 'Describe '
|
||||
my_dyn_var_:
|
||||
type: string
|
||||
|
|
@ -369,7 +472,7 @@ For example using the variable for a particular suffix:
|
|||
all_dyn_var:
|
||||
default:
|
||||
type: variable
|
||||
variable: rougail.my_dyn_family_val1.my_dyn_var_val1
|
||||
variable: _.my_dyn_family_val1.my_dyn_var_val1
|
||||
|
||||
In this case, we recover the value `val1`.
|
||||
|
||||
|
|
@ -378,7 +481,7 @@ Second example using the variable for all suffixes:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
varname:
|
||||
multi: true
|
||||
default:
|
||||
|
|
@ -386,7 +489,9 @@ Second example using the variable for all suffixes:
|
|||
- val2
|
||||
my_dyn_family_:
|
||||
type: dynamic
|
||||
variable: rougail.varname
|
||||
dynamic:
|
||||
type: variable
|
||||
variable: _.varname
|
||||
description: 'Describe '
|
||||
my_dyn_var_:
|
||||
type: string
|
||||
|
|
@ -396,7 +501,7 @@ Second example using the variable for all suffixes:
|
|||
multi: true
|
||||
default:
|
||||
type: variable
|
||||
variable: rougail.my_dyn_family_.my_dyn_var_
|
||||
variable: _.my_dyn_family_.my_dyn_var_
|
||||
|
||||
In this case, we recover the `val1` and `val2` list.
|
||||
|
||||
|
|
@ -406,7 +511,7 @@ Calculation via a suffix
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
varname:
|
||||
multi: true
|
||||
default:
|
||||
|
|
@ -414,7 +519,9 @@ Calculation via a suffix
|
|||
- val2
|
||||
my_dyn_family_:
|
||||
type: dynamic
|
||||
variable: rougail.varname
|
||||
dynamic:
|
||||
type: variable
|
||||
variable: _.varname
|
||||
description: 'Describe '
|
||||
my_dyn_var_:
|
||||
type: string
|
||||
|
|
@ -427,7 +534,7 @@ Calculation via an index
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
family:
|
||||
type: leadership
|
||||
leader:
|
||||
|
|
@ -448,7 +555,7 @@ In a first dictionary, let's declare our variable and our calculation:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_calculated_variable:
|
||||
default:
|
||||
type: jinja
|
||||
|
|
@ -459,7 +566,7 @@ In a second dictionary, it is possible to redefine the calculation:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_calculated_variable:
|
||||
redefine: true
|
||||
default:
|
||||
|
|
@ -471,7 +578,7 @@ In a third dictionary, we even can delete the calculation if needed:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_calculated_variable:
|
||||
redefine: true
|
||||
default: null
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ What is a consistency handling system ?
|
|||
|
||||
Tiramisu
|
||||
|
||||
|Tiramisu| is a consistency handling system that was initially designed
|
||||
|Tiramisu| is a consistency handling system that has initially been designed
|
||||
in the configuration management scope. To put it more simply,
|
||||
this library is generally used to handle configuration options.
|
||||
|
||||
|
|
@ -44,16 +44,16 @@ The dictionaries
|
|||
|
||||
.. image:: images/schema.png
|
||||
|
||||
The main advantage is that declaring variables and writing consistency is a simple
|
||||
as writing YAML. It is not necessary to write :term:`Tiramisu` code.
|
||||
The main advantage is that declaring variables and writing consistency is as simple
|
||||
as writing YAML. With Rougail it is not necessary to write :term:`Tiramisu` code any more.
|
||||
It simplifies a lot of things.
|
||||
|
||||
And rather than writing :term:`Tiramisu` code, we can declare variables and describe the relationships between variables in a declarative mode.
|
||||
And rather than writing :term:`Tiramisu` code, we can declare variables and describe the relationships between variables in a declarative mode (that is, in a YAML file).
|
||||
|
||||
Once the dictionaries are loaded by Rougail, we find all the power of the :term:`Tiramisu` configuration management tool.
|
||||
|
||||
The dictionaries YAML format
|
||||
---------------------------------
|
||||
The YAML dictionaries format
|
||||
-----------------------------
|
||||
|
||||
Before getting started with Rougail we need to learn the specifics of the YAML dictionaries file format (as well as some templating concepts).
|
||||
|
||||
|
|
@ -65,7 +65,7 @@ Here is a :term:`dictionary` example:
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
description: Configure Proxy Access to the Internet
|
||||
type: family
|
||||
|
|
@ -78,14 +78,13 @@ The variables
|
|||
variable
|
||||
|
||||
Here is a second definition of a :term:`variable`: it is a declaration unit that represents a business domain metaphor,
|
||||
|
||||
the most common example is that a variable represents a configuration option
|
||||
the most common example is that a variable that represents a configuration option
|
||||
in a application, but a variable represents something more that a configuration option.
|
||||
It provides a business domain specific representation unit.
|
||||
|
||||
.. note:: dictionaries can just define a list of variables, but we will see that
|
||||
.. note:: Dictionaries can just define a list of variables, but we will see that
|
||||
we can specify a lot more. We can define variables **and** their relations,
|
||||
and the consistency between them.
|
||||
**and** the consistency between them.
|
||||
|
||||
In the next step, we will explain through a tutorial how to construct a list of variables.
|
||||
|
||||
|
|
@ -127,7 +126,7 @@ Here is the tree structure we want to have::
|
|||
:caption: The `hello.yaml` file
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
hello:
|
||||
default: world
|
||||
|
||||
|
|
@ -169,14 +168,14 @@ Let's continuing on our "Hello world" theme and add a :term:`family` container.
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
world:
|
||||
description: Hello world family container
|
||||
name:
|
||||
description: Somebody to say hello
|
||||
default: rougail
|
||||
|
||||
Here, we have a family named `world`.
|
||||
Here, we have a family named `world`.
|
||||
This family contains a variable named `name`
|
||||
|
||||
Again, let's validate this YAML file against Rougail's API:
|
||||
|
|
@ -188,5 +187,5 @@ Again, let's validate this YAML file against Rougail's API:
|
|||
We then have the output:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
{'rougail.world.name': 'rougail'}
|
||||
|
|
|
|||
120
docs/library.rst
120
docs/library.rst
|
|
@ -3,7 +3,8 @@
|
|||
|
||||
Rougail is a configuration management library that allows you to load variables in a simple and convenient way.
|
||||
|
||||
In the following examples, we will use a specific configuration of Rougail. You will find all the options to :doc:`customize the directories structure used <configuration>`.
|
||||
In the following examples, we will use a specific configuration of Rougail.
|
||||
You will find all the configuraiton options in :doc:`configuration`.
|
||||
|
||||
To load the configuration you must import the `RougailConfig` class and set the `dictionaries_dir` values:
|
||||
|
||||
|
|
@ -25,22 +26,22 @@ Here is a first :file:`dict/00-base.yml` dictionary:
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
default: my_value
|
||||
|
||||
Then, let's create the :term:`Tiramisu` objects via the following script:
|
||||
|
||||
.. code-block:: python
|
||||
.. code-block:: python
|
||||
:caption: the `script.py` file content
|
||||
|
||||
|
||||
from rougail import Rougail, RougailConfig
|
||||
|
||||
RougailConfig['dictionaries_dir'] = ['dict']
|
||||
rougail = Rougail()
|
||||
config = rougail.get_config()
|
||||
print(config.value.get())
|
||||
|
||||
|
||||
Let's execute `script.py`:
|
||||
|
||||
.. code-block:: bash
|
||||
|
|
@ -70,15 +71,15 @@ Then let's create an extra :term:`dictionary` :file:`extras/00-base.yml`:
|
|||
.. code-block:: yaml
|
||||
:caption: the :file:`extras/00-base.yml` file content
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable_extra:
|
||||
default: my_value_extra
|
||||
|
||||
Then, let's create the :term:`Tiramisu` objects via the following :file:`script.py` script:
|
||||
|
||||
.. code-block:: python
|
||||
:caption: the :file:`script.py` file content
|
||||
|
||||
.. code-block:: python
|
||||
:caption: the :file:`script.py` file content
|
||||
|
||||
from rougail import Rougail, RougailConfig
|
||||
|
||||
RougailConfig['dictionaries_dir'] = ['dict']
|
||||
|
|
@ -102,24 +103,24 @@ We create the complementary :term:`dictionary` named :file:`dict/01-function.yml
|
|||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
my_variable_jinja:
|
||||
type: "string"
|
||||
default:
|
||||
default:
|
||||
type: jinja
|
||||
jinja: "{{ return_no() }}"
|
||||
|
||||
Then let's define the :func:`return_no` function in :file:`functions.py`:
|
||||
|
||||
.. code-block:: python
|
||||
.. code-block:: python
|
||||
:caption: the :file:`functions.py` content
|
||||
|
||||
|
||||
def return_no():
|
||||
return 'no'
|
||||
|
||||
Then, let's create the :term:`Tiramisu` objects via the following script:
|
||||
|
||||
.. code-block:: python
|
||||
.. code-block:: python
|
||||
:caption: the `script.py` file content
|
||||
|
||||
from rougail import Rougail, RougailConfig
|
||||
|
|
@ -139,3 +140,94 @@ Let's execute `script.py`:
|
|||
{'rougail.my_variable': 'my_value', 'rougail.my_variable_jinja': 'no', 'example.my_variable_extra': 'my_value_extra'}
|
||||
|
||||
The value of the `my_variable_extra` variable is calculated, and it's value comes from the :func:`return_no` function.
|
||||
|
||||
Create your own type
|
||||
----------------------
|
||||
|
||||
A variable has a type. This type enables the variable to define the values that are accepted by this variable.
|
||||
|
||||
There is a series of default types, but obviously not all cases are taken.
|
||||
|
||||
It's possible to create your own type.
|
||||
|
||||
Here an example to a lipogram option (in a string, we cannot use "e" character):
|
||||
|
||||
.. code-block:: python
|
||||
:caption: the `lipogram.py` file content
|
||||
|
||||
from tiramisu import StrOption
|
||||
class LipogramOption(StrOption):
|
||||
__slots__ = tuple()
|
||||
_type = 'lipogram'
|
||||
|
||||
def validate(self,
|
||||
value):
|
||||
super().validate(value)
|
||||
# verify that there is any 'e' in the sentense
|
||||
if 'e' in value:
|
||||
raise ValueError('Perec wrote a book without any "e", you could not do it in a simple sentence?')
|
||||
|
||||
To add the new lipogram type in Rougail:
|
||||
|
||||
.. code-block:: python
|
||||
>>> from rougail import Rougail, RougailConfig
|
||||
>>> RougailConfig['dictionaries_dir'] = ['dict']
|
||||
>>> RougailConfig['custom_types']['lipogram'] = LipogramOption
|
||||
|
||||
Now, we can use lipogram type.
|
||||
Here is a :file:`dict/00-base.yml` dictionary:
|
||||
|
||||
.. code-block:: yaml
|
||||
---
|
||||
version: '1.1'
|
||||
var:
|
||||
type: lipogram
|
||||
|
||||
.. code-block:: python
|
||||
>>> rougail = Rougail()
|
||||
>>> config = rougail.get_config()
|
||||
>>> config.option('rougail.var').value.set('blah')
|
||||
>>> config.option('rougail.var').value.set('I just want to add a quality string that has no bad characters')
|
||||
[...]
|
||||
tiramisu.error.ValueOptionError: "I just want to add a quality string that has no bad characters" is an invalid lipogram for "var", Perec wrote a book without any "e", you could not do it in a simple sentence?
|
||||
|
||||
Upgrade dictionnaries to upper version
|
||||
----------------------------------------
|
||||
|
||||
All dictionnaries has a format version number.
|
||||
When a new format version is proposed, it is possible to automatically convert the files to the new version.
|
||||
|
||||
We create a term:`dictionary` named :file:`dict/01-upgrade.yml` with version 1.0:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
multi: true
|
||||
my_dyn_family:
|
||||
type: "dynamic"
|
||||
variable: my_variable
|
||||
a_variable:
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
>>> from rougail import RougailUpgrade, RougailConfig
|
||||
>>> RougailConfig['dictionaries_dir'] = ['dict']
|
||||
>>> upgrade = RougailUpgrade()
|
||||
>>> upgrade.load_dictionaries('dict_converted')
|
||||
|
||||
The term:`dictionary` named :file:`dict_converted/01-upgrade.yml` is in version 1.1:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
version: '1.1'
|
||||
my_variable:
|
||||
multi: true
|
||||
my_dyn_family:
|
||||
type: dynamic
|
||||
a_variable: null
|
||||
dynamic:
|
||||
type: variable
|
||||
variable: my_variable
|
||||
propertyerror: false
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ Then let's put our first dictionary file in this folder, named :file:`00-proxy.y
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
description: Proxy configuration in order to have access to the internet
|
||||
type: family
|
||||
|
|
@ -69,7 +69,7 @@ Let's create a second :file:`dict/01-proxy_mode.yml` file.
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
proxy_mode:
|
||||
description: Proxy mode
|
||||
|
|
@ -122,7 +122,7 @@ Let's create the :file:`dict/02-proxy_manual.yml` dictionary:
|
|||
:caption: the the :file:`dict/02-proxy_manual.yml` file
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
manual:
|
||||
description: Manual proxy configuration
|
||||
|
|
@ -170,7 +170,7 @@ Let's create the :file:`dict/03-proxy_manual_http_proxy.yml` dictionary:
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
manual:
|
||||
http_proxy:
|
||||
|
|
@ -195,7 +195,7 @@ We then want to offer the user the possibility of providing the same proxy for t
|
|||
.. code-block:: yaml
|
||||
:caption: the :file:`dict/04-proxy_manual_http_use_for_https.yml` file
|
||||
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
manual:
|
||||
use_for_https:
|
||||
|
|
@ -216,7 +216,7 @@ Let's create the :file:`dict/05-proxy_manual_ssl_proxy.yml` file:
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
manual:
|
||||
ssl_proxy:
|
||||
|
|
@ -271,9 +271,12 @@ Let's look at what happens if we try to access the `rougail.proxy.manual` variab
|
|||
We have an error (with the message defined in the Jinja template):
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
.. code-block:: shell
|
||||
|
||||
tiramisu.error.PropertiesOptionError: cannot access to
|
||||
optiondescription "Manual proxy configuration" because
|
||||
has property "disabled" (the mode proxy is not manual)
|
||||
|
||||
tiramisu.error.PropertiesOptionError: cannot access to optiondescription "Manual proxy configuration" because has property "disabled" (the mode proxy is not manual)
|
||||
|
||||
Let's configure the proxy in manual mode
|
||||
|
||||
|
|
@ -291,7 +294,7 @@ We can see that the returned variables does have the desired values:
|
|||
'rougail.proxy.manual.http_proxy.port': '8080',
|
||||
'rougail.proxy.manual.use_for_https': True}
|
||||
|
||||
Let's set the `read_only` mode:
|
||||
Let's set the `read_only` mode and have a look at the configuration again:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
|
@ -307,7 +310,7 @@ Let's set the `read_only` mode:
|
|||
In the `read_only` mode, we can see that the HTTPS configuration appears.
|
||||
|
||||
.. note:: We can see that `rougail.proxy.manual.http_proxy` values have been copied
|
||||
in `rougail.proxy.manual.ssl_proxy` too...
|
||||
in `rougail.proxy.manual.ssl_proxy` too.
|
||||
|
||||
Changing values programmatically
|
||||
--------------------------------------
|
||||
|
|
@ -357,7 +360,7 @@ Let's create the :file:`dict/06-proxy_manual_socks_proxy.yml` file:
|
|||
:caption: the :file:`dict/06-proxy_manual_socks_proxy.yml` file
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
manual:
|
||||
socks_proxy:
|
||||
|
|
@ -389,7 +392,7 @@ Let's create the :file:`dict/07-proxy_auto.yml` file:
|
|||
:caption: the :file:`dict/07-proxy_auto.yml` file
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
auto:
|
||||
type: web_address
|
||||
|
|
@ -416,7 +419,7 @@ Let's create the :file:`dict/07-proxy_no_proxy.yml` file:
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
no_proxy:
|
||||
description: Address for which proxy will be desactivated
|
||||
|
|
@ -507,7 +510,7 @@ Nothing special when creating the authentication request. To do this, let's crea
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
prompt_authentication:
|
||||
description: Prompt for authentication if password is saved
|
||||
|
|
@ -532,7 +535,7 @@ Let's create a `dict/09-proxy_proxy_dns_socks5.yml` file:
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
proxy_dns_socks5:
|
||||
description: Use proxy DNS when using SOCKS v5
|
||||
|
|
@ -575,7 +578,7 @@ Let's create a `dict/10-proxy_dns_over_https.yml` file:
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
dns_over_https:
|
||||
description: DNS over HTTPS
|
||||
|
|
@ -648,7 +651,7 @@ Here is the complete content of the FoxyProxy type proxy configuration
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
_type: leadership
|
||||
title:
|
||||
|
|
@ -810,7 +813,7 @@ If you prefer this option, here is a second extra dictionary :file:`foxyproxy/01
|
|||
:linenos:
|
||||
|
||||
---
|
||||
version: '1.0'
|
||||
version: '1.1'
|
||||
proxy:
|
||||
username:
|
||||
redefine: true
|
||||
|
|
|
|||
|
|
@ -10,58 +10,80 @@ Synopsis
|
|||
variables
|
||||
|
||||
A variable is an abstract black box (container) paired with an associated symbolic name, which contains some defined or undefined quantity of data referred to as a `value`.
|
||||
|
||||
|
||||
.. discussion:: This definition, makes a heavy use of data typing.
|
||||
Indeed, depending on the type system definition of the constistency handling system used, variables may only be able to store a specified data type.
|
||||
OK, variables are the containers for storing the values. It has something to do with typing.
|
||||
OK, variables are the containers for storing the values. It has something to do with typing.
|
||||
But this is not just about typing.
|
||||
|
||||
Name
|
||||
-------------
|
||||
|
||||
|
||||
Variable's associated symbolic name.
|
||||
|
||||
|
||||
It's best to follow the :ref:`convention on variable names`.
|
||||
|
||||
Shorthand declaration
|
||||
----------------------------
|
||||
|
||||
Shorthand declaration is a way to declare a variable in a single line. But you can only define variable name, description, multi or default value.
|
||||
|
||||
To create a variable, just add a key with it's name and default value as value.
|
||||
Be careful not to declare any other attributes.
|
||||
|
||||
To declare a multi variable just add a list as default value.
|
||||
|
||||
By default, the description of the variable is the variable name.
|
||||
If you add a comment in the same line of the name, this comment will be used has a description.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
---
|
||||
version: '1.1'
|
||||
my_variable: 1 # This is a great integer variable
|
||||
my_multi_variable: # This is a great multi string variable
|
||||
- value1
|
||||
- value2
|
||||
|
||||
Parameters
|
||||
-------------
|
||||
|
||||
.. list-table::
|
||||
.. list-table::
|
||||
:widths: 15 45
|
||||
:header-rows: 1
|
||||
|
||||
|
||||
* - Parameter
|
||||
- Comments
|
||||
|
||||
|
||||
* - **help**
|
||||
|
||||
`string`
|
||||
`string`
|
||||
- Additional help associated with the variable.
|
||||
|
||||
* - **default**
|
||||
|
||||
* - **default**
|
||||
- Default value(s) of the variable.
|
||||
|
||||
|
||||
This value is typed, you must correctly fill out the YAML file to avoid defining a value with an incorrect type. For example, a `number` must be a digit type, a multiple variable must be a `list` type, ...
|
||||
|
||||
|
||||
For a non :term:`leading` multiple variable, the first value defined in the list will also be the default value proposed if a new value is added to this variable.
|
||||
|
||||
* - **validators**
|
||||
|
||||
`list`
|
||||
- Value validators.
|
||||
|
||||
Jinja template list. The value of the variable will be considered invalid if the template has a return value.
|
||||
|
||||
Jinja template list. The value of the variable will be considered invalid if the template has a return value.
|
||||
* - **auto_save**
|
||||
|
||||
`boolean`
|
||||
`boolean`
|
||||
- Variable with automatically modified value.
|
||||
|
||||
|
||||
A variable with automatically modified value is a variable whose value will be considered as *modified* (that is, it is no longer the variable's default value).
|
||||
|
||||
For example, if the value of this variable comes from a calculation, the value will no longer be recalculated.
|
||||
|
||||
These variables are usually :term:`required` variables. In fact, these variables are only automatically modified if they have a value.
|
||||
|
||||
|
||||
A :term:`leader` or :term:`follower` variable cannot have the `auto_save` property.
|
||||
|
||||
**Default value**: `false`
|
||||
|
|
@ -69,11 +91,11 @@ Parameters
|
|||
|
||||
`string`
|
||||
- Variable's mode.
|
||||
|
||||
|
||||
**Default value**: The `default` mode of a variable is the mode of the parent family.
|
||||
|
||||
Special cases :
|
||||
|
||||
|
||||
- a variable with an automatically modified value or an automatic read-only variable is by default in `basic` mode
|
||||
- if the variable is not in a family, the variable will have a `standard` mode by default
|
||||
- a :term:`mandatory` variable without default value (calculate or not) will have a `basic` mode
|
||||
|
|
@ -91,19 +113,19 @@ Parameters
|
|||
**Default value**: `false`
|
||||
* - **hidden**
|
||||
|
||||
`boolean` or :term:`calculation`
|
||||
`boolean` or :term:`calculation`
|
||||
- Invisible variable.
|
||||
|
||||
|
||||
Enables us to *hide* a variable.
|
||||
|
||||
This means that the variable will no longer be visible in `read-write` mode, but only for calculations or in `read-only` mode.
|
||||
|
||||
|
||||
When a variable is made invisible, the user will not be able to modify its value; if he has already succeeded in modifying it, this value will not be taken into account.
|
||||
|
||||
**Default value**: `false`
|
||||
* - **disabled**
|
||||
|
||||
`boolean` or :term:`calculation`
|
||||
`boolean` or :term:`calculation`
|
||||
- Disabled variable.
|
||||
|
||||
Allows us to deactivate a variable.
|
||||
|
|
@ -113,7 +135,7 @@ Parameters
|
|||
**Default value**: `false`.
|
||||
* - **mandatory**
|
||||
|
||||
`boolean` or :term:`calculation`
|
||||
`boolean` or :term:`calculation`
|
||||
- Mandatory variable.
|
||||
|
||||
Variable whose value is `required`.
|
||||
|
|
@ -134,74 +156,74 @@ Parameters
|
|||
|
||||
- creates a variable if it does not exist in another :term:`dictionary` (otherwise do nothing), in this case the value of the attribute must be `true`
|
||||
- in conjunction with the `redefine` attribute set to `true`, only modifies the behavior if it is pre-existing, in which case the attribute's value must be `false`.
|
||||
|
||||
|
||||
**Default value**: `null`
|
||||
* - **test**
|
||||
|
||||
`list`
|
||||
- The `test` attribute is a special attribute that allows :term:`dictionary` designers to influence a test robot by specifying useful values to test.
|
||||
|
||||
|
||||
Concretely, the content of this attribute is recorded in the `information` attribute of the corresponding `Tiramisu` option object.
|
||||
|
||||
Variables types
|
||||
----------------
|
||||
|
||||
|
||||
A variable **has a type**.
|
||||
|
||||
This type enables the variable to define the values that are accepted by this variable.
|
||||
|
||||
.. list-table::
|
||||
.. list-table::
|
||||
:widths: 15 25 20 15
|
||||
:header-rows: 1
|
||||
|
||||
|
||||
* - Value
|
||||
- Comments
|
||||
- Parameters
|
||||
- Samples
|
||||
|
||||
|
||||
* - string
|
||||
- character string (default type)
|
||||
-
|
||||
-
|
||||
- test
|
||||
|
||||
|
||||
"1"
|
||||
|
||||
"true"
|
||||
* - number
|
||||
- a number
|
||||
- a number
|
||||
- `min_number`: minimum number allowed
|
||||
|
||||
|
||||
`max_number`: maximum number allowed
|
||||
- 1
|
||||
* - float
|
||||
- a floating number
|
||||
-
|
||||
-
|
||||
- 1.2
|
||||
* - boolean
|
||||
- A boolean, if no value is defined the default value of this variable will be `true`, the variable will also be :term:`mandatory` by default
|
||||
-
|
||||
-
|
||||
- `true`
|
||||
|
||||
|
||||
`false`
|
||||
* - secret
|
||||
- a secret (like a password, a private key, etc.)
|
||||
-
|
||||
-
|
||||
- `hO_'hi`
|
||||
* - mail
|
||||
- a mail address
|
||||
-
|
||||
* - mail
|
||||
- a mail address
|
||||
-
|
||||
- test@rougail.example
|
||||
* - unix_filename
|
||||
- a file name in the Unix meaning
|
||||
-
|
||||
-
|
||||
- :file:`/etc/passwd`
|
||||
* - date
|
||||
* - date
|
||||
- a date in the format `%Y-%m-%d`
|
||||
-
|
||||
-
|
||||
- `2021-01-30`
|
||||
* - unix_user
|
||||
- a user in the Unix meaning
|
||||
-
|
||||
- a user in the Unix meaning
|
||||
-
|
||||
- test
|
||||
* - ip
|
||||
- any kind of IPv4 address
|
||||
|
|
@ -212,73 +234,73 @@ This type enables the variable to define the values that are accepted by this va
|
|||
* - cidr
|
||||
- any IPv4 address in the CIDR format
|
||||
- `private_only`: only private IPs (`false` by default)
|
||||
|
||||
`allow_reserved`: allows reserved IPs (`false` by default)
|
||||
|
||||
`allow_reserved`: allows reserved IPs (`false` by default)
|
||||
- `1.2.3.4/24`
|
||||
* - netmask
|
||||
- mask of an IPv4 address
|
||||
-
|
||||
-
|
||||
- `255.255.255.0`
|
||||
* - network
|
||||
- network address
|
||||
-
|
||||
-
|
||||
- `192.168.1.0`
|
||||
* - network_cidr
|
||||
- network address in CIDR format
|
||||
-
|
||||
-
|
||||
- `192.168.1.0/24`
|
||||
* - broadcast
|
||||
- broadcast address
|
||||
-
|
||||
-
|
||||
- `255.255.255.255`
|
||||
* - netbios
|
||||
- netbios name
|
||||
-
|
||||
- netbios name
|
||||
-
|
||||
- machine
|
||||
* - domainname
|
||||
- domain name
|
||||
- domain name
|
||||
- `allow_ip`: allows an IP rather than a domain name (`false` by default)
|
||||
|
||||
|
||||
`allow_cidr_network`: allows a CIDR type network address (`false` by default)
|
||||
|
||||
|
||||
`allow_without_dot`: allows names without a dot (`false` by default)
|
||||
|
||||
|
||||
`allow_startswith_dot`: allows starting with a point (`false` by default)
|
||||
- `rougail.example`
|
||||
* - hostname
|
||||
- host name
|
||||
* - hostname
|
||||
- host name
|
||||
- `allow_ip`: allows an IP rather than a domain name (`false` by default)
|
||||
- machine
|
||||
* - web_address
|
||||
- web address
|
||||
- `allow_ip`: allows an IP rather than a domain name (`false` by default)
|
||||
|
||||
|
||||
`allow_without_dot`: allows names without a dot (`true` by default)
|
||||
- http://rougail.example
|
||||
* - port
|
||||
- port
|
||||
* - port
|
||||
- port
|
||||
- `allow_range`: allows a port range, for example 80:85 (`false` by default)
|
||||
|
||||
`allow_zero`: allows port 0 (false by default)
|
||||
|
||||
`allow_wellknown`: allows ports from 1 to 1023 (`true` by default)
|
||||
|
||||
|
||||
`allow_registred`: allows ports from 1024 to 49151 (`true` by default)
|
||||
|
||||
|
||||
`allow_private`: allows ports greater than 49152 (`true` by default)
|
||||
|
||||
|
||||
`allow_protocol`: allows the addition of the protocol, for example tcp:80 (`false` by default)
|
||||
|
||||
|
||||
- 8080
|
||||
* - mac
|
||||
- MAC address
|
||||
-
|
||||
-
|
||||
- 11:11:11:11:11:11
|
||||
* - unix_permissions
|
||||
- access rights to the file, directory, etc.
|
||||
-
|
||||
-
|
||||
- 644
|
||||
* - choice
|
||||
- choice variable
|
||||
-
|
||||
-
|
||||
* - choice
|
||||
- choice variable
|
||||
-
|
||||
-
|
||||
|
|
|
|||
166
locale/fr/LC_MESSAGES/rougail.po
Normal file
166
locale/fr/LC_MESSAGES/rougail.po
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
# SOME DESCRIPTIVE TITLE.
|
||||
# Copyright (C) YEAR ORGANIZATION
|
||||
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
|
||||
#
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: \n"
|
||||
"POT-Creation-Date: 2024-10-30 13:21+0100\n"
|
||||
"PO-Revision-Date: 2024-10-30 13:39+0100\n"
|
||||
"Last-Translator: \n"
|
||||
"Language-Team: \n"
|
||||
"Language: fr\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Generated-By: pygettext.py 1.5\n"
|
||||
"X-Generator: Poedit 3.5\n"
|
||||
|
||||
#: src/rougail/annotator/family.py:142
|
||||
msgid "default variable mode \"{0}\" is not a valid mode, valid modes are {1}"
|
||||
msgstr ""
|
||||
"le mode d'une variable par défaut \"{0}\" n'est pas un mode valide, les "
|
||||
"modes valides sont {1}"
|
||||
|
||||
#: src/rougail/annotator/family.py:148
|
||||
msgid "default family mode \"{0}\" is not a valid mode, valid modes are {1}"
|
||||
msgstr ""
|
||||
"le mode d'une famille par défaut \"{0}\" n'est pas un mode valide, les modes "
|
||||
"valides sont {1}"
|
||||
|
||||
#: src/rougail/annotator/family.py:180
|
||||
msgid "mode \"{0}\" for \"{1}\" is not a valid mode, valid modes are {2}"
|
||||
msgstr ""
|
||||
"le mode \"{0}\" pour \"{1}\" n'est pas un mode valide, les modes valides "
|
||||
"sont {2}"
|
||||
|
||||
#: src/rougail/annotator/family.py:184
|
||||
msgid "mode \"{0}\" for \"{1}\" is not a valid mode, no modes are available"
|
||||
msgstr ""
|
||||
"le mode \"{0}\" pour \"{1}\" n'est pas un mode valide, aucun mode ne sont "
|
||||
"définis"
|
||||
|
||||
#: src/rougail/annotator/family.py:248
|
||||
msgid ""
|
||||
"the variable \"{0}\" is mandatory so in \"{1}\" mode but family has the "
|
||||
"higher family mode \"{2}\""
|
||||
msgstr ""
|
||||
"la variable \"{0}\" est obligatoire donc dans le mode \"{1}\" mais la "
|
||||
"famille a un mode supérieur \"{2}\""
|
||||
|
||||
#: src/rougail/annotator/family.py:286
|
||||
msgid ""
|
||||
"the follower \"{0}\" is in \"{1}\" mode but leader have the higher mode "
|
||||
"\"{2}\""
|
||||
msgstr ""
|
||||
"la variable suiveuse \"{0}\" a le mode \"{1}\" mais la variable leader a un "
|
||||
"mode supérieur \"{2}\""
|
||||
|
||||
#: src/rougail/annotator/family.py:319
|
||||
msgid ""
|
||||
"the family \"{0}\" is in \"{1}\" mode but variables and families inside have "
|
||||
"the higher modes \"{2}\""
|
||||
msgstr ""
|
||||
"la famille \"{0}\" a le mode \"{1}\" mais les variables et les familles à "
|
||||
"l'intérieur ont des modes supérieurs \"{2}\""
|
||||
|
||||
#: src/rougail/annotator/family.py:337
|
||||
msgid ""
|
||||
"the variable \"{0}\" is in \"{1}\" mode but family has the higher family "
|
||||
"mode \"{2}\""
|
||||
msgstr ""
|
||||
"la variable \"{0}\" est dans le mode \"{1}\" mais la famille a le mode "
|
||||
"supérieur \"{2}\""
|
||||
|
||||
#: src/rougail/annotator/value.py:80
|
||||
msgid "the follower \"{0}\" without multi attribute can only have one value"
|
||||
msgstr ""
|
||||
"la variable suiveuse \"{0}\" sans l'attribut multi peut avoir seulement une "
|
||||
"valeur"
|
||||
|
||||
#: src/rougail/annotator/value.py:96
|
||||
msgid "the variable \"{0}\" is multi but has a non list default value"
|
||||
msgstr ""
|
||||
"la variable \"{0}\" est multiple mais a une valeur par défaut sans être une "
|
||||
"liste"
|
||||
|
||||
#: src/rougail/annotator/variable.py:192
|
||||
msgid ""
|
||||
"the variable \"{0}\" has regexp attribut but has not the \"regexp\" type"
|
||||
msgstr ""
|
||||
"la variable \"{0}\" a un attribut regexp mais n'a pas le type \"regexp\""
|
||||
|
||||
#: src/rougail/annotator/variable.py:235
|
||||
msgid ""
|
||||
"the variable \"{0}\" has choices attribut but has not the \"choice\" type"
|
||||
msgstr ""
|
||||
"la variable \"{0}\" a un attribut choices mais n'a pas le type \"choice\""
|
||||
|
||||
#: src/rougail/annotator/variable.py:263
|
||||
msgid ""
|
||||
"the variable \"{0}\" has an unvalid default value \"{1}\" should be in {2}"
|
||||
msgstr ""
|
||||
"la variable \"{0}\" a la valeur par défaut invalide \"{1}\" devrait être {2}"
|
||||
|
||||
#: src/rougail/convert.py:268
|
||||
msgid ""
|
||||
"A variable or a family located in the \"{0}\" namespace shall not be used in "
|
||||
"the \"{1}\" namespace"
|
||||
msgstr ""
|
||||
"Une variable ou une famille localisé dans l'espace de nom \"{0}\" ne devrait "
|
||||
"pas être utilisé dans l'espace de nom \"{1}\""
|
||||
|
||||
#: src/rougail/convert.py:462
|
||||
msgid "unknown type {0} for {1}"
|
||||
msgstr "type {0} inconnu pour {1}"
|
||||
|
||||
#: src/rougail/convert.py:1323
|
||||
msgid "duplicate dictionary file name {0}"
|
||||
msgstr "nom de fichier {0} de dictionnaire dupliqué"
|
||||
|
||||
#: src/rougail/convert.py:1370
|
||||
msgid "Cannot execute annotate multiple time"
|
||||
msgstr "Ne peut exécuter l'annotation plusieurs fois"
|
||||
|
||||
#: src/rougail/error.py:70
|
||||
msgid "{0} in {1}"
|
||||
msgstr "{0} dans {1}"
|
||||
|
||||
#: src/rougail/structural_commandline/annotator.py:70
|
||||
msgid "alternative_name \"{0}\" conflict with \"--help\""
|
||||
msgstr "alternative_name \"{0}\" est en conflit avec \"--help\""
|
||||
|
||||
#: src/rougail/structural_commandline/annotator.py:73
|
||||
msgid "conflict alternative_name \"{0}\": \"{1}\" and \"{2}\""
|
||||
msgstr "conflit dans les \"alternative_name\" \"{0}\": \"{1}\" et \"{2}\""
|
||||
|
||||
#: src/rougail/structural_commandline/annotator.py:96
|
||||
msgid ""
|
||||
"negative_description is mandatory for boolean variable, but \"{0}\" hasn't"
|
||||
msgstr ""
|
||||
"l'attribut negative_description est obligatoire pour des variables "
|
||||
"\"boolean\", mais \"{0}\" n'en a pas"
|
||||
|
||||
#: src/rougail/structural_commandline/annotator.py:105
|
||||
msgid ""
|
||||
"negative_description is only available for boolean variable, but \"{0}\" is "
|
||||
"\"{1}\""
|
||||
msgstr ""
|
||||
"l'attribut negative_description est seulement valide pour des variables "
|
||||
"\"boolean\", mais \"{0}\" est \"{1}\""
|
||||
|
||||
#: src/rougail/update/update.py:741
|
||||
msgid "not a XML file: {0}"
|
||||
msgstr "fichier XML invalid : {0}"
|
||||
|
||||
#: src/rougail/utils.py:58
|
||||
msgid ""
|
||||
"invalid variable or family name \"{0}\" must only contains lowercase ascii "
|
||||
"character, number or _"
|
||||
msgstr ""
|
||||
"nom invalide pour la variable ou famille \"{0}\" doit seulement contenir des "
|
||||
"caractères ascii minuscule, nombre or _"
|
||||
|
||||
#: src/rougail/utils.py:120
|
||||
msgid "error in jinja \"{0}\" for the variable \"{1}\": {2}"
|
||||
msgstr "erreur dans Jinja \"{0}\" pour la variable \"{1}\": {2}"
|
||||
117
locale/rougail.pot
Normal file
117
locale/rougail.pot
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
# SOME DESCRIPTIVE TITLE.
|
||||
# Copyright (C) YEAR ORGANIZATION
|
||||
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
|
||||
#
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: PACKAGE VERSION\n"
|
||||
"POT-Creation-Date: 2024-11-04 12:04+0100\n"
|
||||
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
|
||||
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
||||
"Language-Team: LANGUAGE <LL@li.org>\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Generated-By: pygettext.py 1.5\n"
|
||||
|
||||
|
||||
#: src/rougail/annotator/family.py:139
|
||||
msgid "default variable mode \"{0}\" is not a valid mode, valid modes are {1}"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/family.py:145
|
||||
msgid "default family mode \"{0}\" is not a valid mode, valid modes are {1}"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/family.py:177
|
||||
msgid "mode \"{0}\" for \"{1}\" is not a valid mode, valid modes are {2}"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/family.py:181
|
||||
msgid "mode \"{0}\" for \"{1}\" is not a valid mode, no modes are available"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/family.py:245
|
||||
msgid "the variable \"{0}\" is mandatory so in \"{1}\" mode but family has the higher family mode \"{2}\""
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/family.py:283
|
||||
msgid "the follower \"{0}\" is in \"{1}\" mode but leader have the higher mode \"{2}\""
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/family.py:316
|
||||
msgid "the family \"{0}\" is in \"{1}\" mode but variables and families inside have the higher modes \"{2}\""
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/family.py:334
|
||||
msgid "the variable \"{0}\" is in \"{1}\" mode but family has the higher family mode \"{2}\""
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/value.py:77
|
||||
msgid "the follower \"{0}\" without multi attribute can only have one value"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/value.py:93
|
||||
msgid "the variable \"{0}\" is multi but has a non list default value"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/variable.py:189
|
||||
msgid "the variable \"{0}\" has regexp attribut but has not the \"regexp\" type"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/variable.py:232
|
||||
msgid "the variable \"{0}\" has choices attribut but has not the \"choice\" type"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/annotator/variable.py:260
|
||||
msgid "the variable \"{0}\" has an unvalid default value \"{1}\" should be in {2}"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/convert.py:281
|
||||
msgid "A variable or a family located in the \"{0}\" namespace shall not be used in the \"{1}\" namespace"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/convert.py:475
|
||||
msgid "unknown type {0} for {1}"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/convert.py:1345
|
||||
msgid "duplicate dictionary file name {0}"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/convert.py:1392
|
||||
msgid "Cannot execute annotate multiple time"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/error.py:67
|
||||
msgid "{0} in {1}"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/structural_commandline/annotator.py:67
|
||||
msgid "alternative_name \"{0}\" conflict with \"--help\""
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/structural_commandline/annotator.py:72
|
||||
msgid "conflict alternative_name \"{0}\": \"{1}\" and \"{2}\""
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/structural_commandline/annotator.py:95
|
||||
msgid "negative_description is mandatory for boolean variable, but \"{0}\" hasn't"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/structural_commandline/annotator.py:104
|
||||
msgid "negative_description is only available for boolean variable, but \"{0}\" is \"{1}\""
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/update/update.py:738
|
||||
msgid "not a XML file: {0}"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/utils.py:55
|
||||
msgid "invalid variable or family name \"{0}\" must only contains lowercase ascii character, number or _"
|
||||
msgstr ""
|
||||
|
||||
#: src/rougail/utils.py:117
|
||||
msgid "error in jinja \"{0}\" for the variable \"{1}\": {2}"
|
||||
msgstr ""
|
||||
|
||||
|
|
@ -4,18 +4,19 @@ requires = ["flit_core >=3.8.0,<4"]
|
|||
|
||||
[project]
|
||||
name = "rougail"
|
||||
version = "1.0.2"
|
||||
authors = [
|
||||
{name = "Emmanuel Garette", email = "gnunux@gnunux.info"},
|
||||
]
|
||||
description = "A consistency handling system that was initially designed in the configuration management"
|
||||
version = "1.1.1"
|
||||
authors = [{name = "Emmanuel Garette", email = "gnunux@gnunux.info"}]
|
||||
readme = "README.md"
|
||||
description = "A consistency handling system that was initially designed in the configuration management"
|
||||
requires-python = ">=3.8"
|
||||
classifiers = [
|
||||
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
|
||||
"Programming Language :: Python",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Operating System :: OS Independent",
|
||||
"Natural Language :: English",
|
||||
|
|
@ -23,18 +24,27 @@ classifiers = [
|
|||
|
||||
]
|
||||
dependencies = [
|
||||
"pyyaml ~= 6.0.1",
|
||||
"pydantic ~= 2.5.2",
|
||||
"jinja2 ~= 3.1.2",
|
||||
"ruamel.yaml ~= 0.18.6",
|
||||
"pydantic ~= 2.9.2",
|
||||
"jinja2 ~= 3.1.4",
|
||||
"tiramisu >=5.0,<6"
|
||||
]
|
||||
[project.optional-dependancies]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pylint ~= 3.0.3",
|
||||
"pytest ~= 8.2.2",
|
||||
"lxml ~= 5.2.2"
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Home = "https://forge.cloud.silique.fr/stove/rougail"
|
||||
|
||||
|
||||
[tool.commitizen]
|
||||
name = "cz_conventional_commits"
|
||||
tag_format = "$version"
|
||||
version_scheme = "semver"
|
||||
version_scheme = "pep440"
|
||||
version_provider = "pep621"
|
||||
update_changelog_on_bump = true
|
||||
changelog_merge_prerelease = true
|
||||
|
|
|
|||
|
|
@ -11,34 +11,51 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
from tiramisu import Config
|
||||
|
||||
from tiramisu import Config, undefined
|
||||
from tiramisu.error import PropertiesOptionError, LeadershipError, ConfigError
|
||||
from warnings import warn
|
||||
from typing import List
|
||||
from re import compile, findall
|
||||
|
||||
from .convert import RougailConvert
|
||||
from .config import RougailConfig
|
||||
from .update import RougailUpgrade
|
||||
from .object_model import CONVERT_OPTION
|
||||
from .utils import normalize_family
|
||||
|
||||
|
||||
def tiramisu_display_name(kls) -> str:
|
||||
def tiramisu_display_name(
|
||||
kls,
|
||||
subconfig,
|
||||
with_quote: bool = False,
|
||||
) -> str:
|
||||
"""Replace the Tiramisu display_name function to display path + description"""
|
||||
doc = kls.impl_get_information("doc", None)
|
||||
doc = kls._get_information(subconfig, "doc", None)
|
||||
comment = f" ({doc})" if doc and doc != kls.impl_getname() else ""
|
||||
return f"{kls.impl_getpath()}{comment}"
|
||||
if "{{ identifier }}" in comment:
|
||||
comment = comment.replace("{{ identifier }}", str(subconfig.identifiers[-1]))
|
||||
path = kls.impl_getpath()
|
||||
if "{{ identifier }}" in path and subconfig.identifiers:
|
||||
path = path.replace(
|
||||
"{{ identifier }}", normalize_family(str(subconfig.identifiers[-1]))
|
||||
)
|
||||
if with_quote:
|
||||
return f'"{path}"{comment}'
|
||||
return f"{path}{comment}"
|
||||
|
||||
|
||||
class Rougail:
|
||||
|
|
@ -46,7 +63,7 @@ class Rougail:
|
|||
|
||||
def __init__(
|
||||
self,
|
||||
rougailconfig = None,
|
||||
rougailconfig=None,
|
||||
) -> None:
|
||||
if rougailconfig is None:
|
||||
rougailconfig = RougailConfig
|
||||
|
|
@ -59,14 +76,19 @@ class Rougail:
|
|||
path_prefix: str,
|
||||
) -> None:
|
||||
"""Add a prefix"""
|
||||
self.converted.load_config()
|
||||
self.converted.parse_directories(path_prefix)
|
||||
|
||||
def get_config(self):
|
||||
def run(self):
|
||||
"""Get Tiramisu Config"""
|
||||
if not self.config:
|
||||
tiram_obj = self.converted.save(self.rougailconfig["tiramisu_cache"])
|
||||
optiondescription = {}
|
||||
exec(tiram_obj, None, optiondescription) # pylint: disable=W0122
|
||||
custom_types = {
|
||||
custom.__name__: custom
|
||||
for custom in self.rougailconfig["custom_types"].values()
|
||||
}
|
||||
exec(tiram_obj, custom_types, optiondescription) # pylint: disable=W0122
|
||||
self.config = Config(
|
||||
optiondescription["option_0"],
|
||||
display_name=tiramisu_display_name,
|
||||
|
|
@ -74,5 +96,231 @@ class Rougail:
|
|||
self.config.property.read_write()
|
||||
return self.config
|
||||
|
||||
def get_config(self):
|
||||
warn(
|
||||
"get_config is deprecated, use run instead",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return self.run()
|
||||
|
||||
__ALL__ = ("Rougail", "RougailConvert", "RougailConfig", "RougailUpgrade")
|
||||
def user_datas(self, user_datas: List[dict]):
|
||||
values = {}
|
||||
errors = []
|
||||
warnings = []
|
||||
for datas in user_datas:
|
||||
options = datas.get("options", {})
|
||||
for name, data in datas.get("values", {}).items():
|
||||
values[name] = {
|
||||
"values": data,
|
||||
"options": options.copy(),
|
||||
}
|
||||
errors.extend(datas.get("errors", []))
|
||||
warnings.extend(datas.get("warnings", []))
|
||||
self._auto_configure_dynamics(values)
|
||||
while values:
|
||||
value_is_set = False
|
||||
for option in self._get_variable(self.config):
|
||||
path = option.path()
|
||||
if path not in values:
|
||||
path = path.upper()
|
||||
options = values.get(path, {}).get("options", {})
|
||||
if path not in values or options.get("upper") is not True:
|
||||
continue
|
||||
else:
|
||||
options = values[path].get("options", {})
|
||||
value = values[path]["values"]
|
||||
if option.ismulti():
|
||||
if options.get("multi_separator") and not isinstance(value, list):
|
||||
value = value.split(options["multi_separator"])
|
||||
values[path]["values"] = value
|
||||
if options.get("needs_convert"):
|
||||
value = [convert_value(option, val) for val in value]
|
||||
values[path]["values"] = value
|
||||
values[path]["options"]["needs_convert"] = False
|
||||
elif options.get("needs_convert"):
|
||||
value = convert_value(option, value)
|
||||
index = option.index()
|
||||
if index is not None:
|
||||
if not isinstance(value, list) or index >= len(value):
|
||||
continue
|
||||
value = value[index]
|
||||
try:
|
||||
option.value.set(value)
|
||||
value_is_set = True
|
||||
if index is not None:
|
||||
values[path]["values"][index] = undefined
|
||||
if set(values[path]["values"]) == {undefined}:
|
||||
values.pop(path)
|
||||
else:
|
||||
values.pop(path)
|
||||
except Exception as err:
|
||||
if path != option.path():
|
||||
values[option.path()] = values.pop(path)
|
||||
if not value_is_set:
|
||||
break
|
||||
for path, data in values.items():
|
||||
try:
|
||||
option = self.config.option(path)
|
||||
value = data["values"]
|
||||
if option.isfollower():
|
||||
for index, val in enumerate(value):
|
||||
if val is undefined:
|
||||
continue
|
||||
self.config.option(path, index).value.set(val)
|
||||
else:
|
||||
option.value.set(value)
|
||||
except AttributeError as err:
|
||||
errors.append(str(err))
|
||||
except (ValueError, LeadershipError) as err:
|
||||
# errors.append(str(err).replace('"', "'"))
|
||||
errors.append(str(err))
|
||||
except PropertiesOptionError as err:
|
||||
# warnings.append(f'"{err}" but is defined in "{self.filename}"')
|
||||
warnings.append(str(err))
|
||||
return {
|
||||
"errors": errors,
|
||||
"warnings": warnings,
|
||||
}
|
||||
|
||||
def _get_variable(self, config):
|
||||
for subconfig in config:
|
||||
if subconfig.isoptiondescription():
|
||||
yield from self._get_variable(subconfig)
|
||||
else:
|
||||
yield subconfig
|
||||
|
||||
def _auto_configure_dynamics(
|
||||
self,
|
||||
values,
|
||||
):
|
||||
cache = {}
|
||||
added = []
|
||||
for path, data in list(values.items()):
|
||||
value = data["values"]
|
||||
# for value in data['values'].items():
|
||||
try:
|
||||
option = self.config.option(path)
|
||||
option.name()
|
||||
except (ConfigError, PropertiesOptionError):
|
||||
pass
|
||||
except AttributeError:
|
||||
config = self.config
|
||||
current_path = ""
|
||||
identifiers = []
|
||||
for name in path.split(".")[:-1]:
|
||||
if current_path:
|
||||
current_path += "."
|
||||
current_path += name
|
||||
if current_path in cache:
|
||||
config, identifier = cache[current_path]
|
||||
identifiers.append(identifier)
|
||||
else:
|
||||
tconfig = config.option(name)
|
||||
try:
|
||||
tconfig.group_type()
|
||||
config = tconfig
|
||||
except AttributeError:
|
||||
for tconfig in config.list(uncalculated=True):
|
||||
if tconfig.isdynamic(only_self=True):
|
||||
identifier = self._get_identifier(
|
||||
tconfig.name(), name
|
||||
)
|
||||
if identifier is None:
|
||||
continue
|
||||
dynamic_variable = tconfig.information.get(
|
||||
"dynamic_variable",
|
||||
None,
|
||||
)
|
||||
if not dynamic_variable:
|
||||
continue
|
||||
option_type = self.config.option(
|
||||
dynamic_variable
|
||||
).information.get("type")
|
||||
if identifiers:
|
||||
for s in identifiers:
|
||||
dynamic_variable = dynamic_variable.replace(
|
||||
"{{ identifier }}", str(s), 1
|
||||
)
|
||||
if dynamic_variable not in values:
|
||||
values[dynamic_variable] = {"values": []}
|
||||
added.append(dynamic_variable)
|
||||
elif dynamic_variable not in added:
|
||||
continue
|
||||
config = tconfig
|
||||
# option_type = option.information.get('type')
|
||||
typ = CONVERT_OPTION.get(option_type, {}).get(
|
||||
"func"
|
||||
)
|
||||
if typ:
|
||||
identifier = typ(identifier)
|
||||
if (
|
||||
identifier
|
||||
not in values[dynamic_variable]["values"]
|
||||
):
|
||||
values[dynamic_variable]["values"].append(
|
||||
identifier
|
||||
)
|
||||
identifiers.append(identifier)
|
||||
cache[current_path] = config, identifier
|
||||
break
|
||||
else:
|
||||
if option.isdynamic():
|
||||
parent_option = self.config.option(path.rsplit(".", 1)[0])
|
||||
identifiers = self._get_identifier(
|
||||
parent_option.name(uncalculated=True),
|
||||
parent_option.name(),
|
||||
)
|
||||
dynamic_variable = None
|
||||
while True:
|
||||
dynamic_variable = parent_option.information.get(
|
||||
"dynamic_variable",
|
||||
None,
|
||||
)
|
||||
if dynamic_variable:
|
||||
break
|
||||
parent_option = self.config.option(
|
||||
parent_option.path().rsplit(".", 1)[0]
|
||||
)
|
||||
if "." not in parent_option.path():
|
||||
parent_option = None
|
||||
break
|
||||
if not parent_option:
|
||||
continue
|
||||
identifiers = parent_option.identifiers()
|
||||
for identifier in identifiers:
|
||||
dynamic_variable = dynamic_variable.replace(
|
||||
"{{ identifier }}", str(identifier), 1
|
||||
)
|
||||
if dynamic_variable not in values:
|
||||
values[dynamic_variable] = {"values": []}
|
||||
added.append(dynamic_variable)
|
||||
elif dynamic_variable not in added:
|
||||
continue
|
||||
option_type = option.information.get("type")
|
||||
typ = CONVERT_OPTION.get(option_type, {}).get("func")
|
||||
if typ:
|
||||
identifier = typ(identifier)
|
||||
if identifier not in values[dynamic_variable]["values"]:
|
||||
values[dynamic_variable]["values"].append(identifier)
|
||||
cache[option.path()] = option, identifier
|
||||
|
||||
def _get_identifier(self, true_name, name) -> str:
|
||||
regexp = true_name.replace("{{ identifier }}", "(.*)")
|
||||
finded = findall(regexp, name)
|
||||
if len(finded) != 1 or not finded[0]:
|
||||
return
|
||||
return finded[0]
|
||||
|
||||
|
||||
def convert_value(option, value):
|
||||
if value == "":
|
||||
return None
|
||||
option_type = option.information.get("type")
|
||||
func = CONVERT_OPTION.get(option_type, {}).get("func")
|
||||
if func:
|
||||
return func(value)
|
||||
return value
|
||||
|
||||
|
||||
__all__ = ("Rougail", "RougailConfig", "RougailUpgrade")
|
||||
|
|
|
|||
|
|
@ -11,59 +11,49 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
from .variable import CONVERT_OPTION
|
||||
|
||||
import importlib.resources
|
||||
from os.path import isfile
|
||||
from ..utils import load_modules
|
||||
|
||||
|
||||
ANNOTATORS = None
|
||||
#
|
||||
#
|
||||
# if not 'files' in dir(importlib.resources):
|
||||
# # old python version
|
||||
# class fake_files:
|
||||
# def __init__(self, package):
|
||||
# self.mod = []
|
||||
# dir_package = dirname(importlib.resources._get_package(package).__file__)
|
||||
# for mod in importlib.resources.contents(package):
|
||||
# self.mod.append(join(dir_package, mod))
|
||||
#
|
||||
# def iterdir(self):
|
||||
# return self.mod
|
||||
# importlib.resources.files = fake_files
|
||||
|
||||
|
||||
def get_level(module):
|
||||
return module.level
|
||||
|
||||
|
||||
def get_annotators(annotators, module_name):
|
||||
annotators[module_name] = []
|
||||
def get_annotators(annotators, module_name, file_name=None):
|
||||
if file_name is None:
|
||||
_module_name = module_name
|
||||
else:
|
||||
_module_name = module_name + "." + file_name
|
||||
full_file_name = f"/{file_name}.py"
|
||||
annotators[_module_name] = []
|
||||
for pathobj in importlib.resources.files(module_name).iterdir():
|
||||
path = str(pathobj)
|
||||
if not path.endswith(".py") or path.endswith("__.py"):
|
||||
continue
|
||||
module = load_modules(path)
|
||||
if file_name is not None and not path.endswith(full_file_name):
|
||||
continue
|
||||
module = load_modules(module_name, path)
|
||||
if "Annotator" not in dir(module):
|
||||
continue
|
||||
annotators[module_name].append(module.Annotator)
|
||||
annotators[_module_name].append(module.Annotator)
|
||||
|
||||
|
||||
class SpaceAnnotator: # pylint: disable=R0903
|
||||
|
|
@ -77,21 +67,26 @@ class SpaceAnnotator: # pylint: disable=R0903
|
|||
if ANNOTATORS is None:
|
||||
ANNOTATORS = {}
|
||||
get_annotators(ANNOTATORS, "rougail.annotator")
|
||||
for extra_annotator in objectspace.rougailconfig["extra_annotators"]:
|
||||
for extra_annotator in objectspace.extra_annotators:
|
||||
if extra_annotator in ANNOTATORS:
|
||||
continue
|
||||
get_annotators(ANNOTATORS, extra_annotator)
|
||||
for plugin in objectspace.plugins:
|
||||
try:
|
||||
get_annotators(ANNOTATORS, f"rougail.{plugin}", "annotator")
|
||||
except ModuleNotFoundError:
|
||||
pass
|
||||
annotators = ANNOTATORS["rougail.annotator"].copy()
|
||||
for extra_annotator in objectspace.rougailconfig["extra_annotators"]:
|
||||
for extra_annotator in objectspace.extra_annotators:
|
||||
annotators.extend(ANNOTATORS[extra_annotator])
|
||||
for plugin in objectspace.plugins:
|
||||
annotators.extend(ANNOTATORS[f"rougail.{plugin}.annotator"])
|
||||
annotators = sorted(annotators, key=get_level)
|
||||
functions = {}
|
||||
functions_files = objectspace.rougailconfig["functions_file"]
|
||||
if not isinstance(functions_files, list):
|
||||
functions_files = [functions_files]
|
||||
functions_files = objectspace.functions_files
|
||||
for functions_file in functions_files:
|
||||
if isfile(functions_file):
|
||||
loaded_modules = load_modules(functions_file)
|
||||
loaded_modules = load_modules("function_file", functions_file)
|
||||
for function in dir(loaded_modules):
|
||||
if function.startswith("_"):
|
||||
continue
|
||||
|
|
@ -101,4 +96,4 @@ class SpaceAnnotator: # pylint: disable=R0903
|
|||
annotator(objectspace)
|
||||
|
||||
|
||||
__all__ = ("SpaceAnnotator", "CONVERT_OPTION")
|
||||
__all__ = ("SpaceAnnotator",)
|
||||
|
|
|
|||
|
|
@ -11,26 +11,25 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
from rougail.i18n import _
|
||||
from rougail.error import DictConsistencyError
|
||||
from rougail.annotator.variable import Walk
|
||||
from rougail.object_model import VariableCalculation
|
||||
|
||||
|
||||
class Mode: # pylint: disable=R0903
|
||||
|
|
@ -63,16 +62,34 @@ class Annotator(Walk):
|
|||
self.objectspace = objectspace
|
||||
if not self.objectspace.paths:
|
||||
return
|
||||
self.modes = {
|
||||
name: Mode(idx)
|
||||
for idx, name in enumerate(self.objectspace.rougailconfig["modes_level"])
|
||||
}
|
||||
self.check_leadership()
|
||||
self.remove_empty_families()
|
||||
self.family_names()
|
||||
self.change_modes()
|
||||
self.dynamic_families()
|
||||
self.family_description()
|
||||
if self.objectspace.modes_level:
|
||||
self.modes = {
|
||||
name: Mode(idx) for idx, name in enumerate(self.objectspace.modes_level)
|
||||
}
|
||||
self.default_variable_mode = self.objectspace.default_variable_mode
|
||||
self.default_family_mode = self.objectspace.default_family_mode
|
||||
self.change_modes()
|
||||
else:
|
||||
for family in self.get_families():
|
||||
self.valid_mode(family)
|
||||
for variable in self.get_variables():
|
||||
self.valid_mode(variable)
|
||||
self.convert_help()
|
||||
|
||||
def check_leadership(self) -> None:
|
||||
"""No subfamily in a leadership"""
|
||||
for family in self.get_families():
|
||||
if family.type != "leadership":
|
||||
continue
|
||||
for variable_path in self.objectspace.parents[family.path]:
|
||||
variable = self.objectspace.paths[variable_path]
|
||||
if variable.type in self.objectspace.family_types:
|
||||
msg = f'the leadership "{family.path}" cannot have the { variable.type } "{ variable.path}"'
|
||||
raise DictConsistencyError(msg, 24, variable.xmlfiles)
|
||||
|
||||
def remove_empty_families(self) -> None:
|
||||
"""Remove all families without any variable"""
|
||||
removed_families = []
|
||||
|
|
@ -80,7 +97,10 @@ class Annotator(Walk):
|
|||
if isinstance(family, self.objectspace.family) and not self._has_variable(
|
||||
family.path
|
||||
):
|
||||
if "." in family.path:
|
||||
if (
|
||||
self.objectspace.paths.default_namespace is None
|
||||
or "." in family.path
|
||||
):
|
||||
removed_families.append(family.path)
|
||||
removed_families.reverse()
|
||||
for family in removed_families:
|
||||
|
|
@ -98,31 +118,33 @@ class Annotator(Walk):
|
|||
return True
|
||||
return False
|
||||
|
||||
def family_names(self) -> None:
|
||||
"""Set doc, path, ... to family"""
|
||||
def family_description(self) -> None:
|
||||
for family in self.get_families():
|
||||
if not family.description:
|
||||
family.description = family.name
|
||||
|
||||
# family.doc = family.description
|
||||
# del family.description
|
||||
if family.type == "dynamic" and isinstance(
|
||||
family.dynamic, VariableCalculation
|
||||
):
|
||||
path = self.objectspace.paths.get_full_path(
|
||||
family.dynamic.variable,
|
||||
family.path,
|
||||
)
|
||||
self.objectspace.informations.add(family.path, "dynamic_variable", path)
|
||||
|
||||
def change_modes(self):
|
||||
"""change the mode of variables"""
|
||||
modes_level = self.objectspace.rougailconfig["modes_level"]
|
||||
default_variable_mode = self.objectspace.rougailconfig["default_variable_mode"]
|
||||
modes_level = self.objectspace.modes_level
|
||||
default_variable_mode = self.default_variable_mode
|
||||
if default_variable_mode not in modes_level:
|
||||
msg = _(
|
||||
f'default variable mode "{default_variable_mode}" is not a valid mode, '
|
||||
f"valid modes are {modes_level}"
|
||||
)
|
||||
'default variable mode "{0}" is not a valid mode, valid modes are {1}'
|
||||
).format(default_variable_mode, modes_level)
|
||||
raise DictConsistencyError(msg, 72, None)
|
||||
default_family_mode = self.objectspace.rougailconfig["default_family_mode"]
|
||||
default_family_mode = self.default_family_mode
|
||||
if default_family_mode not in modes_level:
|
||||
msg = _(
|
||||
f'default family mode "{default_family_mode}" is not a valid mode, '
|
||||
f"valid modes are {modes_level}"
|
||||
)
|
||||
'default family mode "{0}" is not a valid mode, valid modes are {1}'
|
||||
).format(default_family_mode, modes_level)
|
||||
raise DictConsistencyError(msg, 73, None)
|
||||
families = list(self.get_families())
|
||||
for family in families:
|
||||
|
|
@ -131,17 +153,34 @@ class Annotator(Walk):
|
|||
families.reverse()
|
||||
for family in families:
|
||||
self._change_family_mode(family)
|
||||
if self.objectspace.paths.default_namespace is None:
|
||||
for variable_path in self.objectspace.parents["."]:
|
||||
variable = self.objectspace.paths[variable_path]
|
||||
if (
|
||||
variable.type == "symlink"
|
||||
or variable_path in self.objectspace.families
|
||||
):
|
||||
continue
|
||||
self._set_default_mode_variable(
|
||||
variable,
|
||||
self.default_variable_mode,
|
||||
check_level=False,
|
||||
)
|
||||
|
||||
def valid_mode(
|
||||
self,
|
||||
obj,
|
||||
) -> None:
|
||||
modes_level = self.objectspace.rougailconfig["modes_level"]
|
||||
modes_level = self.objectspace.modes_level
|
||||
if self._has_mode(obj) and obj.mode not in modes_level:
|
||||
msg = _(
|
||||
f'mode "{obj.mode}" for "{obj.name}" is not a valid mode, '
|
||||
f"valid modes are {modes_level}"
|
||||
)
|
||||
if modes_level:
|
||||
msg = _(
|
||||
'mode "{0}" for "{1}" is not a valid mode, valid modes are {2}'
|
||||
).format(obj.mode, obj.name, modes_level)
|
||||
else:
|
||||
msg = _(
|
||||
'mode "{0}" for "{1}" is not a valid mode, no modes are available'
|
||||
).format(obj.mode, obj.name)
|
||||
raise DictConsistencyError(msg, 71, obj.xmlfiles)
|
||||
|
||||
def _set_default_mode(
|
||||
|
|
@ -162,6 +201,7 @@ class Annotator(Walk):
|
|||
continue
|
||||
if leader is None and family.type == "leadership":
|
||||
leader = variable
|
||||
leader_mode = leader.mode
|
||||
if variable_path in self.objectspace.families:
|
||||
# set default mode a subfamily
|
||||
if family_mode and not self._has_mode(variable):
|
||||
|
|
@ -172,9 +212,9 @@ class Annotator(Walk):
|
|||
if leader:
|
||||
self._set_default_mode_leader(leader, variable)
|
||||
self._set_default_mode_variable(variable, family_mode)
|
||||
if leader:
|
||||
if leader and leader_mode is not None:
|
||||
# here because follower can change leader mode
|
||||
self._set_auto_mode(family, leader.mode)
|
||||
self._set_auto_mode(family, leader_mode)
|
||||
|
||||
def _has_mode(self, obj) -> bool:
|
||||
return obj.mode and not obj.path in self.mode_auto
|
||||
|
|
@ -183,11 +223,12 @@ class Annotator(Walk):
|
|||
self,
|
||||
variable: "self.objectspace.variable",
|
||||
family_mode: Optional[str],
|
||||
check_level: bool = True,
|
||||
) -> None:
|
||||
# auto_save variable is set to 'basic' mode
|
||||
# if its mode is not defined by the user
|
||||
if not self._has_mode(variable) and variable.auto_save is True:
|
||||
variable.mode = self.objectspace.rougailconfig["modes_level"][0]
|
||||
variable.mode = self.objectspace.modes_level[0]
|
||||
# mandatory variable without value is a basic variable
|
||||
elif (
|
||||
not self._has_mode(variable)
|
||||
|
|
@ -195,12 +236,15 @@ class Annotator(Walk):
|
|||
and variable.default is None
|
||||
and variable.path not in self.objectspace.default_multi
|
||||
):
|
||||
variable_mode = self.objectspace.rougailconfig["modes_level"][0]
|
||||
if family_mode and self.modes[variable_mode] < self.modes[family_mode]:
|
||||
variable_mode = self.objectspace.modes_level[0]
|
||||
if (
|
||||
check_level
|
||||
and family_mode
|
||||
and self.modes[variable_mode] < self.modes[family_mode]
|
||||
):
|
||||
msg = _(
|
||||
f'the variable "{variable.name}" is mandatory so in "{variable_mode}" mode '
|
||||
f'but family has the higher family mode "{family_mode}"'
|
||||
)
|
||||
'the variable "{0}" is mandatory so in "{1}" mode but family has the higher family mode "{2}"'
|
||||
).format(variable.name, variable_mode, family_mode)
|
||||
raise DictConsistencyError(msg, 36, variable.xmlfiles)
|
||||
|
||||
variable.mode = variable_mode
|
||||
|
|
@ -220,20 +264,15 @@ class Annotator(Walk):
|
|||
leader: "self.objectspace.variable",
|
||||
follower: "self.objectspace.variable",
|
||||
) -> None:
|
||||
if follower.auto_save is True:
|
||||
msg = _(f'leader/followers "{follower.name}" could not be auto_save')
|
||||
raise DictConsistencyError(msg, 29, follower.xmlfiles)
|
||||
if leader == follower:
|
||||
# it's a leader
|
||||
if not leader.mode:
|
||||
self._set_auto_mode(
|
||||
leader, self.objectspace.rougailconfig["default_variable_mode"]
|
||||
)
|
||||
self._set_auto_mode(leader, self.default_variable_mode)
|
||||
return
|
||||
if self._has_mode(follower):
|
||||
follower_mode = follower.mode
|
||||
else:
|
||||
follower_mode = self.objectspace.rougailconfig["default_variable_mode"]
|
||||
follower_mode = self.default_variable_mode
|
||||
if self.modes[leader.mode] > self.modes[follower_mode]:
|
||||
if self._has_mode(follower) and not self._has_mode(leader):
|
||||
# if follower has mode but not the leader
|
||||
|
|
@ -242,9 +281,8 @@ class Annotator(Walk):
|
|||
# leader's mode is minimum level
|
||||
if self._has_mode(follower):
|
||||
msg = _(
|
||||
f'the follower "{follower.name}" is in "{follower_mode}" mode '
|
||||
f'but leader have the higher mode "{leader.mode}"'
|
||||
)
|
||||
'the follower "{0}" is in "{1}" mode but leader have the higher mode "{2}"'
|
||||
).format(follower.name, follower_mode, leader.mode)
|
||||
raise DictConsistencyError(msg, 63, follower.xmlfiles)
|
||||
self._set_auto_mode(follower, leader.mode)
|
||||
|
||||
|
|
@ -255,20 +293,18 @@ class Annotator(Walk):
|
|||
if family.mode:
|
||||
family_mode = family.mode
|
||||
else:
|
||||
family_mode = self.objectspace.rougailconfig["default_family_mode"]
|
||||
min_variable_mode = self.objectspace.rougailconfig["modes_level"][-1]
|
||||
family_mode = self.default_family_mode
|
||||
min_variable_mode = self.objectspace.modes_level[-1]
|
||||
# change variable mode, but not if variables are not in a family
|
||||
is_leadership = family.type == "leadership"
|
||||
if family.path in self.objectspace.parents:
|
||||
for idx, variable_path in enumerate(self.objectspace.parents[family.path]):
|
||||
for variable_path in self.objectspace.parents[family.path]:
|
||||
variable = self.objectspace.paths[variable_path]
|
||||
if variable.type == "symlink":
|
||||
continue
|
||||
if variable_path in self.objectspace.families:
|
||||
if not variable.mode:
|
||||
variable.mode = self.objectspace.rougailconfig[
|
||||
"default_family_mode"
|
||||
]
|
||||
variable.mode = self.default_family_mode
|
||||
else:
|
||||
self._change_variable_mode(variable, family_mode, is_leadership)
|
||||
if self.modes[min_variable_mode] > self.modes[variable.mode]:
|
||||
|
|
@ -276,6 +312,11 @@ class Annotator(Walk):
|
|||
if not family.mode:
|
||||
# set the lower variable mode to family
|
||||
self._set_auto_mode(family, min_variable_mode)
|
||||
if self.modes[family.mode] < self.modes[min_variable_mode]:
|
||||
msg = _(
|
||||
'the family "{0}" is in "{1}" mode but variables and families inside have the higher modes "{2}"'
|
||||
).format(family.name, family.mode, min_variable_mode)
|
||||
raise DictConsistencyError(msg, 62, family.xmlfiles)
|
||||
|
||||
def _change_variable_mode(
|
||||
self,
|
||||
|
|
@ -286,46 +327,18 @@ class Annotator(Walk):
|
|||
if variable.mode:
|
||||
variable_mode = variable.mode
|
||||
else:
|
||||
variable_mode = self.objectspace.rougailconfig["default_variable_mode"]
|
||||
variable_mode = self.default_variable_mode
|
||||
# none basic variable in high level family has to be in high level
|
||||
if not is_follower and self.modes[variable_mode] < self.modes[family_mode]:
|
||||
if self._has_mode(variable):
|
||||
msg = _(
|
||||
f'the variable "{variable.name}" is in "{variable_mode}" mode '
|
||||
f'but family has the higher family mode "{family_mode}"'
|
||||
)
|
||||
'the variable "{0}" is in "{1}" mode but family has the higher family mode "{2}"'
|
||||
).format(variable.name, variable_mode, family_mode)
|
||||
raise DictConsistencyError(msg, 61, variable.xmlfiles)
|
||||
self._set_auto_mode(variable, family_mode)
|
||||
if not variable.mode:
|
||||
variable.mode = variable_mode
|
||||
|
||||
def dynamic_families(self):
|
||||
"""link dynamic families to object"""
|
||||
for family in self.get_families():
|
||||
if family.type != "dynamic":
|
||||
continue
|
||||
try:
|
||||
family.variable = self.objectspace.paths[family.variable]
|
||||
except AttributeError as err:
|
||||
raise Exception(
|
||||
f'cannot load the dynamic family "{family.path}", cannot find variable "{family.variable}"'
|
||||
)
|
||||
if not family.variable.multi:
|
||||
msg = _(
|
||||
f'dynamic family "{family.name}" must be linked '
|
||||
f"to multi variable"
|
||||
)
|
||||
raise DictConsistencyError(msg, 16, family.xmlfiles)
|
||||
for variable in self.objectspace.parents[family.path]:
|
||||
if (
|
||||
isinstance(variable, self.objectspace.family)
|
||||
and not variable.leadership
|
||||
):
|
||||
msg = _(
|
||||
f'dynamic family "{family.name}" cannot contains another family'
|
||||
)
|
||||
raise DictConsistencyError(msg, 22, family.xmlfiles)
|
||||
|
||||
def convert_help(self):
|
||||
"""Convert variable help"""
|
||||
for family in self.get_families():
|
||||
|
|
|
|||
|
|
@ -11,22 +11,20 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from typing import Union
|
||||
from rougail.i18n import _
|
||||
from rougail.error import DictConsistencyError
|
||||
|
|
@ -112,37 +110,37 @@ class Annotator(Walk):
|
|||
self._convert_property(variable)
|
||||
if variable.hidden:
|
||||
if variable.hidden is True:
|
||||
self.frozen[variable.path] = True
|
||||
elif self.frozen.get(variable.path) is not True:
|
||||
self.frozen.setdefault(variable.path, []).append(variable.hidden)
|
||||
if variable.path in self.frozen:
|
||||
frozen = self.frozen[variable.path]
|
||||
self.frozen[path] = True
|
||||
elif self.frozen.get(path) is not True:
|
||||
self.frozen.setdefault(path, []).append(variable.hidden)
|
||||
if path in self.frozen:
|
||||
frozen = self.frozen[path]
|
||||
if frozen is True:
|
||||
value = True
|
||||
else:
|
||||
value = []
|
||||
for calculation in frozen:
|
||||
calculation_object = calculation.__class__
|
||||
calculation_dict = calculation.model_dump().copy()
|
||||
calculation_dict["attribute_name"] = "frozen"
|
||||
calculation_dict["path"] = variable.path
|
||||
value.append(calculation_object(**calculation_dict))
|
||||
calculation_copy = calculation.copy()
|
||||
calculation_copy.attribute_name = "frozen"
|
||||
calculation_copy.ori_path = calculation_copy.path
|
||||
calculation_copy.path = path
|
||||
value.append(calculation_copy)
|
||||
if len(value) == 1:
|
||||
value = value[0]
|
||||
self.objectspace.properties.add(path, "frozen", value)
|
||||
if not variable.auto_save:
|
||||
# if auto_save, save calculated value
|
||||
self.objectspace.properties.add(path, "force_default_on_freeze", True)
|
||||
if variable.mandatory and variable.multi:
|
||||
if not variable.empty and self.objectspace.multis.get(variable.path, False):
|
||||
# a multi could not have "None" has value
|
||||
# to permit it, just add mandatory="False"
|
||||
# to permit it, just add empty="false"
|
||||
self.objectspace.properties.add(path, "notempty", True)
|
||||
if variable.unique:
|
||||
self.objectspace.properties.add(path, "unique", True)
|
||||
if variable.unique is False:
|
||||
self.objectspace.properties.add(path, "notunique", True)
|
||||
if variable.auto_save:
|
||||
self.objectspace.properties.add(variable.path, "force_store_value", True)
|
||||
self.objectspace.properties.add(path, "force_store_value", True)
|
||||
|
||||
def _convert_property(
|
||||
self,
|
||||
|
|
|
|||
|
|
@ -11,22 +11,20 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from rougail.annotator.variable import Walk
|
||||
|
||||
from rougail.i18n import _
|
||||
|
|
@ -48,13 +46,15 @@ class Annotator(Walk): # pylint: disable=R0903
|
|||
return
|
||||
self.objectspace = objectspace
|
||||
self.convert_value()
|
||||
self.add_choice_nil()
|
||||
self.valid_choices()
|
||||
|
||||
def convert_value(self) -> None:
|
||||
"""convert value"""
|
||||
for variable in self.get_variables():
|
||||
if variable.type == "symlink":
|
||||
continue
|
||||
if variable.version != "1.0" and variable.type == "port":
|
||||
self._convert_port(variable)
|
||||
self._convert_value(variable)
|
||||
|
||||
def _convert_value(
|
||||
|
|
@ -66,58 +66,62 @@ class Annotator(Walk): # pylint: disable=R0903
|
|||
if variable.type == "boolean" and multi is False and variable.default is None:
|
||||
variable.default = True
|
||||
|
||||
if variable.default is None:
|
||||
if variable.default is None or isinstance(variable.default, Calculation):
|
||||
return
|
||||
has_value = False
|
||||
if isinstance(variable.default, Calculation):
|
||||
pass
|
||||
# variable.default = variable.default.to_function(self.functions)
|
||||
elif isinstance(variable.default, list):
|
||||
if not multi:
|
||||
raise Exception(
|
||||
f'The variable "{variable.path}" with a list has default value must have "multi" attribute'
|
||||
)
|
||||
if variable.path in self.objectspace.followers:
|
||||
if multi != "submulti" and len(variable.default) != 1:
|
||||
msg = _(
|
||||
f'the follower "{variable.name}" without multi attribute can only have one value'
|
||||
)
|
||||
raise DictConsistencyError(msg, 87, variable.xmlfiles)
|
||||
# else:
|
||||
# variable.default = [value.name for value in variable.default]
|
||||
if variable.path not in self.objectspace.leaders:
|
||||
if multi == "submulti":
|
||||
self.objectspace.default_multi[
|
||||
variable.path
|
||||
] = variable.default # [value.name for value in variable.value]
|
||||
variable.default = None
|
||||
else:
|
||||
self.objectspace.default_multi[variable.path] = variable.default[
|
||||
0
|
||||
] # .name
|
||||
has_value = True
|
||||
elif variable.multi:
|
||||
# msg = _(f'the none multi variable "{variable.name}" cannot have '
|
||||
# 'more than one value')
|
||||
# raise DictConsistencyError(msg, 68, variable.xmlfiles)
|
||||
raise Exception("pfff")
|
||||
else:
|
||||
if variable.path in self.objectspace.followers:
|
||||
self.objectspace.default_multi[variable.path] = variable.default
|
||||
variable.default = None
|
||||
has_value = True
|
||||
|
||||
def add_choice_nil(self) -> None:
|
||||
if isinstance(variable.default, list):
|
||||
if not multi:
|
||||
msg = f'The variable "{variable.path}" with a list as default value must have "multi" attribute'
|
||||
raise DictConsistencyError(msg, 68, variable.xmlfiles)
|
||||
if variable.path in self.objectspace.followers and multi != "submulti":
|
||||
msg = _(
|
||||
'the follower "{0}" without multi attribute can only have one value'
|
||||
).format(variable.name)
|
||||
raise DictConsistencyError(msg, 87, variable.xmlfiles)
|
||||
if not variable.default:
|
||||
variable.default = None
|
||||
else:
|
||||
if variable.path not in self.objectspace.leaders:
|
||||
if multi == "submulti":
|
||||
self.objectspace.default_multi[variable.path] = variable.default
|
||||
variable.default = None
|
||||
else:
|
||||
self.objectspace.default_multi[variable.path] = (
|
||||
variable.default[0]
|
||||
)
|
||||
elif variable.multi:
|
||||
msg = _(
|
||||
'the variable "{0}" is multi but has a non list default value'
|
||||
).format(variable.name)
|
||||
raise DictConsistencyError(msg, 12, variable.xmlfiles)
|
||||
elif variable.path in self.objectspace.followers:
|
||||
self.objectspace.default_multi[variable.path] = variable.default
|
||||
variable.default = None
|
||||
|
||||
def _convert_port(self, variable) -> None:
|
||||
if variable.multi is False and isinstance(variable.default, int):
|
||||
variable.default = str(variable.default)
|
||||
elif variable.multi is True and isinstance(variable.default, list):
|
||||
for idx, value in enumerate(variable.default):
|
||||
if isinstance(value, int):
|
||||
variable.default[idx] = str(value)
|
||||
|
||||
def valid_choices(self) -> None:
|
||||
"""A variable with type "Choice" that is not mandatory must has "nil" value"""
|
||||
for variable in self.get_variables():
|
||||
if variable.type != "choice":
|
||||
continue
|
||||
is_none = False
|
||||
if isinstance(variable.choices, Calculation):
|
||||
continue
|
||||
for choice in variable.choices:
|
||||
if choice is None:
|
||||
is_none = True
|
||||
break
|
||||
if not variable.mandatory and not is_none:
|
||||
variable.choices.append(None)
|
||||
if variable.choices is None:
|
||||
msg = f'the variable "{variable.path}" is a "choice" variable but don\'t have any choice'
|
||||
raise DictConsistencyError(msg, 19, variable.xmlfiles)
|
||||
if not variable.mandatory and not variable.multi:
|
||||
self.add_choice_nil(variable)
|
||||
|
||||
def add_choice_nil(self, variable) -> None:
|
||||
"""A variable with type "Choice" that is not mandatory must has "nil" value"""
|
||||
for choice in variable.choices:
|
||||
if choice is None:
|
||||
return
|
||||
variable.choices.append(None)
|
||||
|
|
|
|||
|
|
@ -11,78 +11,24 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from rougail.i18n import _
|
||||
from rougail.error import DictConsistencyError
|
||||
from rougail.object_model import Calculation
|
||||
|
||||
|
||||
def convert_boolean(value: str) -> bool:
|
||||
"""Boolean coercion. The Rougail XML may contain srings like `True` or `False`"""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
value = value.lower()
|
||||
if value == "true":
|
||||
return True
|
||||
elif value == "false":
|
||||
return False
|
||||
raise Exception(f"unknown boolean value {value}")
|
||||
|
||||
|
||||
CONVERT_OPTION = {
|
||||
"string": dict(opttype="StrOption"),
|
||||
"number": dict(opttype="IntOption", func=int),
|
||||
"float": dict(opttype="FloatOption", func=float),
|
||||
"boolean": dict(opttype="BoolOption", func=convert_boolean),
|
||||
"secret": dict(opttype="PasswordOption"),
|
||||
"mail": dict(opttype="EmailOption"),
|
||||
"unix_filename": dict(opttype="FilenameOption"),
|
||||
"date": dict(opttype="DateOption"),
|
||||
"unix_user": dict(opttype="UsernameOption"),
|
||||
"ip": dict(opttype="IPOption", initkwargs={"allow_reserved": True}),
|
||||
"cidr": dict(opttype="IPOption", initkwargs={"cidr": True}),
|
||||
"netmask": dict(opttype="NetmaskOption"),
|
||||
"network": dict(opttype="NetworkOption"),
|
||||
"network_cidr": dict(opttype="NetworkOption", initkwargs={"cidr": True}),
|
||||
"broadcast": dict(opttype="BroadcastOption"),
|
||||
"netbios": dict(
|
||||
opttype="DomainnameOption",
|
||||
initkwargs={"type": "netbios", "warnings_only": True},
|
||||
),
|
||||
"domainname": dict(
|
||||
opttype="DomainnameOption", initkwargs={"type": "domainname", "allow_ip": False}
|
||||
),
|
||||
"hostname": dict(
|
||||
opttype="DomainnameOption", initkwargs={"type": "hostname", "allow_ip": False}
|
||||
),
|
||||
"web_address": dict(
|
||||
opttype="URLOption", initkwargs={"allow_ip": False, "allow_without_dot": True}
|
||||
),
|
||||
"port": dict(opttype="PortOption", initkwargs={"allow_private": True}),
|
||||
"mac": dict(opttype="MACOption"),
|
||||
"unix_permissions": dict(
|
||||
opttype="PermissionsOption", initkwargs={"warnings_only": True}, func=int
|
||||
),
|
||||
"choice": dict(opttype="ChoiceOption"),
|
||||
#
|
||||
"symlink": dict(opttype="SymLinkOption"),
|
||||
}
|
||||
from rougail.object_model import Calculation, VariableCalculation
|
||||
from tiramisu.error import display_list
|
||||
|
||||
|
||||
class Walk:
|
||||
|
|
@ -116,23 +62,106 @@ class Annotator(Walk): # pylint: disable=R0903
|
|||
if not objectspace.paths:
|
||||
return
|
||||
self.objectspace = objectspace
|
||||
self.forbidden_name = [
|
||||
"services",
|
||||
self.objectspace.rougailconfig["variable_namespace"],
|
||||
]
|
||||
for extra in self.objectspace.rougailconfig["extra_dictionaries"]:
|
||||
self.forbidden_name.append(extra)
|
||||
if self.objectspace.main_namespace:
|
||||
self.forbidden_name = [self.objectspace.main_namespace]
|
||||
for extra in self.objectspace.extra_dictionaries:
|
||||
self.forbidden_name.append(extra)
|
||||
else:
|
||||
self.forbidden_name = []
|
||||
# default type inference from a default value with :term:`basic types`
|
||||
self.basic_types = {
|
||||
str: "string",
|
||||
int: "number",
|
||||
bool: "boolean",
|
||||
float: "float",
|
||||
}
|
||||
self.verify_choices()
|
||||
self.convert_variable()
|
||||
self.convert_test()
|
||||
self.convert_examples()
|
||||
self.convert_help()
|
||||
|
||||
def convert_variable(self):
|
||||
"""convert variable"""
|
||||
for variable in self.get_variables():
|
||||
if variable.version != "1.0":
|
||||
if variable.type == "symlink":
|
||||
continue
|
||||
self._convert_variable_inference(variable)
|
||||
for variable in self.get_variables():
|
||||
if variable.type == "symlink":
|
||||
continue
|
||||
if variable.version != "1.0":
|
||||
self._default_variable_copy_informations(variable)
|
||||
if variable.multi is None:
|
||||
variable.multi = False
|
||||
if variable.type is None:
|
||||
variable.type = "string"
|
||||
self.objectspace.informations.add(variable.path, "type", variable.type)
|
||||
self._convert_variable(variable)
|
||||
|
||||
def _convert_variable_inference(
|
||||
self,
|
||||
variable,
|
||||
) -> None:
|
||||
# variable has no type
|
||||
if variable.type is None:
|
||||
# choice type inference from the `choices` attribute
|
||||
if variable.choices is not None:
|
||||
variable.type = "choice"
|
||||
elif variable.regexp is not None:
|
||||
variable.type = "regexp"
|
||||
elif variable.default not in [None, []]:
|
||||
if isinstance(variable.default, list):
|
||||
tested_value = variable.default[0]
|
||||
else:
|
||||
tested_value = variable.default
|
||||
variable.type = self.basic_types.get(type(tested_value), None)
|
||||
# variable has no multi attribute
|
||||
if variable.multi is None and not (
|
||||
variable.type is None and isinstance(variable.default, VariableCalculation)
|
||||
):
|
||||
if variable.path in self.objectspace.leaders:
|
||||
variable.multi = True
|
||||
else:
|
||||
variable.multi = isinstance(variable.default, list)
|
||||
|
||||
def _default_variable_copy_informations(
|
||||
self,
|
||||
variable,
|
||||
) -> None:
|
||||
# if a variable has a variable as default value, that means the type/params or multi should has same value
|
||||
if variable.type is not None or not isinstance(
|
||||
variable.default, VariableCalculation
|
||||
):
|
||||
return
|
||||
# copy type and params
|
||||
calculated_variable_path = variable.default.variable
|
||||
calculated_variable, identifier = self.objectspace.paths.get_with_dynamic(
|
||||
calculated_variable_path,
|
||||
variable.default.path_prefix,
|
||||
variable.path,
|
||||
variable.version,
|
||||
variable.namespace,
|
||||
variable.xmlfiles,
|
||||
)
|
||||
if calculated_variable is None:
|
||||
return
|
||||
variable.type = calculated_variable.type
|
||||
if variable.params is None and calculated_variable.params is not None:
|
||||
variable.params = calculated_variable.params
|
||||
# copy multi attribut
|
||||
if variable.multi is None:
|
||||
calculated_path = calculated_variable.path
|
||||
if (
|
||||
calculated_path in self.objectspace.leaders
|
||||
and variable.path in self.objectspace.followers
|
||||
and calculated_path.rsplit(".")[0] == variable.path.rsplit(".")[0]
|
||||
):
|
||||
variable.multi = False
|
||||
else:
|
||||
variable.multi = calculated_variable.multi
|
||||
|
||||
def _convert_variable(
|
||||
self,
|
||||
variable: dict,
|
||||
|
|
@ -149,25 +178,43 @@ class Annotator(Walk): # pylint: disable=R0903
|
|||
self.objectspace.multis[variable.path] = True
|
||||
if variable.path in self.objectspace.leaders:
|
||||
if not self.objectspace.multis.get(variable.path, False):
|
||||
msg = _(f'the variable "{variable.path}" in a leadership must be multi')
|
||||
raise DictConsistencyError(msg, 32, variable.xmlfiles)
|
||||
variable.multi = self.objectspace.multis[variable.path] = True
|
||||
family = self.objectspace.paths[variable.path.rsplit(".", 1)[0]]
|
||||
if variable.hidden:
|
||||
family.hidden = variable.hidden
|
||||
elif family.hidden:
|
||||
variable.hidden = family.hidden
|
||||
# elif family.hidden:
|
||||
# variable.hidden = family.hidden
|
||||
variable.hidden = None
|
||||
if variable.regexp is not None and variable.type != "regexp":
|
||||
msg = _(
|
||||
'the variable "{0}" has regexp attribut but has not the "regexp" type'
|
||||
).format(variable.path)
|
||||
raise DictConsistencyError(msg, 37, variable.xmlfiles)
|
||||
if variable.mandatory is None:
|
||||
variable.mandatory = True
|
||||
|
||||
def convert_test(self):
|
||||
"""Convert variable tests value"""
|
||||
for variable in self.get_variables():
|
||||
if variable.type == "symlink":
|
||||
continue
|
||||
if variable.test is None:
|
||||
# with we want remove test, we set "" has test value
|
||||
continue
|
||||
self.objectspace.informations.add(
|
||||
variable.path, "test", tuple(variable.test)
|
||||
)
|
||||
|
||||
def convert_examples(self):
|
||||
"""Convert variable tests value"""
|
||||
for variable in self.get_variables():
|
||||
if variable.type == "symlink":
|
||||
continue
|
||||
if variable.examples is None:
|
||||
continue
|
||||
self.objectspace.informations.add(
|
||||
variable.path, "examples", tuple(variable.examples)
|
||||
)
|
||||
|
||||
def convert_help(self):
|
||||
"""Convert variable help"""
|
||||
for variable in self.get_variables():
|
||||
|
|
@ -175,3 +222,46 @@ class Annotator(Walk): # pylint: disable=R0903
|
|||
continue
|
||||
self.objectspace.informations.add(variable.path, "help", variable.help)
|
||||
del variable.help
|
||||
|
||||
def verify_choices(self):
|
||||
for variable in self.get_variables():
|
||||
if variable.type is None and variable.choices:
|
||||
# choice type inference from the `choices` attribute
|
||||
variable.type = "choice"
|
||||
if variable.choices is not None and variable.type != "choice":
|
||||
msg = _(
|
||||
'the variable "{0}" has choices attribut but has not the "choice" type'
|
||||
).format(variable.path)
|
||||
raise DictConsistencyError(msg, 11, variable.xmlfiles)
|
||||
if variable.type != "choice":
|
||||
continue
|
||||
if variable.default is None:
|
||||
continue
|
||||
if None in variable.choices and variable.mandatory is None:
|
||||
variable.mandatory = False
|
||||
if not isinstance(variable.choices, list):
|
||||
continue
|
||||
choices = variable.choices
|
||||
has_calculation = False
|
||||
for choice in choices:
|
||||
if isinstance(choice, Calculation):
|
||||
has_calculation = True
|
||||
break
|
||||
if has_calculation:
|
||||
continue
|
||||
|
||||
default = variable.default
|
||||
if not isinstance(default, list):
|
||||
default = [default]
|
||||
for value in default:
|
||||
if isinstance(value, Calculation):
|
||||
continue
|
||||
if value not in choices:
|
||||
msg = _(
|
||||
'the variable "{0}" has an unvalid default value "{1}" should be in {2}'
|
||||
).format(
|
||||
variable.path,
|
||||
value,
|
||||
display_list(choices, separator="or", add_quote=True),
|
||||
)
|
||||
raise DictConsistencyError(msg, 26, variable.xmlfiles)
|
||||
|
|
|
|||
|
|
@ -12,69 +12,486 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
from os.path import join, abspath, dirname
|
||||
|
||||
from pathlib import Path
|
||||
from tiramisu import Config
|
||||
from ruamel.yaml import YAML
|
||||
from .utils import _, load_modules, normalize_family
|
||||
from .convert import RougailConvert
|
||||
|
||||
|
||||
ROUGAILROOT = "/srv/rougail"
|
||||
DTDDIR = join(dirname(abspath(__file__)), "data")
|
||||
|
||||
|
||||
RougailConfig = {
|
||||
"dictionaries_dir": [join(ROUGAILROOT, "dictionaries")],
|
||||
"extra_dictionaries": {},
|
||||
"services_dir": [join(ROUGAILROOT, "services")],
|
||||
"patches_dir": join(ROUGAILROOT, "patches"),
|
||||
"templates_dir": join(ROUGAILROOT, "templates"),
|
||||
"destinations_dir": join(ROUGAILROOT, "destinations"),
|
||||
"tmp_dir": join(ROUGAILROOT, "tmp"),
|
||||
"dtdfilename": join(DTDDIR, "rougail.dtd"),
|
||||
"yamlschema_filename": join(DTDDIR, "rougail.yml"),
|
||||
"functions_file": join(ROUGAILROOT, "functions.py"),
|
||||
"system_service_directory": "/usr/lib/systemd/system",
|
||||
"systemd_service_destination_directory": "/usr/local/lib",
|
||||
"systemd_service_directory": "/systemd",
|
||||
"systemd_service_file": "rougail.conf",
|
||||
"systemd_service_ip_file": "rougail_ip.conf",
|
||||
"systemd_tmpfile_factory_dir": "/usr/local/lib",
|
||||
"systemd_tmpfile_directory": "/tmpfiles.d",
|
||||
"systemd_tmpfile_file": "0rougail.conf",
|
||||
"systemd_tmpfile_delete_before_create": False,
|
||||
"variable_namespace": "rougail",
|
||||
"variable_namespace_description": "Rougail",
|
||||
"auto_freeze_variable": "server_deployed",
|
||||
"internal_functions": [],
|
||||
"multi_functions": [],
|
||||
"extra_annotators": [],
|
||||
"modes_level": ["basic", "standard", "advanced"],
|
||||
"default_family_mode": "basic",
|
||||
"default_variable_mode": "standard",
|
||||
"default_files_engine": "jinja",
|
||||
"default_files_mode": 644,
|
||||
"default_files_owner": "root",
|
||||
"default_files_group": "root",
|
||||
"default_files_included": "no",
|
||||
"default_overrides_engine": "jinja",
|
||||
"default_service_names_engine": "none",
|
||||
"default_certificate_domain": "rougail.server_name",
|
||||
"base_option_name": "baseoption",
|
||||
"export_with_import": True,
|
||||
"force_convert_dyn_option_description": False,
|
||||
"suffix": "",
|
||||
"tiramisu_cache": None,
|
||||
RENAMED = {
|
||||
"dictionaries_dir": "main_dictionaries",
|
||||
"variable_namespace": "main_namespace",
|
||||
"functions_file": "functions_files",
|
||||
}
|
||||
NOT_IN_TIRAMISU = {
|
||||
"custom_types": {},
|
||||
}
|
||||
SUBMODULES = None
|
||||
|
||||
|
||||
def get_sub_modules():
|
||||
global SUBMODULES
|
||||
if SUBMODULES is None:
|
||||
SUBMODULES = {}
|
||||
for submodule in Path(__file__).parent.iterdir():
|
||||
if submodule.name.startswith("_") or not submodule.is_dir():
|
||||
continue
|
||||
config_file = submodule / "config.py"
|
||||
if config_file.is_file():
|
||||
SUBMODULES[submodule.name] = load_modules(
|
||||
"rougail." + submodule.name + ".config", str(config_file)
|
||||
)
|
||||
return SUBMODULES
|
||||
|
||||
|
||||
def get_level(module):
|
||||
return module["level"]
|
||||
|
||||
|
||||
class _RougailConfig:
|
||||
def __init__(self, backward_compatibility: bool, root, extra_vars: dict):
|
||||
self.backward_compatibility = backward_compatibility
|
||||
self.root = root
|
||||
self.config = Config(
|
||||
self.root,
|
||||
)
|
||||
self.config.property.read_only()
|
||||
self.extra_vars = extra_vars
|
||||
self.not_in_tiramisu = NOT_IN_TIRAMISU | extra_vars
|
||||
for variable, default_value in self.not_in_tiramisu.items():
|
||||
if not isinstance(default_value, str):
|
||||
default_value = default_value.copy()
|
||||
setattr(self, variable, default_value)
|
||||
|
||||
def copy(self):
|
||||
rougailconfig = _RougailConfig(
|
||||
self.backward_compatibility, self.root, self.extra_vars
|
||||
)
|
||||
rougailconfig.config.value.importation(self.config.value.exportation())
|
||||
rougailconfig.config.property.importation(self.config.property.exportation())
|
||||
rougailconfig.config.property.read_only()
|
||||
for variable in self.not_in_tiramisu:
|
||||
value = getattr(self, variable)
|
||||
if not isinstance(value, str):
|
||||
value = value.copy()
|
||||
setattr(rougailconfig, variable, value)
|
||||
return rougailconfig
|
||||
|
||||
def __setitem__(
|
||||
self,
|
||||
key,
|
||||
value,
|
||||
) -> None:
|
||||
if key in self.not_in_tiramisu:
|
||||
setattr(self, key, value)
|
||||
else:
|
||||
self.config.property.read_write()
|
||||
if key == "export_with_import":
|
||||
key = "not_export_with_import"
|
||||
key = RENAMED.get(key, key)
|
||||
option = self.config.option(key)
|
||||
if option.isoptiondescription() and option.isleadership():
|
||||
leader = list(value)
|
||||
option.leader().value.reset()
|
||||
option.leader().value.set(leader)
|
||||
follower = option.followers()[0]
|
||||
for idx, val in enumerate(value.values()):
|
||||
self.config.option(follower.path(), idx).value.set(val)
|
||||
elif key == "not_export_with_import":
|
||||
option.value.set(not value)
|
||||
else:
|
||||
option.value.set(value)
|
||||
self.config.property.read_only()
|
||||
|
||||
def __getitem__(
|
||||
self,
|
||||
key,
|
||||
) -> None:
|
||||
if key in self.not_in_tiramisu:
|
||||
return getattr(self, key)
|
||||
if key == "export_with_import":
|
||||
key = "not_export_with_import"
|
||||
option = self.config.option(key)
|
||||
if option.isoptiondescription() and option.isleadership():
|
||||
return self.get_leadership(option)
|
||||
ret = self.config.option(key).value.get()
|
||||
if key == "not_export_with_import":
|
||||
return not ret
|
||||
return ret
|
||||
|
||||
def get_leadership(self, option) -> dict:
|
||||
leader = None
|
||||
followers = []
|
||||
for opt, value in option.value.get().items():
|
||||
if opt.issymlinkoption():
|
||||
continue
|
||||
if leader is None:
|
||||
leader = value
|
||||
else:
|
||||
followers.append(value)
|
||||
return dict(zip(leader, followers))
|
||||
|
||||
def parse(self, config) -> str:
|
||||
for option in config:
|
||||
if option.isoptiondescription():
|
||||
yield from self.parse(option)
|
||||
elif not option.issymlinkoption():
|
||||
yield f"{option.path()}: {option.value.get()}"
|
||||
|
||||
def __repr__(self):
|
||||
self.config.property.read_write()
|
||||
try:
|
||||
values = "\n".join(self.parse(self.config))
|
||||
except Exception as err:
|
||||
values = str(err)
|
||||
self.config.property.read_only()
|
||||
return values
|
||||
|
||||
|
||||
class FakeRougailConvert(RougailConvert):
|
||||
def __init__(
|
||||
self,
|
||||
add_extra_options: bool,
|
||||
) -> None:
|
||||
self.add_extra_options = add_extra_options
|
||||
super().__init__({})
|
||||
|
||||
def load_config(self) -> None:
|
||||
self.sort_dictionaries_all = False
|
||||
self.main_namespace = None
|
||||
self.suffix = ""
|
||||
self.custom_types = {}
|
||||
self.functions_files = []
|
||||
self.modes_level = []
|
||||
self.extra_annotators = []
|
||||
self.base_option_name = "baseoption"
|
||||
self.export_with_import = True
|
||||
self.internal_functions = []
|
||||
self.plugins = ["structural_commandline"]
|
||||
self.add_extra_options = self.add_extra_options
|
||||
|
||||
|
||||
def get_rougail_config(
|
||||
*,
|
||||
backward_compatibility: bool = True,
|
||||
add_extra_options: bool = True,
|
||||
) -> _RougailConfig:
|
||||
if backward_compatibility:
|
||||
main_namespace_default = "rougail"
|
||||
else:
|
||||
main_namespace_default = "null"
|
||||
rougail_options = f"""default_dictionary_format_version:
|
||||
description: Dictionary format version by default, if not specified in dictionary file
|
||||
alternative_name: v
|
||||
choices:
|
||||
- '1.0'
|
||||
- '1.1'
|
||||
mandatory: false
|
||||
|
||||
main_dictionaries:
|
||||
description: 'Directories where dictionary files are placed'
|
||||
type: unix_filename
|
||||
alternative_name: m
|
||||
params:
|
||||
allow_relative: True
|
||||
test_existence: True
|
||||
types:
|
||||
- directory
|
||||
multi: true
|
||||
|
||||
sort_dictionaries_all:
|
||||
description: Sort dictionaries from differents directories
|
||||
negative_description: Sort dictionaries directory by directory
|
||||
default: false
|
||||
|
||||
main_namespace:
|
||||
description: Main namespace name
|
||||
default: {main_namespace_default}
|
||||
alternative_name: s
|
||||
mandatory: false
|
||||
|
||||
extra_dictionaries:
|
||||
description: Extra namespaces
|
||||
type: leadership
|
||||
disabled:
|
||||
variable: main_namespace
|
||||
when: null
|
||||
|
||||
names:
|
||||
description: 'Extra namespace name'
|
||||
alternative_name: xn
|
||||
multi: true
|
||||
mandatory: false
|
||||
|
||||
directories:
|
||||
description: Directories where extra dictionary files are placed
|
||||
alternative_name: xd
|
||||
type: unix_filename
|
||||
params:
|
||||
allow_relative: true
|
||||
test_existence: true
|
||||
types:
|
||||
- directory
|
||||
multi: true
|
||||
|
||||
upgrade:
|
||||
description: Update dictionaries to newest Rougail format version
|
||||
negative_description: Do not update dictionaries to newest Rougail format version
|
||||
default: false
|
||||
|
||||
upgrade_options:
|
||||
description: Update informations
|
||||
disabled:
|
||||
variable: upgrade
|
||||
when: false
|
||||
|
||||
main_dictionaries:
|
||||
description: 'Directories where dictionary files will be placed'
|
||||
default:
|
||||
variable: __.main_dictionaries
|
||||
|
||||
extra_dictionary:
|
||||
description: 'Directories where extra files will be placed'
|
||||
type: unix_filename
|
||||
params:
|
||||
allow_relative: true
|
||||
test_existence: true
|
||||
types:
|
||||
- directory
|
||||
disabled:
|
||||
variable: __.main_namespace
|
||||
when: null
|
||||
|
||||
functions_files:
|
||||
description: File with functions
|
||||
alternative_name: c
|
||||
type: unix_filename
|
||||
params:
|
||||
allow_relative: true
|
||||
test_existence: true
|
||||
types:
|
||||
- file
|
||||
multi: true
|
||||
mandatory: false
|
||||
|
||||
modes_level:
|
||||
description: All modes level available
|
||||
multi: true
|
||||
mandatory: false
|
||||
"""
|
||||
if backward_compatibility:
|
||||
rougail_options += """
|
||||
default:
|
||||
- basic
|
||||
- standard
|
||||
- advanced
|
||||
"""
|
||||
rougail_options += """
|
||||
default_family_mode:
|
||||
description: Default mode for a family
|
||||
default:
|
||||
jinja: |
|
||||
{% if modes_level %}
|
||||
{{ modes_level[0] }}
|
||||
{% endif %}
|
||||
disabled:
|
||||
jinja: |
|
||||
{% if not modes_level %}
|
||||
No mode
|
||||
{% endif %}
|
||||
validators:
|
||||
- type: jinja
|
||||
jinja: |
|
||||
{% if default_family_mode not in modes_level %}
|
||||
not in modes_level ({modes_level})
|
||||
{% endif %}
|
||||
commandline: false
|
||||
|
||||
default_variable_mode:
|
||||
description: Default mode for a variable
|
||||
default:
|
||||
jinja: |
|
||||
{% if modes_level %}
|
||||
{% if modes_level | length == 1 %}
|
||||
{{ modes_level[0] }}
|
||||
{% else %}
|
||||
{{ modes_level[1] }}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
disabled:
|
||||
jinja: |
|
||||
{% if not modes_level %}
|
||||
No mode
|
||||
{% endif %}
|
||||
validators:
|
||||
- type: jinja
|
||||
jinja: |
|
||||
{% if default_variable_mode not in modes_level %}
|
||||
not in modes_level ({modes_level})
|
||||
{% endif %}
|
||||
commandline: false
|
||||
|
||||
base_option_name:
|
||||
description: Option name for the base option
|
||||
default: baseoption
|
||||
commandline: false
|
||||
|
||||
not_export_with_import:
|
||||
description: In cache file, do not importation of Tiramisu and other dependencies
|
||||
default: false
|
||||
commandline: false
|
||||
|
||||
tiramisu_cache:
|
||||
description: Tiramisu cache filename
|
||||
alternative_name: t
|
||||
type: unix_filename
|
||||
mandatory: false
|
||||
params:
|
||||
allow_relative: true
|
||||
|
||||
internal_functions:
|
||||
description: Name of internal functions that we can use as a function
|
||||
multi: true
|
||||
mandatory: false
|
||||
commandline: false
|
||||
|
||||
extra_annotators:
|
||||
description: Name of extra annotators
|
||||
multi: true
|
||||
mandatory: false
|
||||
commandline: false
|
||||
|
||||
plugins:
|
||||
description: Name of Rougail plugins
|
||||
multi: true
|
||||
mandatory: false
|
||||
commandline: false
|
||||
|
||||
suffix:
|
||||
description: Suffix add to generated option name
|
||||
default: ''
|
||||
mandatory: false
|
||||
commandline: false
|
||||
"""
|
||||
processes = {
|
||||
"structural": [],
|
||||
"output": [],
|
||||
"user data": [],
|
||||
}
|
||||
for module in get_sub_modules().values():
|
||||
data = module.get_rougail_config()
|
||||
processes[data["process"]].append(data)
|
||||
# reorder
|
||||
for process in processes:
|
||||
processes[process] = list(sorted(processes[process], key=get_level))
|
||||
rougail_process = """step: # Load and exporter steps
|
||||
disabled:
|
||||
variable: upgrade"""
|
||||
for process in processes:
|
||||
if processes[process]:
|
||||
objects = processes[process]
|
||||
rougail_process += """
|
||||
{NAME}:
|
||||
description: Select for {NAME}
|
||||
alternative_name: {NAME[0]}
|
||||
choices:
|
||||
""".format(
|
||||
NAME=normalize_family(process),
|
||||
)
|
||||
for obj in objects:
|
||||
rougail_process += f" - {obj['name']}\n"
|
||||
if process == "structural":
|
||||
rougail_process += " commandline: false"
|
||||
elif process == "user data":
|
||||
rougail_process += """ multi: true
|
||||
mandatory: false
|
||||
"""
|
||||
hidden_outputs = [
|
||||
process["name"]
|
||||
for process in processes["output"]
|
||||
if not process.get("allow_user_data", True)
|
||||
]
|
||||
if hidden_outputs:
|
||||
rougail_process += """ hidden:
|
||||
type: jinja
|
||||
jinja: |
|
||||
"""
|
||||
for hidden_output in hidden_outputs:
|
||||
rougail_process += """ {% if _.output == 'NAME' %}
|
||||
Cannot load user data for NAME output
|
||||
{% endif %}
|
||||
""".replace(
|
||||
"NAME", hidden_output
|
||||
)
|
||||
elif objects:
|
||||
rougail_process += " default: {DEFAULT}".format(
|
||||
DEFAULT=objects[0]["name"]
|
||||
)
|
||||
else:
|
||||
if process == 'output':
|
||||
prop = 'hidden'
|
||||
else:
|
||||
prop = 'disabled'
|
||||
rougail_process += """
|
||||
{NAME}:
|
||||
description: Select for {NAME}
|
||||
mandatory: false
|
||||
{PROP}: true
|
||||
multi: true
|
||||
default: ["You haven't installed \\\"{NAME}\\\" package for rougail"]
|
||||
validators:
|
||||
- jinja: Please install a rougail-{NAME}-* package.
|
||||
""".format(
|
||||
NAME=normalize_family(process),
|
||||
PROP=prop,
|
||||
)
|
||||
rougail_options += rougail_process
|
||||
convert = FakeRougailConvert(add_extra_options)
|
||||
convert._init()
|
||||
convert.namespace = None
|
||||
convert.parse_root_file(
|
||||
"rougail.config",
|
||||
"",
|
||||
"1.1",
|
||||
YAML().load(rougail_options),
|
||||
)
|
||||
extra_vars = {}
|
||||
for process in processes:
|
||||
for obj in processes[process]:
|
||||
if "extra_vars" in obj:
|
||||
extra_vars |= obj["extra_vars"]
|
||||
if not "options" in obj:
|
||||
continue
|
||||
convert.parse_root_file(
|
||||
f'rougail.config.{obj["name"]}',
|
||||
"",
|
||||
"1.1",
|
||||
YAML().load(obj["options"]),
|
||||
)
|
||||
|
||||
tiram_obj = convert.save(None)
|
||||
optiondescription = {}
|
||||
exec(tiram_obj, {}, optiondescription) # pylint: disable=W0122
|
||||
return _RougailConfig(
|
||||
backward_compatibility,
|
||||
optiondescription["option_0"],
|
||||
extra_vars=extra_vars,
|
||||
)
|
||||
|
||||
|
||||
RougailConfig = get_rougail_config()
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -11,22 +11,20 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from .i18n import _
|
||||
|
||||
|
||||
|
|
@ -66,10 +64,25 @@ class DictConsistencyError(Exception):
|
|||
|
||||
def __init__(self, msg, errno, xmlfiles):
|
||||
if xmlfiles:
|
||||
msg = _(f"{msg} in {display_xmlfiles(xmlfiles)}")
|
||||
msg = _("{0} in {1}").format(msg, display_xmlfiles(xmlfiles))
|
||||
super().__init__(msg)
|
||||
self.errno = errno
|
||||
|
||||
|
||||
class UpgradeError(Exception):
|
||||
"""Error during XML upgrade"""
|
||||
|
||||
|
||||
## ---- generic exceptions ----
|
||||
|
||||
|
||||
class NotFoundError(Exception):
|
||||
"not found error"
|
||||
pass
|
||||
|
||||
|
||||
## ---- specific exceptions ----
|
||||
|
||||
|
||||
class VariableCalculationDependencyError(Exception):
|
||||
pass
|
||||
|
|
|
|||
|
|
@ -10,51 +10,23 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
import gettext
|
||||
import os
|
||||
import sys
|
||||
import locale
|
||||
|
||||
# Application Name
|
||||
APP_NAME = "rougail"
|
||||
from gettext import translation
|
||||
from pathlib import Path
|
||||
|
||||
# Traduction dir
|
||||
APP_DIR = os.path.join(sys.prefix, "share")
|
||||
LOCALE_DIR = os.path.join(APP_DIR, "locale")
|
||||
|
||||
# Default Lanugage
|
||||
DEFAULT_LANG = os.environ.get("LANG", "").split(":")
|
||||
DEFAULT_LANG += ["en_US"]
|
||||
|
||||
languages = []
|
||||
lc, encoding = locale.getlocale()
|
||||
if lc:
|
||||
languages = [lc]
|
||||
|
||||
languages += DEFAULT_LANG
|
||||
mo_location = LOCALE_DIR
|
||||
|
||||
gettext.find(APP_NAME, mo_location)
|
||||
gettext.textdomain(APP_NAME)
|
||||
# gettext.bind_textdomain_codeset(APP_NAME, "UTF-8")
|
||||
# gettext.translation(APP_NAME, fallback=True)
|
||||
|
||||
t = gettext.translation(APP_NAME, fallback=True)
|
||||
t = translation("rougail", str(Path(__file__).parent / "locale"), fallback=True)
|
||||
|
||||
_ = t.gettext
|
||||
|
|
|
|||
BIN
src/rougail/locale/fr/LC_MESSAGES/rougail.mo
Normal file
BIN
src/rougail/locale/fr/LC_MESSAGES/rougail.mo
Normal file
Binary file not shown.
|
|
@ -3,49 +3,149 @@
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2023-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from typing import Optional, Union, get_type_hints, Any, Literal, List, Dict, Iterator
|
||||
from pydantic import BaseModel, StrictBool, StrictInt, StrictFloat, StrictStr
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
StrictBool,
|
||||
StrictInt,
|
||||
StrictFloat,
|
||||
StrictStr,
|
||||
ConfigDict,
|
||||
)
|
||||
from tiramisu import undefined
|
||||
from .utils import get_jinja_variable_to_param, get_realpath
|
||||
|
||||
from .error import DictConsistencyError, VariableCalculationDependencyError
|
||||
|
||||
BASETYPE = Union[StrictBool, StrictInt, StrictFloat, StrictStr, None]
|
||||
PROPERTY_ATTRIBUTE = ["frozen", "hidden", "disabled", "mandatory"]
|
||||
|
||||
|
||||
def convert_boolean(value: str) -> bool:
|
||||
"""Boolean coercion. The Rougail XML may contain srings like `True` or `False`"""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
value = value.lower()
|
||||
if value == "true":
|
||||
return True
|
||||
elif value == "false":
|
||||
return False
|
||||
elif value in ["", None]:
|
||||
return None
|
||||
raise Exception(f'unknown boolean value "{value}"')
|
||||
|
||||
|
||||
CONVERT_OPTION = {
|
||||
"string": dict(opttype="StrOption", example="example"),
|
||||
"number": dict(opttype="IntOption", func=int, example=42),
|
||||
"float": dict(opttype="FloatOption", func=float, example=1.42),
|
||||
"boolean": dict(opttype="BoolOption", func=convert_boolean),
|
||||
"secret": dict(opttype="PasswordOption", example="secrets"),
|
||||
"mail": dict(opttype="EmailOption", example="user@example.net"),
|
||||
"unix_filename": dict(opttype="FilenameOption", example="/tmp/myfile.txt"),
|
||||
"date": dict(opttype="DateOption", example="2000-01-01"),
|
||||
"unix_user": dict(opttype="UsernameOption", example="username"),
|
||||
"ip": dict(
|
||||
opttype="IPOption", initkwargs={"allow_reserved": True}, example="1.1.1.1"
|
||||
),
|
||||
"cidr": dict(opttype="IPOption", initkwargs={"cidr": True}, example="1.1.1.0/24"),
|
||||
"netmask": dict(opttype="NetmaskOption", example="255.255.255.0"),
|
||||
"network": dict(opttype="NetworkOption", example="1.1.1.0"),
|
||||
"network_cidr": dict(
|
||||
opttype="NetworkOption", initkwargs={"cidr": True}, example="1.1.1.0/24"
|
||||
),
|
||||
"broadcast": dict(opttype="BroadcastOption", example="1.1.1.255"),
|
||||
"netbios": dict(
|
||||
opttype="DomainnameOption",
|
||||
initkwargs={"type": "netbios", "warnings_only": True},
|
||||
example="example",
|
||||
),
|
||||
"domainname": dict(
|
||||
opttype="DomainnameOption",
|
||||
initkwargs={"type": "domainname", "allow_ip": False},
|
||||
example="example.net",
|
||||
),
|
||||
"hostname": dict(
|
||||
opttype="DomainnameOption",
|
||||
initkwargs={"type": "hostname", "allow_ip": False},
|
||||
example="example",
|
||||
),
|
||||
"web_address": dict(
|
||||
opttype="URLOption",
|
||||
initkwargs={"allow_ip": False, "allow_without_dot": True},
|
||||
example="https://example.net",
|
||||
),
|
||||
"port": dict(
|
||||
opttype="PortOption", initkwargs={"allow_private": True}, example="111"
|
||||
),
|
||||
"mac": dict(opttype="MACOption", example="00:00:00:00:00"),
|
||||
"unix_permissions": dict(
|
||||
opttype="PermissionsOption",
|
||||
initkwargs={"warnings_only": True},
|
||||
func=int,
|
||||
example="644",
|
||||
),
|
||||
"choice": dict(opttype="ChoiceOption", example="a_choice"),
|
||||
"regexp": dict(opttype="RegexpOption"),
|
||||
#
|
||||
"symlink": dict(opttype="SymLinkOption"),
|
||||
}
|
||||
|
||||
|
||||
class Param(BaseModel):
|
||||
key: str
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
path,
|
||||
attribute,
|
||||
family_is_dynamic,
|
||||
is_follower,
|
||||
xmlfiles,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class AnyParam(Param):
|
||||
type: str
|
||||
value: BASETYPE
|
||||
value: Union[BASETYPE, List[BASETYPE]]
|
||||
|
||||
|
||||
class VariableParam(Param):
|
||||
type: str
|
||||
variable: str
|
||||
propertyerror: bool = True
|
||||
whole: bool = False
|
||||
optional: bool = False
|
||||
|
||||
|
||||
class SuffixParam(Param):
|
||||
class IdentifierParam(Param):
|
||||
type: str
|
||||
identifier: Optional[int] = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
if not kwargs["family_is_dynamic"]:
|
||||
msg = f'identifier parameter for "{kwargs["attribute"]}" in "{kwargs["path"]}" cannot be set none dynamic family'
|
||||
raise DictConsistencyError(msg, 10, kwargs["xmlfiles"])
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class InformationParam(Param):
|
||||
|
|
@ -57,11 +157,21 @@ class InformationParam(Param):
|
|||
class IndexParam(Param):
|
||||
type: str
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
|
||||
if not kwargs["is_follower"]:
|
||||
msg = f'the variable "{kwargs["path"]}" is not a follower, so cannot have index type for param in "{kwargs["attribute"]}"'
|
||||
raise DictConsistencyError(msg, 25, kwargs["xmlfiles"])
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
PARAM_TYPES = {
|
||||
"any": AnyParam,
|
||||
"variable": VariableParam,
|
||||
"suffix": SuffixParam,
|
||||
"identifier": IdentifierParam,
|
||||
"information": InformationParam,
|
||||
"index": IndexParam,
|
||||
}
|
||||
|
|
@ -70,6 +180,14 @@ PARAM_TYPES = {
|
|||
class Calculation(BaseModel):
|
||||
path_prefix: Optional[str]
|
||||
path: str
|
||||
inside_list: bool
|
||||
version: str
|
||||
ori_path: Optional[str] = None
|
||||
default_values: Any = None
|
||||
namespace: Optional[str]
|
||||
xmlfiles: List[str]
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
def get_realpath(
|
||||
self,
|
||||
|
|
@ -84,24 +202,49 @@ class Calculation(BaseModel):
|
|||
for param_obj in self.params:
|
||||
param = param_obj.model_dump()
|
||||
if param.get("type") == "variable":
|
||||
variable_path = self.get_realpath(param["variable"])
|
||||
variable, suffix, dynamic = objectspace.paths.get_with_dynamic(variable_path)
|
||||
if self.ori_path is None:
|
||||
path = self.path
|
||||
else:
|
||||
path = self.ori_path
|
||||
variable, identifier = objectspace.paths.get_with_dynamic(
|
||||
param["variable"],
|
||||
self.path_prefix,
|
||||
path,
|
||||
self.version,
|
||||
self.namespace,
|
||||
self.xmlfiles,
|
||||
)
|
||||
if not variable:
|
||||
if not param.get("optional"):
|
||||
raise Exception(f"cannot find {variable_path}")
|
||||
msg = f'cannot find variable "{param["variable"]}" defined attribute in "{self.attribute_name}" for "{self.path}"'
|
||||
raise DictConsistencyError(msg, 22, self.xmlfiles)
|
||||
continue
|
||||
if not isinstance(variable, objectspace.variable):
|
||||
raise Exception("pfff it's a family")
|
||||
param["variable"] = variable
|
||||
if suffix:
|
||||
param["suffix"] = suffix
|
||||
param["dynamic"] = dynamic
|
||||
if identifier:
|
||||
param["identifier"] = identifier
|
||||
if param.get("type") == "information":
|
||||
if param["variable"]:
|
||||
variable_path = self.get_realpath(param["variable"])
|
||||
param["variable"] = objectspace.paths[variable_path]
|
||||
if not param["variable"]:
|
||||
raise Exception("pffff")
|
||||
if self.ori_path is None:
|
||||
path = self.path
|
||||
else:
|
||||
path = self.ori_path
|
||||
variable, identifier = objectspace.paths.get_with_dynamic(
|
||||
param["variable"],
|
||||
self.path_prefix,
|
||||
path,
|
||||
self.version,
|
||||
self.namespace,
|
||||
self.xmlfiles,
|
||||
)
|
||||
if not variable:
|
||||
msg = f'cannot find variable "{param["variable"]}" defined in "{self.attribute_name}" for "{self.path}"'
|
||||
raise DictConsistencyError(msg, 14, self.xmlfiles)
|
||||
param["variable"] = variable
|
||||
if identifier:
|
||||
msg = f'variable "{param["variable"]}" defined in "{self.attribute_name}" for "{self.path}" is a dynamic variable'
|
||||
raise DictConsistencyError(msg, 15, self.xmlfiles)
|
||||
else:
|
||||
del param["variable"]
|
||||
params[param.pop("key")] = param
|
||||
|
|
@ -110,12 +253,20 @@ class Calculation(BaseModel):
|
|||
|
||||
class JinjaCalculation(Calculation):
|
||||
attribute_name: Literal[
|
||||
"frozen", "hidden", "mandatory", "disabled", "default", "validators", "choices"
|
||||
"frozen",
|
||||
"hidden",
|
||||
"mandatory",
|
||||
"empty",
|
||||
"disabled",
|
||||
"default",
|
||||
"validators",
|
||||
"choices",
|
||||
"dynamic",
|
||||
]
|
||||
jinja: StrictStr
|
||||
params: Optional[List[Param]] = None
|
||||
return_type: BASETYPE = None
|
||||
inside_list: bool
|
||||
description: Optional[StrictStr] = None
|
||||
|
||||
def _jinja_to_function(
|
||||
self,
|
||||
|
|
@ -140,29 +291,49 @@ class JinjaCalculation(Calculation):
|
|||
"__internal_jinja": jinja_path,
|
||||
"__internal_type": return_type,
|
||||
"__internal_multi": multi,
|
||||
"__internal_files": self.xmlfiles,
|
||||
"__internal_attribute": self.attribute_name,
|
||||
"__internal_variable": self.path,
|
||||
},
|
||||
}
|
||||
if self.default_values:
|
||||
default["params"]["__default_value"] = self.default_values
|
||||
if add_help:
|
||||
default["help"] = function + "_help"
|
||||
if self.params:
|
||||
default["params"] |= self.get_params(objectspace)
|
||||
if params:
|
||||
default["params"] |= params
|
||||
for sub_variable, suffix, true_path, dynamic in get_jinja_variable_to_param(
|
||||
if self.ori_path is None:
|
||||
path = self.path
|
||||
else:
|
||||
path = self.ori_path
|
||||
for sub_variable, identifier, true_path in get_jinja_variable_to_param(
|
||||
path,
|
||||
self.jinja,
|
||||
objectspace,
|
||||
variable.xmlfiles,
|
||||
objectspace.functions,
|
||||
self.path_prefix,
|
||||
self.version,
|
||||
self.namespace,
|
||||
):
|
||||
if isinstance(sub_variable, objectspace.variable):
|
||||
if true_path in default["params"]:
|
||||
continue
|
||||
if isinstance(sub_variable, dict):
|
||||
default["params"][true_path] = {
|
||||
"type": "value",
|
||||
"value": sub_variable,
|
||||
}
|
||||
else:
|
||||
default["params"][true_path] = {
|
||||
"type": "variable",
|
||||
"variable": sub_variable,
|
||||
}
|
||||
if suffix:
|
||||
default["params"][true_path]["suffix"] = suffix
|
||||
default["params"][true_path]["dynamic"] = dynamic
|
||||
if self.version != "1.0":
|
||||
default["params"][true_path]["propertyerror"] = False
|
||||
if identifier:
|
||||
default["params"][true_path]["identifier"] = identifier
|
||||
return default
|
||||
|
||||
def to_function(
|
||||
|
|
@ -195,7 +366,7 @@ class JinjaCalculation(Calculation):
|
|||
False,
|
||||
objectspace,
|
||||
)
|
||||
elif self.attribute_name in ["frozen", "hidden", "disabled", "mandatory"]:
|
||||
elif self.attribute_name in PROPERTY_ATTRIBUTE:
|
||||
if self.return_type:
|
||||
raise Exception("return_type not allowed!")
|
||||
return self._jinja_to_function(
|
||||
|
|
@ -204,7 +375,7 @@ class JinjaCalculation(Calculation):
|
|||
False,
|
||||
objectspace,
|
||||
add_help=True,
|
||||
params={None: [self.attribute_name]},
|
||||
params={None: [self.attribute_name], "when": True, "inverse": False},
|
||||
)
|
||||
elif self.attribute_name == "choices":
|
||||
return_type = self.return_type
|
||||
|
|
@ -216,112 +387,295 @@ class JinjaCalculation(Calculation):
|
|||
not self.inside_list,
|
||||
objectspace,
|
||||
)
|
||||
elif self.attribute_name == "dynamic":
|
||||
return self._jinja_to_function(
|
||||
"jinja_to_function",
|
||||
"string",
|
||||
True,
|
||||
objectspace,
|
||||
)
|
||||
raise Exception("hu?")
|
||||
|
||||
|
||||
class VariableCalculation(Calculation):
|
||||
attribute_name: Literal[
|
||||
"frozen", "hidden", "mandatory", "disabled", "default", "choices"
|
||||
]
|
||||
class _VariableCalculation(Calculation):
|
||||
variable: StrictStr
|
||||
propertyerror: bool = True
|
||||
inside_list: bool
|
||||
allow_none: bool = False
|
||||
|
||||
def to_function(
|
||||
def get_variable(
|
||||
self,
|
||||
objectspace,
|
||||
) -> dict:
|
||||
variable_path = self.get_realpath(self.variable)
|
||||
variable, suffix, dynamic = objectspace.paths.get_with_dynamic(variable_path)
|
||||
if not variable:
|
||||
raise Exception(f"pffff {variable_path}")
|
||||
if not isinstance(variable, objectspace.variable):
|
||||
) -> "Variable":
|
||||
if self.ori_path is None:
|
||||
path = self.path
|
||||
else:
|
||||
path = self.ori_path
|
||||
variable, identifier = objectspace.paths.get_with_dynamic(
|
||||
self.variable,
|
||||
self.path_prefix,
|
||||
path,
|
||||
self.version,
|
||||
self.namespace,
|
||||
self.xmlfiles,
|
||||
)
|
||||
if variable and not isinstance(variable, objectspace.variable):
|
||||
# FIXME remove the pfff
|
||||
raise Exception("pfff it's a family")
|
||||
return variable, identifier
|
||||
|
||||
def get_params(
|
||||
self,
|
||||
objectspace,
|
||||
variable: "Variable",
|
||||
identifier: Optional[str],
|
||||
*,
|
||||
needs_multi: Optional[bool] = None,
|
||||
):
|
||||
if not variable:
|
||||
msg = f'Variable not found "{self.variable}" for attribut "{self.attribute_name}" for variable "{self.path}"'
|
||||
raise DictConsistencyError(msg, 88, self.xmlfiles)
|
||||
param = {
|
||||
"type": "variable",
|
||||
"variable": variable,
|
||||
"propertyerror": self.propertyerror,
|
||||
}
|
||||
if suffix:
|
||||
param["suffix"] = suffix
|
||||
param["dynamic"] = dynamic
|
||||
if identifier:
|
||||
param["identifier"] = identifier
|
||||
params = {None: [param]}
|
||||
function = "calc_value"
|
||||
help_function = None
|
||||
if self.attribute_name in ["frozen", "hidden", "disabled", "mandatory"]:
|
||||
function = "variable_to_property"
|
||||
help_function = "variable_to_property"
|
||||
if variable.type != "boolean":
|
||||
raise Exception("only boolean!")
|
||||
params[None].insert(0, self.attribute_name)
|
||||
elif (
|
||||
self.attribute_name != "default" and variable.path not in objectspace.multis
|
||||
):
|
||||
raise Exception("pffff")
|
||||
if not self.inside_list and self.path in objectspace.multis:
|
||||
if (
|
||||
not objectspace.paths.is_dynamic(variable_path)
|
||||
and variable_path not in objectspace.multis
|
||||
):
|
||||
params["multi"] = True
|
||||
if self.default_values:
|
||||
params["__default_value"] = self.default_values
|
||||
if self.allow_none:
|
||||
params["allow_none"] = True
|
||||
if self.inside_list and variable.path in objectspace.multis:
|
||||
raise Exception("pfff")
|
||||
ret = {
|
||||
"function": function,
|
||||
if needs_multi is None:
|
||||
if self.attribute_name != "default":
|
||||
needs_multi = True
|
||||
else:
|
||||
needs_multi = self.path in objectspace.multis
|
||||
calc_variable_is_multi = variable.path in objectspace.multis
|
||||
if not calc_variable_is_multi:
|
||||
if variable.path in objectspace.paths._dynamics and (
|
||||
identifier is None or identifier[-1] is None
|
||||
):
|
||||
self_dyn_path = objectspace.paths._dynamics.get(self.path)
|
||||
if self_dyn_path is not None:
|
||||
var_dyn_path = objectspace.paths._dynamics[variable.path]
|
||||
if self_dyn_path != var_dyn_path and not self_dyn_path.startswith(
|
||||
f"{var_dyn_path}."
|
||||
):
|
||||
calc_variable_is_multi = True
|
||||
else:
|
||||
calc_variable_is_multi = True
|
||||
elif identifier and "{{ identifier }}" in identifier:
|
||||
calc_variable_is_multi = True
|
||||
if needs_multi:
|
||||
if calc_variable_is_multi:
|
||||
if self.inside_list:
|
||||
msg = f'the variable "{self.path}" has an invalid attribute "{self.attribute_name}", the variable "{variable.path}" is multi but is inside a list'
|
||||
raise DictConsistencyError(msg, 18, self.xmlfiles)
|
||||
elif not self.inside_list:
|
||||
msg = f'the variable "{self.path}" has an invalid attribute "{self.attribute_name}", the variable "{variable.path}" is not multi but is not inside a list'
|
||||
raise DictConsistencyError(msg, 20, self.xmlfiles)
|
||||
elif self.inside_list:
|
||||
msg = f'the variable "{self.path}" has an invalid attribute "{self.attribute_name}", it\'s a list'
|
||||
raise DictConsistencyError(msg, 23, self.xmlfiles)
|
||||
elif calc_variable_is_multi:
|
||||
if (
|
||||
variable.multi
|
||||
or variable.path.rsplit(".", 1)[0] != self.path.rsplit(".", 1)[0]
|
||||
):
|
||||
# it's not a follower or not in same leadership
|
||||
msg = f'the variable "{self.path}" has an invalid attribute "{self.attribute_name}", the variable "{variable.path}" is a multi'
|
||||
raise DictConsistencyError(msg, 21, self.xmlfiles)
|
||||
else:
|
||||
params[None][0]["index"] = {"index": {"type": "index"}}
|
||||
return params
|
||||
|
||||
|
||||
class VariableCalculation(_VariableCalculation):
|
||||
attribute_name: Literal["default", "choices", "dynamic"]
|
||||
optional: bool = False
|
||||
|
||||
def to_function(
|
||||
self,
|
||||
objectspace,
|
||||
) -> dict:
|
||||
if self.attribute_name != "default" and self.optional:
|
||||
msg = f'"{self.attribute_name}" variable shall not have an "optional" attribute for variable "{self.variable}"'
|
||||
raise DictConsistencyError(msg, 33, self.xmlfiles)
|
||||
variable, identifier = self.get_variable(objectspace)
|
||||
if not variable and self.optional:
|
||||
raise VariableCalculationDependencyError()
|
||||
params = self.get_params(
|
||||
objectspace,
|
||||
variable,
|
||||
identifier,
|
||||
)
|
||||
return {
|
||||
"function": "calc_value",
|
||||
"params": params,
|
||||
}
|
||||
if help_function:
|
||||
ret["help"] = help_function
|
||||
return ret
|
||||
|
||||
|
||||
class VariablePropertyCalculation(_VariableCalculation):
|
||||
attribute_name: Literal[*PROPERTY_ATTRIBUTE]
|
||||
when: Any = undefined
|
||||
when_not: Any = undefined
|
||||
|
||||
def to_function(
|
||||
self,
|
||||
objectspace,
|
||||
) -> dict:
|
||||
variable, identifier = self.get_variable(objectspace)
|
||||
params = self.get_params(
|
||||
objectspace,
|
||||
variable,
|
||||
identifier,
|
||||
needs_multi=False,
|
||||
)
|
||||
variable = params[None][0]["variable"]
|
||||
if self.when is not undefined:
|
||||
if self.version == "1.0":
|
||||
msg = f'when is not allowed in format version 1.0 for attribute "{self.attribute_name}" for variable "{self.path}"'
|
||||
raise DictConsistencyError(msg, 103, variable.xmlfiles)
|
||||
if self.when_not is not undefined:
|
||||
msg = f'the variable "{self.path}" has an invalid attribute "{self.attribute_name}", when and when_not cannot set together'
|
||||
raise DictConsistencyError(msg, 31, variable.xmlfiles)
|
||||
when = self.when
|
||||
inverse = False
|
||||
elif self.when_not is not undefined:
|
||||
if self.version == "1.0":
|
||||
msg = f'when_not is not allowed in format version 1.0 for attribute "{self.attribute_name}" for variable "{self.path}"'
|
||||
raise DictConsistencyError(msg, 104, variable.xmlfiles)
|
||||
when = self.when_not
|
||||
inverse = True
|
||||
else:
|
||||
if variable.type != "boolean":
|
||||
raise Exception("only boolean!")
|
||||
when = True
|
||||
inverse = False
|
||||
params[None].insert(0, self.attribute_name)
|
||||
params["when"] = when
|
||||
params["inverse"] = inverse
|
||||
return {
|
||||
"function": "variable_to_property",
|
||||
"params": params,
|
||||
"help": "variable_to_property",
|
||||
}
|
||||
|
||||
|
||||
class InformationCalculation(Calculation):
|
||||
attribute_name: Literal["default"]
|
||||
attribute_name: Literal["default", "choice", "dynamic"]
|
||||
information: StrictStr
|
||||
variable: Optional[StrictStr]
|
||||
inside_list: bool
|
||||
|
||||
def to_function(
|
||||
self,
|
||||
objectspace,
|
||||
) -> dict:
|
||||
param = {
|
||||
"type": "information",
|
||||
"information": self.information,
|
||||
params = {
|
||||
None: [
|
||||
{
|
||||
"type": "information",
|
||||
"information": self.information,
|
||||
}
|
||||
]
|
||||
}
|
||||
if self.variable:
|
||||
variable_path = self.get_realpath(self.variable)
|
||||
variable = objectspace.paths[variable_path]
|
||||
if variable is None:
|
||||
if self.ori_path is None:
|
||||
path = self.path
|
||||
else:
|
||||
path = self.ori_path
|
||||
variable, identifier = objectspace.paths.get_with_dynamic(
|
||||
self.variable,
|
||||
self.path_prefix,
|
||||
path,
|
||||
self.version,
|
||||
self.namespace,
|
||||
self.xmlfiles,
|
||||
)
|
||||
if variable is None or identifier is not None:
|
||||
raise Exception("pfff")
|
||||
param["variable"] = variable
|
||||
params[None][0]["variable"] = variable
|
||||
if self.default_values:
|
||||
params["__default_value"] = self.default_values
|
||||
return {
|
||||
"function": "calc_value",
|
||||
"params": {None: [param]},
|
||||
"params": params,
|
||||
}
|
||||
|
||||
|
||||
class SuffixCalculation(Calculation):
|
||||
attribute_name: Literal["default"]
|
||||
class _IdentifierCalculation(Calculation):
|
||||
identifier: Optional[int] = None
|
||||
|
||||
def get_identifier(self) -> dict:
|
||||
identifier = {"type": "identifier"}
|
||||
if self.identifier is not None:
|
||||
identifier["identifier"] = self.identifier
|
||||
return identifier
|
||||
|
||||
|
||||
class IdentifierCalculation(_IdentifierCalculation):
|
||||
attribute_name: Literal["default", "choice", "dynamic"]
|
||||
|
||||
def to_function(
|
||||
self,
|
||||
objectspace,
|
||||
) -> dict:
|
||||
identifier = {"type": "identifier"}
|
||||
if self.identifier is not None:
|
||||
identifier["identifier"] = self.identifier
|
||||
return {
|
||||
"function": "calc_value",
|
||||
"params": {None: [{"type": "suffix"}]},
|
||||
"params": {None: [self.get_identifier()]},
|
||||
}
|
||||
|
||||
|
||||
class IdentifierPropertyCalculation(_IdentifierCalculation):
|
||||
attribute_name: Literal[*PROPERTY_ATTRIBUTE]
|
||||
when: Any = undefined
|
||||
when_not: Any = undefined
|
||||
|
||||
def to_function(
|
||||
self,
|
||||
objectspace,
|
||||
) -> dict:
|
||||
if self.version == "1.0":
|
||||
msg = f'when is not allowed in format version 1.0 for attribute "{self.attribute_name}"'
|
||||
raise DictConsistencyError(msg, 105, variable.xmlfiles)
|
||||
if self.when is not undefined:
|
||||
if self.when_not is not undefined:
|
||||
msg = f'the identifier has an invalid attribute "{self.attribute_name}", when and when_not cannot set together'
|
||||
raise DictConsistencyError(msg, 35, variable.xmlfiles)
|
||||
when = self.when
|
||||
inverse = False
|
||||
elif self.when_not is not undefined:
|
||||
when = self.when_not
|
||||
inverse = True
|
||||
else:
|
||||
msg = f'the identifier has an invalid attribute "{self.attribute_name}", when and when_not cannot set together'
|
||||
raise DictConsistencyError
|
||||
params = {
|
||||
None: [self.attribute_name, self.get_identifier()],
|
||||
"when": when,
|
||||
"inverse": inverse,
|
||||
}
|
||||
return {
|
||||
"function": "variable_to_property",
|
||||
"params": params,
|
||||
"help": "variable_to_property",
|
||||
}
|
||||
|
||||
|
||||
class IndexCalculation(Calculation):
|
||||
attribute_name: Literal["default"]
|
||||
attribute_name: Literal["default", "choice", "dynamic"]
|
||||
|
||||
def to_function(
|
||||
self,
|
||||
objectspace,
|
||||
) -> dict:
|
||||
if self.path not in objectspace.followers:
|
||||
msg = f'the variable "{self.path}" is not a follower, so cannot have index type for "{self.attribute_name}"'
|
||||
raise DictConsistencyError(msg, 60, self.xmlfiles)
|
||||
return {
|
||||
"function": "calc_value",
|
||||
"params": {None: [{"type": "index"}]},
|
||||
|
|
@ -332,87 +686,80 @@ CALCULATION_TYPES = {
|
|||
"jinja": JinjaCalculation,
|
||||
"variable": VariableCalculation,
|
||||
"information": InformationCalculation,
|
||||
"suffix": SuffixCalculation,
|
||||
"identifier": IdentifierCalculation,
|
||||
"suffix": IdentifierCalculation,
|
||||
"index": IndexCalculation,
|
||||
}
|
||||
BASETYPE_CALC = Union[StrictBool, StrictInt, StrictFloat, StrictStr, None, Calculation]
|
||||
CALCULATION_PROPERTY_TYPES = {
|
||||
"jinja": JinjaCalculation,
|
||||
"variable": VariablePropertyCalculation,
|
||||
"information": InformationCalculation,
|
||||
"identifier": IdentifierPropertyCalculation,
|
||||
"index": IndexCalculation,
|
||||
}
|
||||
BASETYPE_CALC = Union[StrictBool, StrictInt, StrictFloat, StrictStr, Calculation, None]
|
||||
|
||||
|
||||
class Family(BaseModel):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
type: Literal["family", "leadership", "dynamic"] = "family"
|
||||
path: str
|
||||
help: Optional[str] = None
|
||||
mode: Optional[str] = None
|
||||
hidden: Union[bool, Calculation] = False
|
||||
disabled: Union[bool, Calculation] = False
|
||||
namespace: Optional[str]
|
||||
version: str
|
||||
xmlfiles: List[str] = []
|
||||
path: str
|
||||
|
||||
class ConfigDict:
|
||||
arbitrary_types_allowed = True
|
||||
model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
|
||||
|
||||
|
||||
class Dynamic(Family):
|
||||
variable: str
|
||||
# None only for format 1.0
|
||||
variable: str = None
|
||||
dynamic: Union[List[Union[StrictStr, Calculation]], Calculation]
|
||||
|
||||
|
||||
class Variable(BaseModel):
|
||||
# type will be set dynamically in `annotator/value.py`, default is None
|
||||
type: str = None
|
||||
name: str
|
||||
type: Literal[
|
||||
"number",
|
||||
"float",
|
||||
"string",
|
||||
"password",
|
||||
"secret",
|
||||
"mail",
|
||||
"boolean",
|
||||
"unix_filename",
|
||||
"date",
|
||||
"unix_user",
|
||||
"ip",
|
||||
"local_ip",
|
||||
"netmask",
|
||||
"network",
|
||||
"broadcast",
|
||||
"netbios",
|
||||
"domainname",
|
||||
"hostname",
|
||||
"web_address",
|
||||
"port",
|
||||
"mac",
|
||||
"cidr",
|
||||
"network_cidr",
|
||||
"choice",
|
||||
"unix_permissions",
|
||||
] = "string"
|
||||
description: Optional[str] = None
|
||||
default: Union[List[BASETYPE_CALC], BASETYPE_CALC] = None
|
||||
choices: Optional[Union[List[BASETYPE_CALC], Calculation]] = None
|
||||
regexp: Optional[str] = None
|
||||
params: Optional[List[Param]] = None
|
||||
validators: Optional[List[Calculation]] = None
|
||||
multi: bool = False
|
||||
multi: Optional[bool] = None
|
||||
unique: Optional[bool] = None
|
||||
help: Optional[str] = None
|
||||
hidden: Union[bool, Calculation] = False
|
||||
disabled: Union[bool, Calculation] = False
|
||||
mandatory: Union[None, bool, Calculation] = True
|
||||
mandatory: Union[None, bool, Calculation] = None
|
||||
empty: Union[None, bool, Calculation] = True
|
||||
auto_save: bool = False
|
||||
mode: Optional[str] = None
|
||||
test: Optional[list] = None
|
||||
xmlfiles: List[str] = []
|
||||
examples: Optional[list] = None
|
||||
path: str
|
||||
namespace: Optional[str]
|
||||
version: str
|
||||
path_prefix: Optional[str]
|
||||
xmlfiles: List[str] = []
|
||||
|
||||
class ConfigDict:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
|
||||
class Choice(Variable):
|
||||
choices: Union[List[BASETYPE_CALC], Calculation]
|
||||
model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
|
||||
|
||||
|
||||
class SymLink(BaseModel):
|
||||
type: Literal["symlink"] = "symlink"
|
||||
name: str
|
||||
type: str = "symlink"
|
||||
opt: Variable
|
||||
xmlfiles: List[str] = []
|
||||
path: str
|
||||
opt: Variable
|
||||
namespace: Optional[str]
|
||||
version: str
|
||||
path_prefix: Optional[str]
|
||||
xmlfiles: List[str] = []
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
|
|
|||
|
|
@ -1,527 +0,0 @@
|
|||
"""Manage path to find objects
|
||||
|
||||
Created by:
|
||||
EOLE (http://eole.orion.education.fr)
|
||||
Copyright (C) 2005-2018
|
||||
|
||||
Forked by:
|
||||
Cadoles (http://www.cadoles.com)
|
||||
Copyright (C) 2019-2021
|
||||
|
||||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
|
||||
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 2 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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
"""
|
||||
from typing import List
|
||||
from .i18n import _
|
||||
from .error import DictConsistencyError
|
||||
from .utils import normalize_family
|
||||
|
||||
|
||||
class Path:
|
||||
"""Helper class to handle the `path` attribute.
|
||||
|
||||
sample: path="creole.general.condition"
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rougailconfig: "RougailConfig",
|
||||
) -> None:
|
||||
self.variables = {}
|
||||
self.families = {}
|
||||
# self.names = {}
|
||||
self.full_paths_families = {}
|
||||
self.full_paths_variables = {}
|
||||
self.full_dyn_paths_families = {}
|
||||
self.valid_enums = {}
|
||||
self.variable_namespace = rougailconfig["variable_namespace"]
|
||||
self.providers = {}
|
||||
self.suppliers = {}
|
||||
self.list_conditions = {}
|
||||
self.suffix = rougailconfig["suffix"]
|
||||
self.index = 0
|
||||
|
||||
def set_path_prefix(self, prefix: str) -> None:
|
||||
self._path_prefix = prefix
|
||||
if prefix:
|
||||
if None in self.full_paths_families:
|
||||
raise DictConsistencyError(
|
||||
_(f'prefix "{prefix}" cannot be set if a prefix "None" exists'),
|
||||
39,
|
||||
None,
|
||||
)
|
||||
else:
|
||||
for old_prefix in self.full_paths_families:
|
||||
if old_prefix != None:
|
||||
raise DictConsistencyError(
|
||||
_(f"no prefix cannot be set if a prefix exists"), 84, None
|
||||
)
|
||||
if prefix in self.full_paths_families:
|
||||
raise DictConsistencyError(_(f'prefix "{prefix}" already exists'), 83, None)
|
||||
self.full_paths_families[prefix] = {}
|
||||
self.full_paths_variables[prefix] = {}
|
||||
self.valid_enums[prefix] = {}
|
||||
self.providers[prefix] = {}
|
||||
self.suppliers[prefix] = {}
|
||||
self.list_conditions[prefix] = {}
|
||||
|
||||
def has_path_prefix(self) -> bool:
|
||||
return None not in self.full_paths_families
|
||||
|
||||
def get_path_prefixes(self) -> list:
|
||||
return list(self.full_paths_families)
|
||||
|
||||
def get_path_prefix(self) -> str:
|
||||
return self._path_prefix
|
||||
|
||||
# Family
|
||||
def add_family(
|
||||
self,
|
||||
namespace: str,
|
||||
subpath: str,
|
||||
variableobj: str,
|
||||
is_dynamic: str,
|
||||
force_path_prefix: str = None,
|
||||
) -> str: # pylint: disable=C0111
|
||||
"""Add a new family"""
|
||||
if force_path_prefix is None:
|
||||
force_path_prefix = self._path_prefix
|
||||
path = subpath + "." + variableobj.name
|
||||
if namespace == self.variable_namespace:
|
||||
if variableobj.name in self.full_paths_families[force_path_prefix]:
|
||||
msg = _(f'Duplicate family name "{variableobj.name}"')
|
||||
raise DictConsistencyError(msg, 55, variableobj.xmlfiles)
|
||||
self.full_paths_families[force_path_prefix][variableobj.name] = path
|
||||
if is_dynamic:
|
||||
if subpath in self.full_dyn_paths_families:
|
||||
dyn_subpath = self.full_dyn_paths_families[subpath]
|
||||
else:
|
||||
dyn_subpath = subpath
|
||||
self.full_dyn_paths_families[
|
||||
path
|
||||
] = f"{dyn_subpath}.{variableobj.name}{{suffix}}"
|
||||
if path in self.families:
|
||||
msg = _(f'Duplicate family name "{path}"')
|
||||
raise DictConsistencyError(msg, 37, variableobj.xmlfiles)
|
||||
if path in self.variables:
|
||||
msg = _(f'A variable and a family has the same path "{path}"')
|
||||
raise DictConsistencyError(msg, 56, variableobj.xmlfiles)
|
||||
self.families[path] = dict(
|
||||
name=path,
|
||||
namespace=namespace,
|
||||
variableobj=variableobj,
|
||||
)
|
||||
self.set_name(variableobj, "optiondescription_")
|
||||
variableobj.path = path
|
||||
variableobj.path_prefix = force_path_prefix
|
||||
|
||||
def get_family(
|
||||
self,
|
||||
path: str,
|
||||
current_namespace: str,
|
||||
path_prefix: str,
|
||||
allow_variable_namespace: bool = False,
|
||||
) -> "Family": # pylint: disable=C0111
|
||||
"""Get a family"""
|
||||
if (
|
||||
current_namespace == self.variable_namespace or allow_variable_namespace
|
||||
) and path in self.full_paths_families[path_prefix]:
|
||||
path = self.full_paths_families[path_prefix][path]
|
||||
elif allow_variable_namespace and path_prefix:
|
||||
path = f"{path_prefix}.{path}"
|
||||
if path not in self.families:
|
||||
raise DictConsistencyError(_(f'unknown option "{path}"'), 42, [])
|
||||
dico = self.families[path]
|
||||
if current_namespace != dico["namespace"] and (
|
||||
not allow_variable_namespace or current_namespace != self.variable_namespace
|
||||
):
|
||||
msg = _(
|
||||
f'A family located in the "{dico["namespace"]}" namespace '
|
||||
f'shall not be used in the "{current_namespace}" namespace'
|
||||
)
|
||||
raise DictConsistencyError(msg, 38, [])
|
||||
return dico["variableobj"]
|
||||
|
||||
def _get_dyn_path(
|
||||
self,
|
||||
subpath: str,
|
||||
name: bool,
|
||||
) -> str:
|
||||
if subpath in self.full_dyn_paths_families:
|
||||
subpath = self.full_dyn_paths_families[subpath]
|
||||
path = f"{subpath}.{name}{{suffix}}"
|
||||
else:
|
||||
path = f"{subpath}.{name}"
|
||||
return path
|
||||
|
||||
def set_provider(
|
||||
self,
|
||||
variableobj,
|
||||
name,
|
||||
family,
|
||||
):
|
||||
if not hasattr(variableobj, "provider"):
|
||||
return
|
||||
p_name = "provider:" + variableobj.provider
|
||||
if "." in name:
|
||||
msg = f'provider "{p_name}" not allowed in extra'
|
||||
raise DictConsistencyError(msg, 82, variableobj.xmlfiles)
|
||||
if p_name in self.providers[variableobj.path_prefix]:
|
||||
msg = f'provider "{p_name}" declare multiple time'
|
||||
raise DictConsistencyError(msg, 79, variableobj.xmlfiles)
|
||||
self.providers[variableobj.path_prefix][p_name] = {
|
||||
"path": self._get_dyn_path(
|
||||
family,
|
||||
name,
|
||||
),
|
||||
"option": variableobj,
|
||||
}
|
||||
|
||||
def get_provider(
|
||||
self,
|
||||
name: str,
|
||||
path_prefix: str = None,
|
||||
) -> "self.objectspace.variable":
|
||||
return self.providers[path_prefix][name]["option"]
|
||||
|
||||
def get_providers_path(self, path_prefix=None):
|
||||
if path_prefix:
|
||||
return {
|
||||
name: option["path"].split(".", 1)[-1]
|
||||
for name, option in self.providers[path_prefix].items()
|
||||
}
|
||||
return {
|
||||
name: option["path"] for name, option in self.providers[path_prefix].items()
|
||||
}
|
||||
|
||||
def set_supplier(
|
||||
self,
|
||||
variableobj,
|
||||
name,
|
||||
family,
|
||||
):
|
||||
if not hasattr(variableobj, "supplier"):
|
||||
return
|
||||
s_name = "supplier:" + variableobj.supplier
|
||||
if "." in name:
|
||||
msg = f'supplier "{s_name}" not allowed in extra'
|
||||
raise DictConsistencyError(msg, 82, variableobj.xmlfiles)
|
||||
if s_name in self.suppliers[variableobj.path_prefix]:
|
||||
msg = f'supplier "{s_name}" declare multiple time'
|
||||
raise DictConsistencyError(msg, 79, variableobj.xmlfiles)
|
||||
self.suppliers[variableobj.path_prefix][s_name] = {
|
||||
"path": self._get_dyn_path(family, name),
|
||||
"option": variableobj,
|
||||
}
|
||||
|
||||
def get_supplier(
|
||||
self,
|
||||
name: str,
|
||||
path_prefix: str = None,
|
||||
) -> "self.objectspace.variable":
|
||||
return self.suppliers[path_prefix][name]["option"]
|
||||
|
||||
def get_suppliers_path(self, path_prefix=None):
|
||||
if path_prefix:
|
||||
return {
|
||||
name: option["path"].split(".", 1)[-1]
|
||||
for name, option in self.suppliers[path_prefix].items()
|
||||
}
|
||||
return {
|
||||
name: option["path"] for name, option in self.suppliers[path_prefix].items()
|
||||
}
|
||||
|
||||
# Variable
|
||||
def add_variable(
|
||||
self, # pylint: disable=R0913
|
||||
namespace: str,
|
||||
subpath: str,
|
||||
variableobj: "self.objectspace.variable",
|
||||
is_dynamic: bool = False,
|
||||
is_leader: bool = False,
|
||||
force_path_prefix: str = None,
|
||||
) -> str: # pylint: disable=C0111
|
||||
"""Add a new variable (with path)"""
|
||||
if force_path_prefix is None:
|
||||
force_path_prefix = self._path_prefix
|
||||
path = subpath + "." + variableobj.name
|
||||
if namespace == self.variable_namespace:
|
||||
self.full_paths_variables[force_path_prefix][variableobj.name] = path
|
||||
if path in self.families:
|
||||
msg = _(f'A family and a variable has the same path "{path}"')
|
||||
raise DictConsistencyError(msg, 57, variableobj.xmlfiles)
|
||||
if is_leader:
|
||||
leader = subpath
|
||||
else:
|
||||
leader = None
|
||||
self.variables[path] = dict(
|
||||
name=path,
|
||||
family=subpath,
|
||||
leader=leader,
|
||||
is_dynamic=is_dynamic,
|
||||
variableobj=variableobj,
|
||||
)
|
||||
variableobj.path = path
|
||||
variableobj.path_prefix = force_path_prefix
|
||||
self.set_name(variableobj, "option_")
|
||||
|
||||
def set_name(
|
||||
self,
|
||||
variableobj,
|
||||
option_prefix,
|
||||
):
|
||||
self.index += 1
|
||||
variableobj.reflector_name = f"{option_prefix}{self.index}{self.suffix}"
|
||||
|
||||
def get_variable(
|
||||
self,
|
||||
name: str,
|
||||
namespace: str,
|
||||
xmlfiles: List[str] = [],
|
||||
allow_variable_namespace: bool = False,
|
||||
force_path_prefix: str = None,
|
||||
add_path_prefix: bool = False,
|
||||
) -> "Variable": # pylint: disable=C0111
|
||||
"""Get variable object from a path"""
|
||||
if force_path_prefix is None:
|
||||
force_path_prefix = self._path_prefix
|
||||
try:
|
||||
variable, suffix = self._get_variable(
|
||||
name,
|
||||
namespace,
|
||||
with_suffix=True,
|
||||
xmlfiles=xmlfiles,
|
||||
path_prefix=force_path_prefix,
|
||||
add_path_prefix=add_path_prefix,
|
||||
)
|
||||
except DictConsistencyError as err:
|
||||
if (
|
||||
not allow_variable_namespace
|
||||
or err.errno != 42
|
||||
or namespace == self.variable_namespace
|
||||
):
|
||||
raise err from err
|
||||
variable, suffix = self._get_variable(
|
||||
name,
|
||||
self.variable_namespace,
|
||||
with_suffix=True,
|
||||
xmlfiles=xmlfiles,
|
||||
path_prefix=force_path_prefix,
|
||||
)
|
||||
if suffix:
|
||||
raise DictConsistencyError(_(f"{name} is a dynamic variable"), 36, [])
|
||||
return variable["variableobj"]
|
||||
|
||||
def get_variable_family_path(
|
||||
self,
|
||||
name: str,
|
||||
namespace: str,
|
||||
xmlfiles: List[str] = False,
|
||||
force_path_prefix: str = None,
|
||||
) -> str: # pylint: disable=C0111
|
||||
"""Get the full path of a family"""
|
||||
if force_path_prefix is None:
|
||||
force_path_prefix = self._path_prefix
|
||||
return self._get_variable(
|
||||
name,
|
||||
namespace,
|
||||
xmlfiles=xmlfiles,
|
||||
path_prefix=force_path_prefix,
|
||||
)["family"]
|
||||
|
||||
def get_variable_with_suffix(
|
||||
self,
|
||||
name: str,
|
||||
current_namespace: str,
|
||||
xmlfiles: List[str],
|
||||
path_prefix: str,
|
||||
) -> str: # pylint: disable=C0111
|
||||
"""get full path of a variable"""
|
||||
try:
|
||||
dico, suffix = self._get_variable(
|
||||
name,
|
||||
current_namespace,
|
||||
with_suffix=True,
|
||||
xmlfiles=xmlfiles,
|
||||
path_prefix=path_prefix,
|
||||
add_path_prefix=True,
|
||||
)
|
||||
except DictConsistencyError as err:
|
||||
if err.errno != 42 or current_namespace == self.variable_namespace:
|
||||
raise err from err
|
||||
dico, suffix = self._get_variable(
|
||||
name,
|
||||
self.variable_namespace,
|
||||
with_suffix=True,
|
||||
xmlfiles=xmlfiles,
|
||||
path_prefix=path_prefix,
|
||||
add_path_prefix=True,
|
||||
)
|
||||
namespace = dico["variableobj"].namespace
|
||||
if (
|
||||
namespace not in [self.variable_namespace, "services"]
|
||||
and current_namespace != "services"
|
||||
and current_namespace != namespace
|
||||
):
|
||||
msg = _(
|
||||
f'A variable located in the "{namespace}" namespace shall not be used '
|
||||
f'in the "{current_namespace}" namespace'
|
||||
)
|
||||
raise DictConsistencyError(msg, 41, xmlfiles)
|
||||
return dico["variableobj"], suffix
|
||||
|
||||
def path_is_defined(
|
||||
self,
|
||||
path: str,
|
||||
namespace: str,
|
||||
force_path_prefix: str = None,
|
||||
) -> str: # pylint: disable=C0111
|
||||
"""The path is a valid path"""
|
||||
if namespace == self.variable_namespace:
|
||||
if force_path_prefix is None:
|
||||
force_path_prefix = self._path_prefix
|
||||
return path in self.full_paths_variables[force_path_prefix]
|
||||
return path in self.variables
|
||||
|
||||
def get_path(
|
||||
self,
|
||||
path: str,
|
||||
namespace: str,
|
||||
) -> str:
|
||||
if namespace == self.variable_namespace:
|
||||
if path not in self.full_paths_variables[self._path_prefix]:
|
||||
return None
|
||||
path = self.full_paths_variables[self._path_prefix][path]
|
||||
else:
|
||||
path = f"{self._path_prefix}.{path}"
|
||||
return path
|
||||
|
||||
def is_dynamic(self, variableobj) -> bool:
|
||||
"""This variable is in dynamic family"""
|
||||
return self._get_variable(
|
||||
variableobj.path,
|
||||
variableobj.namespace,
|
||||
path_prefix=variableobj.path_prefix,
|
||||
)["is_dynamic"]
|
||||
|
||||
def is_leader(self, variableobj): # pylint: disable=C0111
|
||||
"""Is the variable is a leader"""
|
||||
path = variableobj.path
|
||||
variable = self._get_variable(
|
||||
path,
|
||||
variableobj.namespace,
|
||||
path_prefix=variableobj.path_prefix,
|
||||
)
|
||||
if not variable["leader"]:
|
||||
return False
|
||||
leadership = self.get_family(
|
||||
variable["leader"],
|
||||
variableobj.namespace,
|
||||
path_prefix=variableobj.path_prefix,
|
||||
)
|
||||
return next(iter(leadership.variable.values())).path == path
|
||||
|
||||
def is_follower(self, variableobj) -> bool:
|
||||
"""Is the variable is a follower"""
|
||||
variable = self._get_variable(
|
||||
variableobj.path,
|
||||
variableobj.namespace,
|
||||
path_prefix=variableobj.path_prefix,
|
||||
)
|
||||
if not variable["leader"]:
|
||||
return False
|
||||
leadership = self.get_family(
|
||||
variable["leader"],
|
||||
variableobj.namespace,
|
||||
path_prefix=variableobj.path_prefix,
|
||||
)
|
||||
return next(iter(leadership.variable.values())).path != variableobj.path
|
||||
|
||||
def get_leader(self, variableobj) -> str:
|
||||
variable = self._get_variable(
|
||||
variableobj.path,
|
||||
variableobj.namespace,
|
||||
path_prefix=variableobj.path_prefix,
|
||||
)
|
||||
if not variable["leader"]:
|
||||
raise Exception(f"cannot find leader for {variableobj.path}")
|
||||
leadership = self.get_family(
|
||||
variable["leader"],
|
||||
variableobj.namespace,
|
||||
path_prefix=variableobj.path_prefix,
|
||||
)
|
||||
return next(iter(leadership.variable.values()))
|
||||
|
||||
def _get_variable(
|
||||
self,
|
||||
path: str,
|
||||
namespace: str,
|
||||
with_suffix: bool = False,
|
||||
xmlfiles: List[str] = [],
|
||||
path_prefix: str = None,
|
||||
add_path_prefix: bool = False,
|
||||
) -> str:
|
||||
if namespace == self.variable_namespace:
|
||||
if path in self.full_paths_variables[path_prefix]:
|
||||
path = self.full_paths_variables[path_prefix][path]
|
||||
else:
|
||||
if with_suffix:
|
||||
for var_name, full_path in self.full_paths_variables[
|
||||
path_prefix
|
||||
].items():
|
||||
if not path.startswith(var_name):
|
||||
continue
|
||||
variable = self._get_variable(
|
||||
full_path, namespace, path_prefix=path_prefix
|
||||
)
|
||||
if not variable["is_dynamic"]:
|
||||
continue
|
||||
return variable, path[len(var_name) :]
|
||||
if path_prefix and add_path_prefix:
|
||||
path = f"{path_prefix}.{path}"
|
||||
elif path_prefix and add_path_prefix:
|
||||
path = f"{path_prefix}.{path}"
|
||||
# FIXME with_suffix and variable in extra?
|
||||
if path not in self.variables:
|
||||
raise DictConsistencyError(_(f'unknown option "{path}"'), 42, xmlfiles)
|
||||
if with_suffix:
|
||||
return self.variables[path], None
|
||||
return self.variables[path]
|
||||
|
||||
def set_valid_enums(
|
||||
self,
|
||||
path,
|
||||
values,
|
||||
path_prefix,
|
||||
):
|
||||
self.valid_enums[path_prefix][path] = values
|
||||
|
||||
def has_valid_enums(
|
||||
self,
|
||||
path: str,
|
||||
path_prefix: str,
|
||||
) -> bool:
|
||||
return path in self.valid_enums[path_prefix]
|
||||
|
||||
def get_valid_enums(
|
||||
self,
|
||||
path: str,
|
||||
path_prefix: str,
|
||||
):
|
||||
return self.valid_enums[path_prefix][path]
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
"""Provider/supplier
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
|
||||
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 2 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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
"""
|
||||
# from rougail.objspace import get_variables
|
||||
# from rougail.utils import normalize_family
|
||||
#
|
||||
#
|
||||
# def provider_supplier(objectspace,
|
||||
# path_prefix,
|
||||
# ):
|
||||
# n_path_prefix = normalize_family(path_prefix)
|
||||
# for variable in get_variables(objectspace):
|
||||
# if variable.path_prefix != n_path_prefix:
|
||||
# continue
|
||||
# if hasattr(variable, 'provider'):
|
||||
# family_name, variable.name = variable.path.rsplit('.', 1)
|
||||
# objectspace.paths.set_provider(variable,
|
||||
# variable.name,
|
||||
# family_name,
|
||||
# )
|
||||
# if hasattr(variable, 'supplier'):
|
||||
# family_name, variable.name = variable.path.rsplit('.', 1)
|
||||
# objectspace.paths.set_supplier(variable,
|
||||
# variable.name,
|
||||
# family_name,
|
||||
# )
|
||||
|
|
@ -1,220 +0,0 @@
|
|||
"""load XML and YAML file from directory
|
||||
|
||||
Created by:
|
||||
EOLE (http://eole.orion.education.fr)
|
||||
Copyright (C) 2005-2018
|
||||
|
||||
Forked by:
|
||||
Cadoles (http://www.cadoles.com)
|
||||
Copyright (C) 2019-2021
|
||||
|
||||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
|
||||
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 2 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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
"""
|
||||
from typing import List
|
||||
from os.path import join, isfile
|
||||
from os import listdir
|
||||
|
||||
from lxml.etree import DTD, parse, XMLSyntaxError # pylint: disable=E0611
|
||||
from pykwalify.compat import yml
|
||||
from pykwalify.core import Core
|
||||
from pykwalify.errors import SchemaError
|
||||
|
||||
|
||||
from .i18n import _
|
||||
from .error import DictConsistencyError
|
||||
|
||||
|
||||
FORCE_SUBYAML = ["override"]
|
||||
SCHEMA_DATA = {}
|
||||
|
||||
|
||||
class Reflector:
|
||||
"""Helper class for loading the Creole XML file,
|
||||
parsing it, validating against the Creole DTD
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rougailconfig: "RougailConfig",
|
||||
) -> None:
|
||||
"""Loads the Creole DTD
|
||||
|
||||
:raises IOError: if the DTD is not found
|
||||
|
||||
:param dtdfilename: the full filename of the Creole DTD
|
||||
"""
|
||||
dtdfilename = rougailconfig["dtdfilename"]
|
||||
yamlschema_filename = rougailconfig["yamlschema_filename"]
|
||||
if not isfile(dtdfilename):
|
||||
raise IOError(_(f"no such DTD file: {dtdfilename}"))
|
||||
with open(dtdfilename, "r") as dtdfd:
|
||||
self.dtd = DTD(dtdfd)
|
||||
if not isfile(yamlschema_filename):
|
||||
raise IOError(_(f"no such YAML Schema file: {yamlschema_filename}"))
|
||||
self.yamlschema_filename = yamlschema_filename
|
||||
self.schema_data = None
|
||||
|
||||
def load_dictionaries_from_folders(
|
||||
self,
|
||||
folders: List[str],
|
||||
just_doc: bool,
|
||||
):
|
||||
"""Loads all the dictionary files located in the folders' list
|
||||
|
||||
:param folders: list of full folder's name
|
||||
"""
|
||||
filenames = {}
|
||||
for folder in folders:
|
||||
for filename in listdir(folder):
|
||||
if filename.endswith(".xml"):
|
||||
ext = "xml"
|
||||
full_filename = join(folder, filename)
|
||||
elif filename.endswith(".yml"):
|
||||
ext = "yml"
|
||||
full_filename = join(folder, filename)
|
||||
else:
|
||||
continue
|
||||
if filename in filenames:
|
||||
raise DictConsistencyError(
|
||||
_(f"duplicate dictionary file name {filename}"),
|
||||
78,
|
||||
[filenames[filename][1], full_filename],
|
||||
)
|
||||
filenames[filename] = (ext, full_filename)
|
||||
if not filenames and not just_doc:
|
||||
raise DictConsistencyError(_("there is no dictionary file"), 77, folders)
|
||||
file_names = list(filenames.keys())
|
||||
file_names.sort()
|
||||
for filename in file_names:
|
||||
ext, filename = filenames[filename]
|
||||
if ext == "xml":
|
||||
yield self.load_xml_file(filename)
|
||||
else:
|
||||
yield self.load_yml_file(filename)
|
||||
|
||||
def load_xml_file(
|
||||
self,
|
||||
filename: str,
|
||||
):
|
||||
try:
|
||||
document = parse(filename)
|
||||
except XMLSyntaxError as err:
|
||||
raise DictConsistencyError(
|
||||
_(f"not a XML file: {err}"), 52, [filename]
|
||||
) from err
|
||||
if not self.dtd.validate(document):
|
||||
dtd_error = self.dtd.error_log.filter_from_errors()[0]
|
||||
msg = _(f"not a valid XML file: {dtd_error}")
|
||||
raise DictConsistencyError(msg, 43, [filename])
|
||||
return filename, document.getroot()
|
||||
|
||||
def load_yml_file(
|
||||
self,
|
||||
filename: str,
|
||||
):
|
||||
global SCHEMA_DATA
|
||||
if self.yamlschema_filename not in SCHEMA_DATA:
|
||||
with open(self.yamlschema_filename, "r") as fh:
|
||||
SCHEMA_DATA[self.yamlschema_filename] = yml.load(fh)
|
||||
try:
|
||||
document = Core(
|
||||
source_file=filename,
|
||||
schema_data=SCHEMA_DATA[self.yamlschema_filename],
|
||||
)
|
||||
except XMLSyntaxError as err:
|
||||
raise DictConsistencyError(
|
||||
_(f"not a XML file: {err}"), 52, [filename]
|
||||
) from err
|
||||
try:
|
||||
return filename, YParser(document.validate(raise_exception=True))
|
||||
except SchemaError as yaml_error:
|
||||
msg = _(f"not a valid YAML file: {yaml_error}")
|
||||
raise DictConsistencyError(msg, 43, [filename])
|
||||
|
||||
|
||||
class SubYAML:
|
||||
def __init__(self, key, value):
|
||||
if value is None:
|
||||
value = {}
|
||||
self.tag = key
|
||||
self.dico = value
|
||||
if "text" in value:
|
||||
self.text = value["text"]
|
||||
else:
|
||||
self.text = None
|
||||
if isinstance(value, list):
|
||||
self.attrib = {}
|
||||
else:
|
||||
self.attrib = {
|
||||
k: v
|
||||
for k, v in value.items()
|
||||
if not isinstance(v, list) and k not in FORCE_SUBYAML
|
||||
}
|
||||
|
||||
def __str__(self):
|
||||
return f"<SubYAML {self.tag} at {id(self)}>"
|
||||
|
||||
def __iter__(self):
|
||||
if isinstance(self.dico, list):
|
||||
lists = []
|
||||
for dico in self.dico:
|
||||
for key, value in dico.items():
|
||||
if not isinstance(value, list):
|
||||
value = [value]
|
||||
lists.append((key, value))
|
||||
else:
|
||||
lists = []
|
||||
for key, values in self.dico.items():
|
||||
if key == "variables":
|
||||
for v in values:
|
||||
if "variable" in v:
|
||||
lists.append(("variable", v["variable"]))
|
||||
if "family" in v:
|
||||
lists.append(("family", v["family"]))
|
||||
else:
|
||||
lists.append((key, values))
|
||||
for key, values in lists:
|
||||
if key not in FORCE_SUBYAML and not isinstance(values, list):
|
||||
continue
|
||||
if values is None:
|
||||
values = [None]
|
||||
for value in values:
|
||||
yield SubYAML(key, value)
|
||||
|
||||
def __len__(self):
|
||||
length = 0
|
||||
for _ in self.__iter__():
|
||||
length += 1
|
||||
return length
|
||||
|
||||
|
||||
class YParser:
|
||||
def __init__(self, dico):
|
||||
self.dico = dico
|
||||
|
||||
def __iter__(self):
|
||||
for key, values in self.dico.items():
|
||||
if not isinstance(values, list):
|
||||
continue
|
||||
if key == "variables":
|
||||
yield SubYAML(key, values)
|
||||
else:
|
||||
for val in values:
|
||||
yield SubYAML(key, val)
|
||||
112
src/rougail/structural_commandline/annotator.py
Normal file
112
src/rougail/structural_commandline/annotator.py
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
"""Annotate to add specify attribute for tiramisu-cmdline
|
||||
|
||||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2024
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from rougail.annotator.variable import Walk
|
||||
from rougail.utils import _
|
||||
from rougail.error import DictConsistencyError
|
||||
|
||||
|
||||
class Annotator(Walk):
|
||||
"""Annotate value"""
|
||||
|
||||
level = 80
|
||||
|
||||
def __init__(self, objectspace, *args) -> None:
|
||||
if not objectspace.paths:
|
||||
return
|
||||
self.alternative_names = {}
|
||||
self.objectspace = objectspace
|
||||
not_for_commandlines = []
|
||||
for family in self.get_families():
|
||||
if family.commandline:
|
||||
continue
|
||||
self.not_for_commandline(family)
|
||||
not_for_commandlines.append(family.path + ".")
|
||||
for variable in self.get_variables():
|
||||
if variable.type == "symlink":
|
||||
continue
|
||||
variable_path = variable.path
|
||||
for family_path in not_for_commandlines:
|
||||
if variable_path.startswith(family_path):
|
||||
break
|
||||
else:
|
||||
if not variable.commandline:
|
||||
self.not_for_commandline(variable)
|
||||
else:
|
||||
self.manage_alternative_name(variable)
|
||||
self.manage_negative_description(variable)
|
||||
|
||||
def not_for_commandline(self, variable) -> None:
|
||||
self.objectspace.properties.add(variable.path, "not_for_commandline", True)
|
||||
|
||||
def manage_alternative_name(self, variable) -> None:
|
||||
if not variable.alternative_name:
|
||||
return
|
||||
alternative_name = variable.alternative_name
|
||||
variable_path = variable.path
|
||||
all_letters = ""
|
||||
for letter in alternative_name:
|
||||
all_letters += letter
|
||||
if all_letters == "h":
|
||||
msg = _('alternative_name "{0}" conflict with "--help"').format(
|
||||
alternative_name
|
||||
)
|
||||
raise DictConsistencyError(msg, 202, variable.xmlfiles)
|
||||
if all_letters in self.alternative_names:
|
||||
msg = _('conflict alternative_name "{0}": "{1}" and "{2}"').format(
|
||||
alternative_name, variable_path, self.alternative_names[all_letters]
|
||||
)
|
||||
raise DictConsistencyError(msg, 202, variable.xmlfiles)
|
||||
|
||||
self.alternative_names[alternative_name] = variable_path
|
||||
if "." not in variable_path:
|
||||
path = alternative_name
|
||||
else:
|
||||
path = variable_path.rsplit(".", 1)[0] + "." + alternative_name
|
||||
self.objectspace.add_variable(
|
||||
alternative_name,
|
||||
{"type": "symlink", "path": path, "opt": variable},
|
||||
variable.xmlfiles,
|
||||
False,
|
||||
False,
|
||||
variable.version,
|
||||
)
|
||||
|
||||
def manage_negative_description(self, variable) -> None:
|
||||
if not variable.negative_description:
|
||||
if variable.type == "boolean" and not self.objectspace.add_extra_options:
|
||||
raise DictConsistencyError(
|
||||
_(
|
||||
'negative_description is mandatory for boolean variable, but "{0}" hasn\'t'
|
||||
).format(variable.path),
|
||||
200,
|
||||
variable.xmlfiles,
|
||||
)
|
||||
return
|
||||
if variable.type != "boolean":
|
||||
raise DictConsistencyError(
|
||||
_(
|
||||
'negative_description is only available for boolean variable, but "{0}" is "{1}"'
|
||||
).format(variable.path, variable.type),
|
||||
201,
|
||||
variable.xmlfiles,
|
||||
)
|
||||
self.objectspace.informations.add(
|
||||
variable.path, "negative_description", variable.negative_description
|
||||
)
|
||||
42
src/rougail/structural_commandline/config.py
Normal file
42
src/rougail/structural_commandline/config.py
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
"""
|
||||
Config file for Rougail-structural_commandline
|
||||
|
||||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2024
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
|
||||
def get_rougail_config(
|
||||
*,
|
||||
backward_compatibility=True,
|
||||
) -> dict:
|
||||
options = """
|
||||
structural_commandline:
|
||||
description: Configuration rougail-structural_commandline
|
||||
commandline: false
|
||||
add_extra_options:
|
||||
description: Add extra options to tiramisu-cmdline-parser
|
||||
default: true
|
||||
"""
|
||||
return {
|
||||
"name": "exporter",
|
||||
"process": "structural",
|
||||
"options": options,
|
||||
"level": 20,
|
||||
}
|
||||
|
||||
|
||||
__all__ = "get_rougail_config"
|
||||
34
src/rougail/structural_commandline/object_model.py
Normal file
34
src/rougail/structural_commandline/object_model.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
"""Annotate to add specify attribute for tiramisu-cmdline
|
||||
|
||||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2024
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Variable(BaseModel):
|
||||
alternative_name: Optional[str] = None
|
||||
commandline: bool = True
|
||||
negative_description: Optional[str] = None
|
||||
|
||||
|
||||
class Family(BaseModel):
|
||||
commandline: bool = True
|
||||
|
||||
|
||||
__all__ = ("Variable", "Family")
|
||||
|
|
@ -11,50 +11,231 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
from tiramisu4 import DynOptionDescription
|
||||
from tiramisu5 import DynOptionDescription, calc_value
|
||||
except ModuleNotFoundError:
|
||||
from tiramisu import DynOptionDescription
|
||||
from tiramisu import DynOptionDescription, calc_value
|
||||
from importlib.machinery import SourceFileLoader as _SourceFileLoader
|
||||
from importlib.util import (
|
||||
spec_from_loader as _spec_from_loader,
|
||||
module_from_spec as _module_from_spec,
|
||||
)
|
||||
from jinja2 import StrictUndefined, DictLoader
|
||||
from jinja2.sandbox import SandboxedEnvironment
|
||||
from rougail.object_model import CONVERT_OPTION
|
||||
from rougail.error import display_xmlfiles
|
||||
from tiramisu import function_waiting_for_error
|
||||
from tiramisu.error import ValueWarning, ConfigError, PropertiesOptionError
|
||||
from .utils import normalize_family
|
||||
|
||||
|
||||
global func
|
||||
dict_env = {}
|
||||
ENV = SandboxedEnvironment(loader=DictLoader(dict_env), undefined=StrictUndefined)
|
||||
func = ENV.filters
|
||||
ENV.compile_templates("jinja_caches", zip=None)
|
||||
|
||||
|
||||
class JinjaError:
|
||||
__slot__ = ("_err",)
|
||||
|
||||
def __init__(self, err):
|
||||
self._err = err
|
||||
|
||||
def __str__(self):
|
||||
raise self._err from self._err
|
||||
|
||||
def __repr__(self):
|
||||
raise self._err from self._err
|
||||
|
||||
def __eq__(self, *args, **kwargs):
|
||||
raise self._err from self._err
|
||||
|
||||
def __ge__(self, *args, **kwargs):
|
||||
raise self._err from self._err
|
||||
|
||||
def __gt__(self, *args, **kwargs):
|
||||
raise self._err from self._err
|
||||
|
||||
def __le__(self, *args, **kwargs):
|
||||
raise self._err from self._err
|
||||
|
||||
def __lt__(self, *args, **kwargs):
|
||||
raise self._err from self._err
|
||||
|
||||
def __ne__(self, *args, **kwargs):
|
||||
raise self._err from self._err
|
||||
|
||||
|
||||
def test_propertyerror(value: Any) -> bool:
|
||||
return isinstance(value, JinjaError)
|
||||
|
||||
|
||||
ENV.tests["propertyerror"] = test_propertyerror
|
||||
|
||||
|
||||
def load_functions(path):
|
||||
global _SourceFileLoader, _spec_from_loader, _module_from_spec, func
|
||||
loader = _SourceFileLoader("func", path)
|
||||
spec = _spec_from_loader(loader.name, loader)
|
||||
func_ = _module_from_spec(spec)
|
||||
loader.exec_module(func_)
|
||||
for function in dir(func_):
|
||||
if function.startswith("_"):
|
||||
continue
|
||||
func[function] = getattr(func_, function)
|
||||
|
||||
|
||||
def rougail_calc_value(*args, __default_value=None, **kwargs):
|
||||
values = calc_value(*args, **kwargs)
|
||||
if __default_value is not None and values in [None, []]:
|
||||
return __default_value
|
||||
return values
|
||||
|
||||
|
||||
@function_waiting_for_error
|
||||
def jinja_to_function(
|
||||
__internal_variable,
|
||||
__internal_attribute,
|
||||
__internal_jinja,
|
||||
__internal_type,
|
||||
__internal_multi,
|
||||
__internal_files,
|
||||
__default_value=None,
|
||||
**kwargs,
|
||||
):
|
||||
global ENV, CONVERT_OPTION
|
||||
kw = {}
|
||||
for key, value in kwargs.items():
|
||||
if isinstance(value, PropertiesOptionError):
|
||||
value = JinjaError(value)
|
||||
if "." in key:
|
||||
c_kw = kw
|
||||
path, var = key.rsplit(".", 1)
|
||||
for subkey in path.split("."):
|
||||
c_kw = c_kw.setdefault(subkey, {})
|
||||
c_kw[var] = value
|
||||
else:
|
||||
if key in kw:
|
||||
raise ConfigError(
|
||||
f'internal error, multi key for "{key}" in jinja_to_function'
|
||||
)
|
||||
kw[key] = value
|
||||
try:
|
||||
values = ENV.get_template(__internal_jinja).render(kw, **func).strip()
|
||||
except Exception as err:
|
||||
raise ConfigError(
|
||||
f'cannot calculating "{__internal_attribute}" attribute for variable "{__internal_variable}" in {display_xmlfiles(__internal_files)}: {err}'
|
||||
) from err
|
||||
convert = CONVERT_OPTION[__internal_type].get("func", str)
|
||||
if __internal_multi:
|
||||
values = [convert(val) for val in values.split("\n") if val != ""]
|
||||
if not values and __default_value is not None:
|
||||
return __default_value
|
||||
return values
|
||||
try:
|
||||
values = convert(values)
|
||||
except Exception as err:
|
||||
raise ConfigError(
|
||||
f'cannot converting "{__internal_attribute}" attribute for variable "{__internal_variable}" in {display_xmlfiles(__internal_files)}: {err}'
|
||||
) from err
|
||||
values = values if values != "" and values != "None" else None
|
||||
if values is None and __default_value is not None:
|
||||
return __default_value
|
||||
return values
|
||||
|
||||
|
||||
def variable_to_property(prop, value, when, inverse):
|
||||
if isinstance(value, PropertiesOptionError):
|
||||
raise value from value
|
||||
if inverse:
|
||||
is_match = value != when
|
||||
else:
|
||||
is_match = value == when
|
||||
return prop if is_match else None
|
||||
|
||||
|
||||
@function_waiting_for_error
|
||||
def jinja_to_property(prop, when, inverse, **kwargs):
|
||||
value = func["jinja_to_function"](**kwargs)
|
||||
return func["variable_to_property"](prop, value is not None, when, inverse)
|
||||
|
||||
|
||||
@function_waiting_for_error
|
||||
def jinja_to_property_help(prop, **kwargs):
|
||||
value = func["jinja_to_function"](**kwargs)
|
||||
return (prop, f'"{prop}" ({value})')
|
||||
|
||||
|
||||
@function_waiting_for_error
|
||||
def valid_with_jinja(warnings_only=False, **kwargs):
|
||||
global ValueWarning
|
||||
value = func["jinja_to_function"](**kwargs)
|
||||
if value:
|
||||
if warnings_only:
|
||||
raise ValueWarning(value)
|
||||
else:
|
||||
raise ValueError(value)
|
||||
|
||||
|
||||
func["calc_value"] = rougail_calc_value
|
||||
func["jinja_to_function"] = jinja_to_function
|
||||
func["jinja_to_property"] = jinja_to_property
|
||||
func["jinja_to_property_help"] = jinja_to_property_help
|
||||
func["variable_to_property"] = variable_to_property
|
||||
func["valid_with_jinja"] = valid_with_jinja
|
||||
|
||||
|
||||
class ConvertDynOptionDescription(DynOptionDescription):
|
||||
"""Suffix could be an integer, we should convert it in str
|
||||
Suffix could also contain invalid character, so we should "normalize" it
|
||||
"""Identifier could be an integer, we should convert it in str
|
||||
Identifier could also contain invalid character, so we should "normalize" it
|
||||
"""
|
||||
|
||||
def convert_suffix_to_path(self, suffix):
|
||||
if suffix is None:
|
||||
return suffix
|
||||
if not isinstance(suffix, str):
|
||||
suffix = str(suffix)
|
||||
return normalize_family(suffix)
|
||||
def convert_identifier_to_path(self, identifier):
|
||||
if identifier is None:
|
||||
return identifier
|
||||
if not isinstance(identifier, str):
|
||||
identifier = str(identifier)
|
||||
return normalize_family(identifier)
|
||||
|
||||
def impl_getname(
|
||||
self,
|
||||
suffix=None,
|
||||
identifier=None,
|
||||
) -> str:
|
||||
"""get name"""
|
||||
name = super().impl_getname(None)
|
||||
if suffix is None:
|
||||
if identifier is None:
|
||||
return name
|
||||
path_suffix = self.convert_suffix_to_path(suffix)
|
||||
if "{{ suffix }}" in name:
|
||||
return name.replace("{{ suffix }}", path_suffix)
|
||||
return name + path_suffix
|
||||
path_identifier = self.convert_identifier_to_path(identifier)
|
||||
if "{{ identifier }}" in name:
|
||||
return name.replace("{{ identifier }}", path_identifier)
|
||||
return name + path_identifier
|
||||
|
||||
def impl_get_display_name(
|
||||
self,
|
||||
subconfig,
|
||||
with_quote: bool = False,
|
||||
) -> str:
|
||||
display = super().impl_get_display_name(subconfig, with_quote=with_quote)
|
||||
if "{{ identifier }}" in display:
|
||||
return display.replace(
|
||||
"{{ identifier }}",
|
||||
self.convert_identifier_to_path(self.get_identifiers(subconfig)[-1]),
|
||||
)
|
||||
return display
|
||||
|
|
|
|||
|
|
@ -12,31 +12,28 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
from typing import Optional
|
||||
|
||||
from typing import Optional, Union
|
||||
from json import dumps
|
||||
from os.path import isfile, basename
|
||||
|
||||
from .i18n import _
|
||||
from .annotator import CONVERT_OPTION
|
||||
from .error import DictConsistencyError
|
||||
from .error import DictConsistencyError, VariableCalculationDependencyError
|
||||
from .utils import normalize_family
|
||||
from .object_model import Calculation
|
||||
from .object_model import Calculation, CONVERT_OPTION
|
||||
|
||||
|
||||
class BaseElt: # pylint: disable=R0903
|
||||
|
|
@ -60,176 +57,109 @@ class TiramisuReflector:
|
|||
objectspace,
|
||||
funcs_paths,
|
||||
):
|
||||
self.rougailconfig = objectspace.rougailconfig
|
||||
self.jinja_added = False
|
||||
self.informations_idx = -1
|
||||
self.reflector_objects = {}
|
||||
self.text = {
|
||||
"header": [],
|
||||
"option": [],
|
||||
}
|
||||
if self.rougailconfig["export_with_import"]:
|
||||
if self.rougailconfig["internal_functions"]:
|
||||
for func in self.rougailconfig["internal_functions"]:
|
||||
self.objectspace = objectspace
|
||||
if self.objectspace.export_with_import:
|
||||
if self.objectspace.internal_functions:
|
||||
for func in self.objectspace.internal_functions:
|
||||
self.text["header"].append(f"func[func] = func")
|
||||
self.text["header"].extend(
|
||||
[
|
||||
"from tiramisu import *",
|
||||
"from tiramisu.setting import ALLOWED_LEADER_PROPERTIES",
|
||||
"from re import compile as re_compile",
|
||||
]
|
||||
)
|
||||
if self.objectspace.export_with_import:
|
||||
self.text["header"].extend(
|
||||
[
|
||||
"from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription"
|
||||
]
|
||||
)
|
||||
for mode in self.rougailconfig["modes_level"]:
|
||||
self.text["header"].append(f'ALLOWED_LEADER_PROPERTIES.add("{mode}")')
|
||||
if funcs_paths:
|
||||
if self.rougailconfig["export_with_import"]:
|
||||
self.text["header"].extend(
|
||||
[
|
||||
"from importlib.machinery import SourceFileLoader as _SourceFileLoader",
|
||||
"from importlib.util import spec_from_loader as _spec_from_loader, module_from_spec as _module_from_spec",
|
||||
"global func",
|
||||
"func = {'calc_value': calc_value}",
|
||||
"",
|
||||
"def _load_functions(path):",
|
||||
" global _SourceFileLoader, _spec_from_loader, _module_from_spec, func",
|
||||
" loader = _SourceFileLoader('func', path)",
|
||||
" spec = _spec_from_loader(loader.name, loader)",
|
||||
" func_ = _module_from_spec(spec)",
|
||||
" loader.exec_module(func_)",
|
||||
" for function in dir(func_):",
|
||||
" if function.startswith('_'):",
|
||||
" continue",
|
||||
" func[function] = getattr(func_, function)",
|
||||
]
|
||||
)
|
||||
for funcs_path in sorted(funcs_paths, key=sorted_func_name):
|
||||
if not isfile(funcs_path):
|
||||
continue
|
||||
self.text["header"].append(f"_load_functions('{funcs_path}')")
|
||||
self.objectspace = objectspace
|
||||
self.text["header"].append(f"load_functions('{funcs_path}')")
|
||||
if self.objectspace.export_with_import:
|
||||
if objectspace.main_namespace:
|
||||
self.text["header"].extend(
|
||||
[
|
||||
"try:",
|
||||
" groups.namespace",
|
||||
"except:",
|
||||
" groups.addgroup('namespace')",
|
||||
]
|
||||
)
|
||||
for mode in self.objectspace.modes_level:
|
||||
self.text["header"].append(f'ALLOWED_LEADER_PROPERTIES.add("{mode}")')
|
||||
self.make_tiramisu_objects()
|
||||
if self.rougailconfig["export_with_import"] and (
|
||||
self.rougailconfig["force_convert_dyn_option_description"]
|
||||
or self.objectspace.has_dyn_option is True
|
||||
):
|
||||
self.text["header"].append(
|
||||
"from rougail.tiramisu import ConvertDynOptionDescription"
|
||||
)
|
||||
for key, value in self.objectspace.jinja.items():
|
||||
self.add_jinja_to_function(key, value)
|
||||
|
||||
def add_jinja_support(self):
|
||||
if not self.jinja_added:
|
||||
self.text["header"].extend(
|
||||
[
|
||||
"from jinja2 import StrictUndefined, DictLoader",
|
||||
"from jinja2.sandbox import SandboxedEnvironment",
|
||||
"from rougail.annotator.variable import CONVERT_OPTION",
|
||||
"from tiramisu.error import ValueWarning",
|
||||
"def jinja_to_function(__internal_jinja, __internal_type, __internal_multi, **kwargs):",
|
||||
" global ENV, CONVERT_OPTION",
|
||||
" kw = {}",
|
||||
" for key, value in kwargs.items():",
|
||||
" if '.' in key:",
|
||||
" c_kw = kw",
|
||||
" path, var = key.rsplit('.', 1)",
|
||||
" for subkey in path.split('.'):",
|
||||
" c_kw = c_kw.setdefault(subkey, {})",
|
||||
" c_kw[var] = value",
|
||||
" else:",
|
||||
" kw[key] = value",
|
||||
" values = ENV.get_template(__internal_jinja).render(kw, **func).strip()",
|
||||
" convert = CONVERT_OPTION[__internal_type].get('func', str)",
|
||||
" if __internal_multi:",
|
||||
" return [convert(val) for val in values.split()]",
|
||||
" values = convert(values)",
|
||||
" return values if values != '' and values != 'None' else None",
|
||||
"def variable_to_property(prop, value):",
|
||||
" return prop if value else None",
|
||||
"def jinja_to_property(prop, **kwargs):",
|
||||
" value = func['jinja_to_function'](**kwargs)",
|
||||
" return func['variable_to_property'](prop, value is not None)",
|
||||
"def jinja_to_property_help(prop, **kwargs):",
|
||||
" value = func['jinja_to_function'](**kwargs)",
|
||||
" return (prop, f'\"{prop}\" ({value})')",
|
||||
"def valid_with_jinja(warnings_only=False, **kwargs):",
|
||||
" global ValueWarning",
|
||||
" value = func['jinja_to_function'](**kwargs)",
|
||||
" if value:",
|
||||
" if warnings_only:",
|
||||
" raise ValueWarning(value)",
|
||||
" else:",
|
||||
" raise ValueError(value)",
|
||||
"func['jinja_to_function'] = jinja_to_function",
|
||||
"func['jinja_to_property'] = jinja_to_property",
|
||||
"func['jinja_to_property_help'] = jinja_to_property_help",
|
||||
"func['variable_to_property'] = variable_to_property",
|
||||
"func['valid_with_jinja'] = valid_with_jinja",
|
||||
"dict_env = {}",
|
||||
]
|
||||
)
|
||||
self.jinja_added = True
|
||||
|
||||
def add_jinja_to_function(
|
||||
self,
|
||||
variable_name: str,
|
||||
jinja: str,
|
||||
) -> None:
|
||||
self.add_jinja_support()
|
||||
jinja_text = dumps(jinja, ensure_ascii=False)
|
||||
self.text["header"].append(f"dict_env['{variable_name}'] = {jinja_text}")
|
||||
|
||||
def make_tiramisu_objects(self) -> None:
|
||||
"""make tiramisu objects"""
|
||||
baseelt = BaseElt()
|
||||
self.objectspace.reflector_names[
|
||||
baseelt.path
|
||||
] = f'option_0{self.rougailconfig["suffix"]}'
|
||||
self.objectspace.reflector_names[baseelt.path] = (
|
||||
f"option_0{self.objectspace.suffix}"
|
||||
)
|
||||
basefamily = Family(
|
||||
baseelt,
|
||||
self,
|
||||
)
|
||||
# FIXMEif not self.objectspace.paths.has_path_prefix():
|
||||
if 1:
|
||||
# for elt in self.reorder_family(self.objectspace.space):
|
||||
for elt in self.objectspace.paths.get():
|
||||
if elt.path in self.objectspace.families:
|
||||
Family(
|
||||
elt,
|
||||
self,
|
||||
)
|
||||
else:
|
||||
Variable(
|
||||
elt,
|
||||
self,
|
||||
)
|
||||
else:
|
||||
path_prefixes = self.objectspace.paths.get_path_prefixes()
|
||||
for path_prefix in path_prefixes:
|
||||
space = self.objectspace.space.variables[path_prefix]
|
||||
self.set_name(space)
|
||||
baseprefix = Family(
|
||||
space,
|
||||
for elt in self.objectspace.paths.get():
|
||||
if elt.path in self.objectspace.families:
|
||||
Family(
|
||||
elt,
|
||||
self,
|
||||
)
|
||||
basefamily.add(baseprefix)
|
||||
for elt in self.reorder_family(space):
|
||||
self.populate_family(
|
||||
baseprefix,
|
||||
elt,
|
||||
)
|
||||
if not hasattr(baseprefix.elt, "information"):
|
||||
baseprefix.elt.information = self.objectspace.information(
|
||||
baseprefix.elt.xmlfiles
|
||||
)
|
||||
for key, value in self.objectspace.paths.get_providers_path(
|
||||
path_prefix
|
||||
).items():
|
||||
setattr(baseprefix.elt.information, key, value)
|
||||
for key, value in self.objectspace.paths.get_suppliers_path(
|
||||
path_prefix
|
||||
).items():
|
||||
setattr(baseprefix.elt.information, key, value)
|
||||
baseelt.name = normalize_family(self.rougailconfig["base_option_name"])
|
||||
baseelt.description = self.rougailconfig["base_option_name"]
|
||||
else:
|
||||
Variable(
|
||||
elt,
|
||||
self,
|
||||
)
|
||||
# else:
|
||||
# path_prefixes = self.objectspace.paths.get_path_prefixes()
|
||||
# for path_prefix in path_prefixes:
|
||||
# space = self.objectspace.space.variables[path_prefix]
|
||||
# self.set_name(space)
|
||||
# baseprefix = Family(
|
||||
# space,
|
||||
# self,
|
||||
# )
|
||||
# basefamily.add(baseprefix)
|
||||
# for elt in self.reorder_family(space):
|
||||
# self.populate_family(
|
||||
# baseprefix,
|
||||
# elt,
|
||||
# )
|
||||
# if not hasattr(baseprefix.elt, "information"):
|
||||
# baseprefix.elt.information = self.objectspace.information(
|
||||
# baseprefix.elt.xmlfiles
|
||||
# )
|
||||
# for key, value in self.objectspace.paths.get_providers_path(
|
||||
# path_prefix
|
||||
# ).items():
|
||||
# setattr(baseprefix.elt.information, key, value)
|
||||
# for key, value in self.objectspace.paths.get_suppliers_path(
|
||||
# path_prefix
|
||||
# ).items():
|
||||
# setattr(baseprefix.elt.information, key, value)
|
||||
baseelt.name = normalize_family(self.objectspace.base_option_name)
|
||||
baseelt.description = self.objectspace.base_option_name
|
||||
self.reflector_objects[baseelt.path].get(
|
||||
[], baseelt.description
|
||||
) # pylint: disable=E1101
|
||||
|
|
@ -243,16 +173,12 @@ class TiramisuReflector:
|
|||
self.objectspace.set_name(elt, "optiondescription_")
|
||||
return self.objectspace.reflector_names[elt.path]
|
||||
|
||||
def get_information_name(self):
|
||||
self.informations_idx += 1
|
||||
return f"information_{self.informations_idx}"
|
||||
|
||||
def get_text(self):
|
||||
"""Get text"""
|
||||
if self.jinja_added:
|
||||
self.text["header"].extend(
|
||||
[
|
||||
"ENV = SandboxedEnvironment(loader=DictLoader(dict_env), undefined=StrictUndefined)",
|
||||
"ENV.filters = func",
|
||||
"ENV.compile_templates('jinja_caches', zip=None)",
|
||||
]
|
||||
)
|
||||
return "\n".join(self.text["header"] + self.text["option"])
|
||||
|
||||
|
||||
|
|
@ -270,19 +196,24 @@ class Common:
|
|||
self.tiramisu = tiramisu
|
||||
tiramisu.reflector_objects[elt.path] = self
|
||||
self.object_type = None
|
||||
self.informations = []
|
||||
|
||||
def get(self, calls, parent_name):
|
||||
"""Get tiramisu's object"""
|
||||
self_calls = calls.copy()
|
||||
if self.elt.path in self_calls:
|
||||
if self.elt.path in calls:
|
||||
msg = f'"{self.elt.path}" will make an infinite loop'
|
||||
raise DictConsistencyError(msg, 80, self.elt.xmlfiles)
|
||||
self_calls = calls.copy()
|
||||
self_calls.append(self.elt.path)
|
||||
self.calls = self_calls
|
||||
if self.option_name is None:
|
||||
self.option_name = self.objectspace.reflector_names[self.elt.path]
|
||||
self.populate_attrib()
|
||||
self.populate_informations()
|
||||
if self.informations:
|
||||
for information in self.informations:
|
||||
self.tiramisu.text["option"].append(
|
||||
f"{information}.set_option({self.option_name})"
|
||||
)
|
||||
return self.option_name
|
||||
|
||||
def populate_attrib(self):
|
||||
|
|
@ -295,6 +226,7 @@ class Common:
|
|||
keys["properties"] = self.properties_to_string(
|
||||
self.objectspace.properties[self.elt.path]
|
||||
)
|
||||
self.populate_informations(keys)
|
||||
attrib = ", ".join([f"{key}={value}" for key, value in keys.items()])
|
||||
self.tiramisu.text["option"].append(
|
||||
f"{self.option_name} = {self.object_type}({attrib})"
|
||||
|
|
@ -323,12 +255,11 @@ class Common:
|
|||
for property_, value in values.items():
|
||||
if value is True:
|
||||
properties.append(self.convert_str(property_))
|
||||
elif isinstance(value, list):
|
||||
for val in value:
|
||||
calc_properties.append(self.calculation_value(val))
|
||||
else:
|
||||
if isinstance(value, list):
|
||||
for val in value:
|
||||
calc_properties.append(self.calculation_value(val))
|
||||
else:
|
||||
calc_properties.append(self.calculation_value(value))
|
||||
calc_properties.append(self.calculation_value(value))
|
||||
return "frozenset({" + ", ".join(sorted(properties) + calc_properties) + "})"
|
||||
|
||||
def calc_properties(
|
||||
|
|
@ -351,17 +282,12 @@ class Common:
|
|||
f"kwargs={{{kwargs}}}), func['calc_value_property_help'])"
|
||||
)
|
||||
|
||||
def populate_informations(self):
|
||||
def populate_informations(self, keys):
|
||||
"""Populate Tiramisu's informations"""
|
||||
informations = self.objectspace.informations.get(self.elt.path)
|
||||
if not informations:
|
||||
return
|
||||
for key, value in informations.items():
|
||||
if isinstance(value, str):
|
||||
value = self.convert_str(value)
|
||||
self.tiramisu.text["option"].append(
|
||||
f"{self.option_name}.impl_set_information('{key}', {value})"
|
||||
)
|
||||
keys["informations"] = informations
|
||||
|
||||
def populate_param(
|
||||
self,
|
||||
|
|
@ -374,7 +300,10 @@ class Common:
|
|||
else:
|
||||
value = param
|
||||
return f"ParamValue({value})"
|
||||
if param["type"] == "value":
|
||||
return f"ParamValue({param['value']})"
|
||||
if param["type"] == "information":
|
||||
# default? really?
|
||||
if self.elt.multi:
|
||||
default = []
|
||||
else:
|
||||
|
|
@ -382,18 +311,37 @@ class Common:
|
|||
if "variable" in param:
|
||||
if param["variable"].path == self.elt.path:
|
||||
return f'ParamSelfInformation("{param["information"]}", {default})'
|
||||
return f'ParamInformation("{param["information"]}", {default}, option={self.tiramisu.reflector_objects[param["variable"].path].get(self.calls, self.elt.path)})'
|
||||
information_variable_path = param["variable"].path
|
||||
information_variable = self.tiramisu.reflector_objects[
|
||||
information_variable_path
|
||||
]
|
||||
if information_variable_path not in self.calls:
|
||||
option_name = information_variable.get(self.calls, self.elt.path)
|
||||
return f'ParamInformation("{param["information"]}", {default}, option={option_name})'
|
||||
else:
|
||||
information = (
|
||||
f'ParamInformation("{param["information"]}", {default})'
|
||||
)
|
||||
information_name = self.tiramisu.get_information_name()
|
||||
self.tiramisu.text["option"].append(
|
||||
f"{information_name} = {information}"
|
||||
)
|
||||
information_variable.informations.append(information_name)
|
||||
return information_name
|
||||
return f'ParamInformation("{param["information"]}", {default})'
|
||||
if param["type"] == "suffix":
|
||||
return "ParamSuffix()"
|
||||
if param["type"] == "identifier":
|
||||
if "identifier" in param and param["identifier"] != None:
|
||||
return f"ParamIdentifier(identifier_index={param['identifier']})"
|
||||
return "ParamIdentifier()"
|
||||
if param["type"] == "index":
|
||||
return "ParamIndex()"
|
||||
if param["type"] == "variable":
|
||||
return self.build_option_param(
|
||||
param["variable"],
|
||||
param.get("propertyerror", True),
|
||||
param.get("suffix"),
|
||||
param.get("identifier"),
|
||||
param.get("dynamic"),
|
||||
param.get("whole", False),
|
||||
)
|
||||
if param["type"] == "any":
|
||||
if isinstance(param["value"], str):
|
||||
|
|
@ -405,24 +353,30 @@ class Common:
|
|||
|
||||
def build_option_param(
|
||||
self,
|
||||
param,
|
||||
variable,
|
||||
propertyerror,
|
||||
suffix: Optional[str],
|
||||
identifier: Optional[str],
|
||||
dynamic,
|
||||
whole: bool,
|
||||
) -> str:
|
||||
"""build variable parameters"""
|
||||
if param.path == self.elt.path:
|
||||
return "ParamSelfOption(whole=False)"
|
||||
option_name = self.tiramisu.reflector_objects[param.path].get(
|
||||
if variable.path == self.elt.path:
|
||||
return f"ParamSelfOption(whole={whole})"
|
||||
if whole:
|
||||
msg = f'variable param "{variable.path}" has whole attribute but it\'s not allowed for external variable'
|
||||
raise DictConsistencyError(msg, 34, self.elt.xmlfiles)
|
||||
option_name = self.tiramisu.reflector_objects[variable.path].get(
|
||||
self.calls, self.elt.path
|
||||
)
|
||||
params = [f"{option_name}"]
|
||||
if suffix is not None:
|
||||
if identifier is not None:
|
||||
param_type = "ParamDynOption"
|
||||
family = self.tiramisu.reflector_objects[dynamic.path].get(
|
||||
self.calls, self.elt.path
|
||||
)
|
||||
params.extend([f"'{suffix}'", f"{family}"])
|
||||
identifiers = []
|
||||
for ident in identifier:
|
||||
if isinstance(ident, str):
|
||||
ident = self.convert_str(ident)
|
||||
identifiers.append(str(ident))
|
||||
params.append("[" + ", ".join(identifiers) + "]")
|
||||
else:
|
||||
param_type = "ParamOption"
|
||||
if not propertyerror:
|
||||
|
|
@ -434,7 +388,6 @@ class Common:
|
|||
function,
|
||||
) -> str:
|
||||
"""Generate calculated value"""
|
||||
self.tiramisu.add_jinja_support()
|
||||
child = function.to_function(self.objectspace)
|
||||
new_args = []
|
||||
kwargs = []
|
||||
|
|
@ -454,13 +407,47 @@ class Common:
|
|||
ret += ", kwargs={" + ", ".join(kwargs) + "}"
|
||||
ret += ")"
|
||||
if hasattr(child, "warnings_only"):
|
||||
print("HU????")
|
||||
ret += f", warnings_only={child.warnings_only}"
|
||||
if "help" in child:
|
||||
ret += f", help_function=func['{child['help']}']"
|
||||
ret = ret + ")"
|
||||
return ret
|
||||
|
||||
def populate_calculation(
|
||||
self,
|
||||
datas: Union[Calculation, str, list],
|
||||
return_a_tuple: bool = False,
|
||||
) -> str:
|
||||
if isinstance(datas, str):
|
||||
return self.convert_str(datas)
|
||||
if isinstance(datas, Calculation):
|
||||
return self.calculation_value(datas)
|
||||
if not isinstance(datas, list):
|
||||
return datas
|
||||
params = []
|
||||
for idx, data in enumerate(datas):
|
||||
if isinstance(data, Calculation):
|
||||
try:
|
||||
params.append(self.calculation_value(data))
|
||||
except VariableCalculationDependencyError:
|
||||
pass
|
||||
elif isinstance(data, str):
|
||||
params.append(self.convert_str(data))
|
||||
else:
|
||||
params.append(str(data))
|
||||
if return_a_tuple:
|
||||
ret = "("
|
||||
else:
|
||||
ret = "["
|
||||
ret += ", ".join(params)
|
||||
if return_a_tuple:
|
||||
if len(params) <= 1:
|
||||
ret += ","
|
||||
ret += ")"
|
||||
else:
|
||||
ret += "]"
|
||||
return ret
|
||||
|
||||
|
||||
class Variable(Common):
|
||||
"""Manage variable"""
|
||||
|
|
@ -471,7 +458,10 @@ class Variable(Common):
|
|||
tiramisu,
|
||||
):
|
||||
super().__init__(elt, tiramisu)
|
||||
self.object_type = CONVERT_OPTION[elt.type]["opttype"]
|
||||
if elt.type in self.tiramisu.objectspace.custom_types:
|
||||
self.object_type = self.tiramisu.objectspace.custom_types[elt.type].__name__
|
||||
else:
|
||||
self.object_type = CONVERT_OPTION[elt.type]["opttype"]
|
||||
|
||||
def _populate_attrib(
|
||||
self,
|
||||
|
|
@ -481,58 +471,41 @@ class Variable(Common):
|
|||
keys["opt"] = self.tiramisu.reflector_objects[self.elt.opt.path].get(
|
||||
self.calls, self.elt.path
|
||||
)
|
||||
return
|
||||
if self.elt.type == "choice":
|
||||
choices = self.elt.choices
|
||||
if isinstance(choices, Calculation):
|
||||
keys["values"] = self.calculation_value(choices)
|
||||
else:
|
||||
new_values = []
|
||||
for value in choices:
|
||||
if isinstance(value, Calculation):
|
||||
new_values.append(self.calculation_value(value))
|
||||
elif isinstance(value, str):
|
||||
new_values.append(self.convert_str(value))
|
||||
else:
|
||||
new_values.append(str(value))
|
||||
keys["values"] = "(" + ", ".join(new_values)
|
||||
if len(new_values) <= 1:
|
||||
keys["values"] += ","
|
||||
keys["values"] += ")"
|
||||
keys["values"] = self.populate_calculation(
|
||||
self.elt.choices, return_a_tuple=True
|
||||
)
|
||||
if self.elt.type == "regexp":
|
||||
self.object_type = "Regexp_" + self.option_name
|
||||
self.tiramisu.text["header"].append(
|
||||
f"""class {self.object_type}(RegexpOption):
|
||||
__slots__ = tuple()
|
||||
_type = 'value'
|
||||
{self.object_type}._regexp = re_compile(r"{self.elt.regexp}")
|
||||
"""
|
||||
)
|
||||
if self.elt.path in self.objectspace.multis:
|
||||
keys["multi"] = self.objectspace.multis[self.elt.path]
|
||||
if hasattr(self.elt, "default") and self.elt.default is not None:
|
||||
value = self.elt.default
|
||||
if isinstance(value, str):
|
||||
value = self.convert_str(value)
|
||||
elif isinstance(value, Calculation):
|
||||
value = self.calculation_value(value)
|
||||
elif isinstance(value, list):
|
||||
value = value.copy()
|
||||
for idx, val in enumerate(value):
|
||||
if isinstance(val, Calculation):
|
||||
value[idx] = self.calculation_value(val)
|
||||
else:
|
||||
value[idx] = self.convert_str(val)
|
||||
value = "[" + ", ".join(value) + "]"
|
||||
keys["default"] = value
|
||||
try:
|
||||
keys["default"] = self.populate_calculation(self.elt.default)
|
||||
except VariableCalculationDependencyError:
|
||||
pass
|
||||
if self.elt.path in self.objectspace.default_multi:
|
||||
value = self.objectspace.default_multi[self.elt.path]
|
||||
try:
|
||||
keys["default_multi"] = self.populate_calculation(
|
||||
self.objectspace.default_multi[self.elt.path]
|
||||
)
|
||||
except VariableCalculationDependencyError:
|
||||
pass
|
||||
if self.elt.validators:
|
||||
keys["validators"] = self.populate_calculation(self.elt.validators)
|
||||
for key, value in (
|
||||
CONVERT_OPTION.get(self.elt.type, {}).get("initkwargs", {}).items()
|
||||
):
|
||||
if isinstance(value, str):
|
||||
value = self.convert_str(value)
|
||||
elif isinstance(value, Calculation):
|
||||
value = self.calculation_value(value)
|
||||
keys["default_multi"] = value
|
||||
if self.elt.validators:
|
||||
validators = []
|
||||
for val in self.elt.validators:
|
||||
if isinstance(val, Calculation):
|
||||
validators.append(self.calculation_value(val))
|
||||
else:
|
||||
validators.append(val)
|
||||
keys["validators"] = "[" + ", ".join(validators) + "]"
|
||||
for key, value in CONVERT_OPTION[self.elt.type].get("initkwargs", {}).items():
|
||||
if isinstance(value, str):
|
||||
value = f"'{value}'"
|
||||
keys[key] = value
|
||||
if self.elt.params:
|
||||
for param in self.elt.params:
|
||||
|
|
@ -558,6 +531,10 @@ class Family(Common):
|
|||
self.object_type = "Leadership"
|
||||
else:
|
||||
self.object_type = "OptionDescription"
|
||||
if hasattr(self.elt, "name") and self.elt.name == self.elt.namespace:
|
||||
self.group_type = "groups.namespace"
|
||||
else:
|
||||
self.group_type = None
|
||||
self.children = []
|
||||
|
||||
def add(self, child):
|
||||
|
|
@ -568,13 +545,10 @@ class Family(Common):
|
|||
self,
|
||||
keys: list,
|
||||
) -> None:
|
||||
if self.group_type:
|
||||
keys["group_type"] = self.group_type
|
||||
if self.elt.type == "dynamic":
|
||||
dyn = self.tiramisu.reflector_objects[self.elt.variable.path].get(
|
||||
self.calls, self.elt.path
|
||||
)
|
||||
keys[
|
||||
"suffixes"
|
||||
] = f"Calculation(func['calc_value'], Params((ParamOption({dyn}, notraisepropertyerror=True))))"
|
||||
keys["identifiers"] = self.populate_calculation(self.elt.dynamic)
|
||||
children = []
|
||||
for path in self.objectspace.parents[self.elt.path]:
|
||||
children.append(self.objectspace.paths[path])
|
||||
|
|
|
|||
19
src/rougail/update/__init__.py
Normal file
19
src/rougail/update/__init__.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
"""
|
||||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2024
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from .update import RougailUpgrade
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
"""Update Rougail XML file to new version
|
||||
"""Update Rougail structure file to new version
|
||||
|
||||
Cadoles (http://www.cadoles.com)
|
||||
Copyright (C) 2021
|
||||
|
|
@ -6,55 +6,42 @@ Copyright (C) 2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from typing import List, Any, Optional, Tuple
|
||||
from os.path import join, isfile, isdir, basename
|
||||
from os import listdir, makedirs
|
||||
from os import listdir
|
||||
from os.path import basename, isdir, isfile, join
|
||||
from typing import Any, List, Optional, Tuple
|
||||
|
||||
try:
|
||||
from lxml.etree import parse, XMLParser, XMLSyntaxError # pylint: disable=E0611
|
||||
from lxml.etree import Element, SubElement, tostring
|
||||
from lxml.etree import SubElement # pylint: disable=E0611
|
||||
from lxml.etree import Element, XMLParser, XMLSyntaxError, parse, tostring
|
||||
except ModuleNotFoundError as err:
|
||||
parse = None
|
||||
|
||||
# from ast import parse as ast_parse
|
||||
from json import dumps
|
||||
from yaml import safe_load, dump, SafeDumper
|
||||
from ruamel.yaml import YAML
|
||||
from pathlib import Path
|
||||
|
||||
from .i18n import _
|
||||
from .error import UpgradeError
|
||||
from ..config import RougailConfig
|
||||
from ..error import UpgradeError
|
||||
from ..i18n import _
|
||||
from ..object_model import CONVERT_OPTION
|
||||
from ..utils import normalize_family
|
||||
|
||||
from .utils import normalize_family
|
||||
from .config import RougailConfig
|
||||
from .annotator.variable import CONVERT_OPTION
|
||||
|
||||
|
||||
VERSIONS = ["0.10", "1.0"]
|
||||
|
||||
FIXME_PRINT_FILENAME = True
|
||||
FIXME_PRINT_FILENAME = False
|
||||
FIXME_PRINT_FILE = True
|
||||
FIXME_PRINT_FILE = False
|
||||
FIXME_PRINT_UNKNOWN_VAR = True
|
||||
FIXME_PRINT_UNKNOWN_VAR = False
|
||||
FIXME_PRINT_REMOVE = True
|
||||
FIXME_PRINT_REMOVE = False
|
||||
VERSIONS = ["0.10", "1.0", "1.1"]
|
||||
|
||||
|
||||
def get_function_name(version):
|
||||
|
|
@ -65,24 +52,15 @@ def get_function_name(version):
|
|||
FUNCTION_VERSIONS = [(version, get_function_name(version)) for version in VERSIONS]
|
||||
|
||||
|
||||
class NoAliasDumper(SafeDumper):
|
||||
def ignore_aliases(self, data):
|
||||
return True
|
||||
|
||||
|
||||
class upgrade_010_to_100:
|
||||
class upgrade_010_to_10:
|
||||
def __init__(
|
||||
self,
|
||||
dico: dict,
|
||||
namespace: str,
|
||||
xmlsrc: str,
|
||||
) -> None:
|
||||
if FIXME_PRINT_FILE:
|
||||
from pprint import pprint
|
||||
|
||||
pprint(dico)
|
||||
self.xmlsrc = xmlsrc
|
||||
self.paths = {"family": {}, "variable": {}}
|
||||
self.paths = {"family": {}, "variable": {}, "dynamic": {}}
|
||||
self.lists = {
|
||||
"service": {},
|
||||
"ip": {},
|
||||
|
|
@ -90,26 +68,37 @@ class upgrade_010_to_100:
|
|||
"file": {},
|
||||
}
|
||||
self.flatten_paths = {"family": {}, "variable": {}}
|
||||
self.variables = self.parse_variables(dico, namespace)
|
||||
self.variables = self.parse_variables(dico, namespace, namespace, root=True)
|
||||
self.parse_variables_with_path()
|
||||
self.parse_services(dico)
|
||||
self.parse_constraints(dico)
|
||||
if FIXME_PRINT_FILE:
|
||||
print("==")
|
||||
pprint(self.variables)
|
||||
pprint(self.services)
|
||||
|
||||
def parse_variables(
|
||||
self,
|
||||
family: dict,
|
||||
sub_path: str,
|
||||
true_sub_path: str,
|
||||
*,
|
||||
root: bool = False,
|
||||
is_dynamic: bool = False,
|
||||
) -> dict:
|
||||
new_families = {}
|
||||
if root:
|
||||
new_families["version"] = None
|
||||
if "variables" in family:
|
||||
for subelt in family["variables"]:
|
||||
for typ, obj in subelt.items():
|
||||
for subobj in obj:
|
||||
getattr(self, f"convert_{typ}")(subobj, new_families, sub_path)
|
||||
local_is_dynamic = (
|
||||
is_dynamic or subobj.get("dynamic") is not None
|
||||
)
|
||||
getattr(self, f"convert_{typ}")(
|
||||
subobj,
|
||||
new_families,
|
||||
sub_path,
|
||||
true_sub_path,
|
||||
local_is_dynamic,
|
||||
)
|
||||
family.pop("variables")
|
||||
return new_families
|
||||
|
||||
|
|
@ -118,9 +107,17 @@ class upgrade_010_to_100:
|
|||
family: dict,
|
||||
new_families: dict,
|
||||
sub_path: str,
|
||||
true_sub_path: str,
|
||||
is_dynamic: bool,
|
||||
) -> None:
|
||||
# name is the key, do not let it in values
|
||||
name = family.pop("name")
|
||||
if true_sub_path:
|
||||
true_sub_path = true_sub_path + "." + name
|
||||
else:
|
||||
true_sub_path = name
|
||||
if is_dynamic:
|
||||
name += "{{ suffix }}"
|
||||
if sub_path:
|
||||
sub_path = sub_path + "." + name
|
||||
else:
|
||||
|
|
@ -134,7 +131,9 @@ class upgrade_010_to_100:
|
|||
if typ == "dynamic":
|
||||
family["variable"] = self.get_variable_path(value)
|
||||
# add sub families and sub variables
|
||||
sub_families = self.parse_variables(family, sub_path)
|
||||
sub_families = self.parse_variables(
|
||||
family, sub_path, true_sub_path, is_dynamic=is_dynamic
|
||||
)
|
||||
for sub_name, sub_family in sub_families.copy().items():
|
||||
if sub_name not in family:
|
||||
continue
|
||||
|
|
@ -150,22 +149,34 @@ class upgrade_010_to_100:
|
|||
variable: dict,
|
||||
new_families: dict,
|
||||
sub_path: str,
|
||||
true_sub_path: str,
|
||||
is_dynamic: bool,
|
||||
) -> dict:
|
||||
name = variable.pop("name")
|
||||
if is_dynamic:
|
||||
if true_sub_path:
|
||||
true_sub_path = true_sub_path + "." + name
|
||||
else:
|
||||
true_sub_path = name
|
||||
self.flatten_paths["variable"][name] = true_sub_path
|
||||
name += "{{ suffix }}"
|
||||
if sub_path:
|
||||
sub_path = sub_path + "." + name
|
||||
else:
|
||||
sub_path = name
|
||||
if is_dynamic:
|
||||
self.paths["dynamic"][true_sub_path] = sub_path
|
||||
new_families[name] = variable
|
||||
self.flatten_paths["variable"][name] = sub_path
|
||||
self.paths["variable"][sub_path] = variable
|
||||
if "redefine" not in variable and "value" not in variable and "mandatory" not in variable and ("type" not in variable or variable["type"] != "boolean"):
|
||||
if (
|
||||
"redefine" not in variable
|
||||
and "value" not in variable
|
||||
and "mandatory" not in variable
|
||||
and ("type" not in variable or variable["type"] != "boolean")
|
||||
):
|
||||
variable["mandatory"] = False
|
||||
if "remove_condition" in variable and variable.pop("remove_condition"):
|
||||
if FIXME_PRINT_REMOVE:
|
||||
print(
|
||||
f"variable {name} in file {self.xmlsrc} has remove_condition, all properties (hidden, disabled and mandatory) are set to False"
|
||||
)
|
||||
for prop in ["hidden", "disabled", "mandatory"]:
|
||||
if prop not in variable:
|
||||
variable[prop] = False
|
||||
|
|
@ -194,24 +205,34 @@ class upgrade_010_to_100:
|
|||
)(test)
|
||||
)
|
||||
variable["test"] = tests
|
||||
if variable.get("mandatory", False):
|
||||
del variable["mandatory"]
|
||||
CONVERT_TYPE = {
|
||||
"filename": "unix_filename",
|
||||
"password": "secret",
|
||||
}
|
||||
if variable.get("type") in CONVERT_TYPE:
|
||||
variable["type"] = CONVERT_TYPE[variable["type"]]
|
||||
|
||||
def parse_variables_with_path(self):
|
||||
for variable in self.paths["variable"].values():
|
||||
multi = variable.get("multi", False)
|
||||
if "value" in variable:
|
||||
default = variable.pop("value")
|
||||
if default is not None:
|
||||
if not variable.get("multi", False) and len(default) == 1:
|
||||
variable["default"] = self.get_value(default[0])
|
||||
if not multi and len(default) == 1:
|
||||
variable["default"] = self.get_value(default[0], multi)
|
||||
else:
|
||||
variable["default"] = [
|
||||
self.get_value(value) for value in default
|
||||
self.get_value(value, multi) for value in default
|
||||
]
|
||||
if "choice" in variable:
|
||||
if not variable["choice"]:
|
||||
variable["choices"] = variable.pop("choice")
|
||||
else:
|
||||
variable["choices"] = [
|
||||
self.get_value(choice) for choice in variable.pop("choice")
|
||||
self.get_value(choice, multi)
|
||||
for choice in variable.pop("choice")
|
||||
]
|
||||
|
||||
def parse_services(
|
||||
|
|
@ -327,34 +348,43 @@ class upgrade_010_to_100:
|
|||
apply_on_fallback = False
|
||||
source = self.get_variable_path(condition["source"])
|
||||
if not source:
|
||||
source = f'__{condition["source"]}'
|
||||
source = condition["source"]
|
||||
name = condition.pop("name")
|
||||
prop = name.split("_", 1)[0]
|
||||
if apply_on_fallback:
|
||||
condition_value = True
|
||||
else:
|
||||
condition_value = self.params_condition_to_jinja(
|
||||
source, condition["param"], name.endswith("if_in")
|
||||
)
|
||||
multi = False
|
||||
for target in condition["target"]:
|
||||
typ = target.get("type", "variable")
|
||||
if typ == "variable":
|
||||
variable_path = self.get_variable_path(target["text"])
|
||||
if variable_path is None:
|
||||
continue
|
||||
variable = self.paths["variable"][variable_path]
|
||||
if variable.get("multi", False):
|
||||
multi = True
|
||||
if apply_on_fallback:
|
||||
condition_value = True
|
||||
else:
|
||||
if "{{ suffix }}" in source:
|
||||
force_param = {"__var": source}
|
||||
source = "__var"
|
||||
else:
|
||||
force_param = None
|
||||
condition_value = self.params_condition_to_jinja(
|
||||
prop, source, condition["param"], name.endswith("if_in"), multi
|
||||
)
|
||||
if force_param:
|
||||
condition_value.setdefault("params", {}).update(force_param)
|
||||
for target in condition["target"]:
|
||||
typ = target.get("type", "variable")
|
||||
if typ == "variable":
|
||||
variable_path = self.get_variable_path(target["text"])
|
||||
if variable_path is None:
|
||||
if FIXME_PRINT_UNKNOWN_VAR and not target.get("optional", False):
|
||||
print(
|
||||
f'pffff la target {target["text"]} de la condition n\'est pas trouvable'
|
||||
)
|
||||
continue
|
||||
variable = self.paths["variable"][variable_path]
|
||||
variable[prop] = condition_value
|
||||
elif typ == "family":
|
||||
family_path = self.get_family_path(target["text"])
|
||||
if family_path is None:
|
||||
if FIXME_PRINT_UNKNOWN_VAR and not target.get("optional", False):
|
||||
print(
|
||||
f'pffff la target {target["text"]} de la condition n\'est pas trouvable'
|
||||
)
|
||||
continue
|
||||
family = self.paths["family"][family_path]
|
||||
family[prop] = condition_value
|
||||
|
|
@ -386,10 +416,6 @@ class upgrade_010_to_100:
|
|||
for target in check["target"]:
|
||||
variable_path = self.get_variable_path(target["text"])
|
||||
if variable_path is None:
|
||||
if FIXME_PRINT_UNKNOWN_VAR and not target.get("optional", False):
|
||||
print(
|
||||
f'pffff la target {target["text"]} dans le check n\'est pas trouvable'
|
||||
)
|
||||
continue
|
||||
variable = self.paths["variable"][variable_path]
|
||||
if "validators" in variable and variable["validators"] is None:
|
||||
|
|
@ -400,7 +426,9 @@ class upgrade_010_to_100:
|
|||
check["param"] = [
|
||||
{"text": variable_path, "type": "variable"}
|
||||
] + check.get("param", [])
|
||||
check_value = self.convert_param_function(check)
|
||||
check_value = self.convert_param_function(
|
||||
check, variable.get("multi", False)
|
||||
)
|
||||
variable.setdefault("validators", []).append(check_value)
|
||||
|
||||
def parse_fill(
|
||||
|
|
@ -410,27 +438,34 @@ class upgrade_010_to_100:
|
|||
for target in fill.pop("target"):
|
||||
params = []
|
||||
variable_path = self.get_variable_path(target["text"])
|
||||
if variable_path is None:
|
||||
if FIXME_PRINT_UNKNOWN_VAR and not target.get("optional", False):
|
||||
print(
|
||||
f'pffff la target {target["text"]} dans le fill n\'est pas trouvable'
|
||||
if variable_path in self.paths["dynamic"]:
|
||||
variable_path = self.paths["dynamic"][variable_path]
|
||||
if variable_path in self.paths["variable"]:
|
||||
variable = self.paths["variable"][variable_path]
|
||||
if fill.get("type") == "jinja":
|
||||
fill_value = {
|
||||
"type": "jinja",
|
||||
"jinja": fill["name"],
|
||||
}
|
||||
else:
|
||||
fill_value = self.convert_param_function(
|
||||
fill, variable.get("multi", False)
|
||||
)
|
||||
continue
|
||||
variable = self.paths["variable"][variable_path]
|
||||
if fill.get("type") == "jinja":
|
||||
fill_value = {
|
||||
"type": "jinja",
|
||||
"jinja": fill["name"],
|
||||
}
|
||||
variable["default"] = fill_value
|
||||
if variable.get("mandatory") is False:
|
||||
del variable["mandatory"]
|
||||
else:
|
||||
fill_value = self.convert_param_function(fill)
|
||||
variable["default"] = fill_value
|
||||
raise Exception(
|
||||
f'cannot set fill to unknown variable "{variable_path}"'
|
||||
)
|
||||
|
||||
def params_condition_to_jinja(
|
||||
self,
|
||||
prop: str,
|
||||
path: str,
|
||||
params: List[dict],
|
||||
if_in: bool,
|
||||
multi: bool,
|
||||
) -> str:
|
||||
new_params = {}
|
||||
jinja = "{% if "
|
||||
|
|
@ -438,15 +473,15 @@ class upgrade_010_to_100:
|
|||
if idx:
|
||||
jinja += " or "
|
||||
|
||||
new_param, value = self.get_jinja_param_and_value(param)
|
||||
new_param, value = self.get_jinja_param_and_value(param, multi)
|
||||
if value:
|
||||
jinja += path + " == " + value
|
||||
if new_param:
|
||||
new_params |= new_param
|
||||
if if_in:
|
||||
jinja += " %}true{% else %}false{% endif %}"
|
||||
jinja += " %}" + prop + "{% endif %}"
|
||||
else:
|
||||
jinja += " %}false{% else %}true{% endif %}"
|
||||
jinja += " %}{% else %}" + prop + "{% endif %}"
|
||||
ret = {
|
||||
"type": "jinja",
|
||||
"jinja": jinja,
|
||||
|
|
@ -458,12 +493,11 @@ class upgrade_010_to_100:
|
|||
def get_value(
|
||||
self,
|
||||
param: dict,
|
||||
multi: bool,
|
||||
) -> Any:
|
||||
# <!ATTLIST type (string|number|nil|space|boolean|variable|function|information|suffix|index) "string">
|
||||
typ = param.get("type", "string")
|
||||
if typ == "string":
|
||||
value = param["text"]
|
||||
# value = dumps(value, ensure_ascii=False)
|
||||
value = param.get("text")
|
||||
elif typ == "number":
|
||||
value = int(param["text"])
|
||||
elif typ == "nil":
|
||||
|
|
@ -485,7 +519,7 @@ class upgrade_010_to_100:
|
|||
if "propertyerror" in param:
|
||||
value["propertyerror"] = param["propertyerror"]
|
||||
elif typ == "function":
|
||||
value = self.convert_param_function(param)
|
||||
value = self.convert_param_function(param, multi)
|
||||
elif typ == "information":
|
||||
value = {
|
||||
"type": "information",
|
||||
|
|
@ -503,10 +537,11 @@ class upgrade_010_to_100:
|
|||
def get_jinja_param_and_value(
|
||||
self,
|
||||
param,
|
||||
multi: bool,
|
||||
) -> Tuple[list, Any]:
|
||||
new_param = None
|
||||
typ = param.get("type", "string")
|
||||
value = self.get_value(param)
|
||||
value = self.get_value(param, multi)
|
||||
if isinstance(value, dict):
|
||||
if typ == "information":
|
||||
key = normalize_family(value["information"])
|
||||
|
|
@ -514,17 +549,25 @@ class upgrade_010_to_100:
|
|||
attr_name = f'{value["variable"]}.{key}'
|
||||
else:
|
||||
attr_name = key
|
||||
attr_name = f"__information.{attr_name}"
|
||||
attr_name = f"__information_{attr_name}"
|
||||
new_param = {attr_name: value}
|
||||
value = attr_name
|
||||
elif typ in ["index", "suffix"]:
|
||||
attr_name = f"__{typ}"
|
||||
new_param = {attr_name: value}
|
||||
if "name" in value:
|
||||
attr_name = value["name"]
|
||||
else:
|
||||
attr_name = f"__{typ}"
|
||||
new_param = {attr_name: {"type": typ}}
|
||||
value = attr_name
|
||||
elif "propertyerror" in param or "optional" in param:
|
||||
attr_name = value["variable"]
|
||||
new_param = {attr_name: value}
|
||||
value = value[typ]
|
||||
elif "{{ suffix }}" in value[typ]:
|
||||
path = value[typ]
|
||||
attr_name = path.split(".")[-1][:-12] # remove {{ suffix }}
|
||||
new_param = {attr_name: value}
|
||||
value = attr_name
|
||||
else:
|
||||
value = value[typ]
|
||||
if not value:
|
||||
|
|
@ -536,23 +579,41 @@ class upgrade_010_to_100:
|
|||
def convert_param_function(
|
||||
self,
|
||||
param: dict,
|
||||
multi: bool,
|
||||
) -> str:
|
||||
text = param["name"]
|
||||
params = {}
|
||||
# multi = False
|
||||
if "param" in param and param["param"]:
|
||||
if (
|
||||
text == "calc_value"
|
||||
and len(param["param"]) == 1
|
||||
and isinstance(param["param"][0], dict)
|
||||
and param["param"][0].get("type") == "variable"
|
||||
and param["param"][0].get("text")
|
||||
):
|
||||
value = param["param"][0]["text"]
|
||||
path = self.get_variable_path(value)
|
||||
if not path:
|
||||
path = value
|
||||
ret = {"type": "variable", "variable": path}
|
||||
if "optional" in param["param"][0]:
|
||||
ret["optional"] = param["param"][0]["optional"]
|
||||
return ret
|
||||
first, *others = param["param"]
|
||||
new_param, first = self.get_jinja_param_and_value(first)
|
||||
new_param, first = self.get_jinja_param_and_value(first, multi)
|
||||
text = f"{first} | {text}"
|
||||
if new_param:
|
||||
params |= new_param
|
||||
if others:
|
||||
values = []
|
||||
for param in others:
|
||||
new_param, value = self.get_jinja_param_and_value(param)
|
||||
new_param, value = self.get_jinja_param_and_value(param, multi)
|
||||
if new_param:
|
||||
params |= new_param
|
||||
# if param.get('type') != 'variable' or value is not None:
|
||||
if "name" in param:
|
||||
if param["name"] == "multi" and value == "true":
|
||||
multi = True
|
||||
values.append(f'{param["name"]}={value}')
|
||||
else:
|
||||
values.append(value)
|
||||
|
|
@ -561,7 +622,16 @@ class upgrade_010_to_100:
|
|||
text += ")"
|
||||
else:
|
||||
text += "()"
|
||||
text = "{{ " + text + " }}"
|
||||
if not multi:
|
||||
text = "{{ " + text + " }}"
|
||||
else:
|
||||
text = (
|
||||
"""{% for __variable in """
|
||||
+ text
|
||||
+ """ %}
|
||||
{{ __variable }}
|
||||
{% endfor %}"""
|
||||
)
|
||||
ret = {"type": "jinja", "jinja": text}
|
||||
if params:
|
||||
ret["params"] = params
|
||||
|
|
@ -576,10 +646,10 @@ class upgrade_010_to_100:
|
|||
and path in self.flatten_paths["variable"]
|
||||
):
|
||||
path = self.flatten_paths["variable"][path]
|
||||
if path in self.paths["dynamic"]:
|
||||
path = self.paths["dynamic"][path]
|
||||
if path not in self.paths["variable"]:
|
||||
if FIXME_PRINT_UNKNOWN_VAR:
|
||||
print("pffff impossible de trouver la variable", path)
|
||||
return
|
||||
return path
|
||||
return path
|
||||
|
||||
def get_family_path(
|
||||
|
|
@ -589,8 +659,6 @@ class upgrade_010_to_100:
|
|||
if path not in self.paths["family"] and path in self.flatten_paths["family"]:
|
||||
path = self.flatten_paths["family"][path]
|
||||
if path not in self.paths["family"]:
|
||||
if FIXME_PRINT_UNKNOWN_VAR:
|
||||
print("pffff impossible de trouver la famille", path)
|
||||
return
|
||||
return path
|
||||
|
||||
|
|
@ -613,42 +681,43 @@ class RougailUpgrade:
|
|||
rougailconfig = RougailConfig
|
||||
self.rougailconfig = rougailconfig
|
||||
|
||||
def load_dictionaries(
|
||||
def run(
|
||||
self,
|
||||
# srcfolder: str,
|
||||
dstfolder: str,
|
||||
services_dstfolder: Optional[str],
|
||||
extra_dstfolder: Optional[str] = None,
|
||||
# namespace: str,
|
||||
# display: bool=True,
|
||||
):
|
||||
if extra_dstfolder is None:
|
||||
extra_dstfolder = dstfolder
|
||||
self._load_dictionaries(
|
||||
self.rougailconfig["dictionaries_dir"],
|
||||
dstfolder,
|
||||
services_dstfolder,
|
||||
self.rougailconfig["variable_namespace"],
|
||||
)
|
||||
for namespace, extra_dirs in self.rougailconfig["extra_dictionaries"].items():
|
||||
extra_dstsubfolder = join(extra_dstfolder, namespace)
|
||||
if not isdir(extra_dstsubfolder):
|
||||
makedirs(extra_dstsubfolder)
|
||||
for extra_dir in extra_dirs:
|
||||
self._load_dictionaries(
|
||||
extra_dir,
|
||||
extra_dstsubfolder,
|
||||
None,
|
||||
namespace,
|
||||
)
|
||||
for dict_dir, dest_dir in zip(
|
||||
self.rougailconfig["main_dictionaries"],
|
||||
self.rougailconfig["upgrade_options.main_dictionaries"],
|
||||
):
|
||||
self._load_dictionaries(
|
||||
dict_dir,
|
||||
dest_dir,
|
||||
normalize_family(self.rougailconfig["main_namespace"]),
|
||||
)
|
||||
if self.rougailconfig["main_namespace"]:
|
||||
if self.rougailconfig["extra_dictionaries"]:
|
||||
dst_extra_dir = self.rougailconfig["upgrade_options.extra_dictionary"]
|
||||
for namespace, extra_dirs in self.rougailconfig[
|
||||
"extra_dictionaries"
|
||||
].items():
|
||||
extra_dstsubfolder = Path(dst_extra_dir) / namespace
|
||||
if not extra_dstsubfolder.is_dir():
|
||||
extra_dstsubfolder.mkdir()
|
||||
for extra_dir in extra_dirs:
|
||||
self._load_dictionaries(
|
||||
str(extra_dir),
|
||||
str(extra_dstsubfolder),
|
||||
normalize_family(namespace),
|
||||
)
|
||||
|
||||
def _load_dictionaries(
|
||||
self,
|
||||
srcfolder: str,
|
||||
dstfolder: str,
|
||||
services_dstfolder: Optional[str],
|
||||
dstfolder: Optional[str],
|
||||
namespace: str,
|
||||
) -> None:
|
||||
if dstfolder is None:
|
||||
dstfolder = srcfolder
|
||||
Path(dstfolder).mkdir(parents=True, exist_ok=True)
|
||||
filenames = [
|
||||
filename
|
||||
for filename in listdir(srcfolder)
|
||||
|
|
@ -657,87 +726,59 @@ class RougailUpgrade:
|
|||
filenames.sort()
|
||||
for filename in filenames:
|
||||
xmlsrc = Path(srcfolder) / Path(filename)
|
||||
ymlfile = filename[:-3] + "yml"
|
||||
xmldst = Path(dstfolder) / Path(ymlfile)
|
||||
if xmldst.is_file():
|
||||
raise Exception(
|
||||
f'cannot update "{xmlsrc}" destination file "{xmldst}" already exists'
|
||||
)
|
||||
if services_dstfolder:
|
||||
ymldst_services = Path(services_dstfolder) / ymlfile
|
||||
if ymldst_services.is_file():
|
||||
raise Exception(
|
||||
f'cannot update "{xmlsrc}" destination file "{ymldst_services}" already exists'
|
||||
)
|
||||
|
||||
ymldst = Path(dstfolder) / (Path(filename).stem + ".yml")
|
||||
if filename.endswith(".xml"):
|
||||
if parse is None:
|
||||
raise Exception('XML module is not installed')
|
||||
raise Exception("XML module is not installed")
|
||||
try:
|
||||
parser = XMLParser(remove_blank_text=True)
|
||||
document = parse(xmlsrc, parser)
|
||||
except XMLSyntaxError as err:
|
||||
raise Exception(_(f"not a XML file: {err}")) from err
|
||||
raise Exception(_("not a XML file: {0}").format(err)) from err
|
||||
root = document.getroot()
|
||||
search_function_name = get_function_name(
|
||||
root.attrib.get("version", "1")
|
||||
)
|
||||
ext = "xml"
|
||||
else:
|
||||
with xmlsrc.open() as xml_fh:
|
||||
root = safe_load(xml_fh)
|
||||
search_function_name = get_function_name(root["version"])
|
||||
with xmlsrc.open() as file_fh:
|
||||
root = YAML(typ="safe").load(file_fh)
|
||||
search_function_name = get_function_name(str(root["version"]))
|
||||
ext = "yml"
|
||||
function_found = False
|
||||
if FIXME_PRINT_FILENAME:
|
||||
print(
|
||||
"========================================================================"
|
||||
)
|
||||
print(xmlsrc)
|
||||
print(
|
||||
"========================================================================"
|
||||
)
|
||||
root_services = None
|
||||
for version, function_version in FUNCTION_VERSIONS:
|
||||
if function_found and hasattr(self, function_version):
|
||||
# if display:
|
||||
# print(f' - convert {filename} to version {version}')
|
||||
upgrade_help = self.upgrade_help.get(function_version, {}).get(
|
||||
filename, {}
|
||||
)
|
||||
if upgrade_help.get("remove") is True:
|
||||
continue
|
||||
root, root_services, new_type = getattr(self, function_version)(
|
||||
root, root_services_, new_type = getattr(self, function_version)(
|
||||
root, upgrade_help, namespace, xmlsrc, ext
|
||||
)
|
||||
if root_services_ is not None:
|
||||
root_services = root_services_
|
||||
if function_version == search_function_name:
|
||||
function_found = True
|
||||
if root:
|
||||
root["version"] = version
|
||||
xmldst.parent.mkdir(parents=True, exist_ok=True)
|
||||
with xmldst.open("w") as ymlfh:
|
||||
dump(
|
||||
if root != {"version": None}:
|
||||
root["version"] = float(version)
|
||||
with ymldst.open("w") as ymlfh:
|
||||
yaml = YAML()
|
||||
yaml.dump(
|
||||
root,
|
||||
ymlfh,
|
||||
allow_unicode=True,
|
||||
sort_keys=False,
|
||||
Dumper=NoAliasDumper,
|
||||
)
|
||||
if root_services and services_dstfolder:
|
||||
root_services["version"] = version
|
||||
ymldst_services.parent.mkdir(parents=True, exist_ok=True)
|
||||
with ymldst_services.open("w") as ymlfh:
|
||||
dump(
|
||||
root_services,
|
||||
ymlfh,
|
||||
allow_unicode=True,
|
||||
sort_keys=False,
|
||||
Dumper=NoAliasDumper,
|
||||
)
|
||||
|
||||
# if not self.dtd.validate(document):
|
||||
# dtd_error = self.dtd.error_log.filter_from_errors()[0]
|
||||
# msg = _(f'not a valid XML file: {dtd_error}')
|
||||
# raise DictConsistencyError(msg, 43, [xmlfile])
|
||||
# yield xmlfile, document.getroot()
|
||||
# if root_services and services_dstfolder:
|
||||
# root_services["version"] = version
|
||||
# ymldst_services.parent.mkdir(parents=True, exist_ok=True)
|
||||
# with ymldst_services.open("w") as ymlfh:
|
||||
# yaml = YAML()
|
||||
# yaml.dump(
|
||||
# root_services,
|
||||
# ymlfh,
|
||||
# )
|
||||
|
||||
def _attribut_to_bool(self, variable):
|
||||
for prop in [
|
||||
|
|
@ -766,10 +807,11 @@ class RougailUpgrade:
|
|||
def _attribut_to_int(self, variable):
|
||||
for prop in ["mode"]:
|
||||
if prop in variable:
|
||||
if variable[prop] in ['expert', 'normal']:
|
||||
variable[prop] = {'expert': 'advanced',
|
||||
'normal': 'standard',
|
||||
}.get(variable[prop])
|
||||
if variable[prop] in ["expert", "normal"]:
|
||||
variable[prop] = {
|
||||
"expert": "advanced",
|
||||
"normal": "standard",
|
||||
}.get(variable[prop])
|
||||
continue
|
||||
try:
|
||||
variable[prop] = int(variable[prop])
|
||||
|
|
@ -891,6 +933,61 @@ class RougailUpgrade:
|
|||
dico = {obj_name: dico}
|
||||
return dico
|
||||
|
||||
def _update_1_1(self, root):
|
||||
new_root = {}
|
||||
update_root = False
|
||||
for key, value in root.items():
|
||||
new_root[key] = value
|
||||
if not isinstance(value, dict):
|
||||
continue
|
||||
# migrate dynamic family
|
||||
if (
|
||||
("variable" in value and isinstance(value["variable"], str))
|
||||
or ("_variable" in value and isinstance(value["_variable"], str))
|
||||
) and (
|
||||
("_type" in value and value["_type"] == "dynamic")
|
||||
or ("type" in value and value["type"] == "dynamic")
|
||||
):
|
||||
value["dynamic"] = {
|
||||
"type": "variable",
|
||||
"variable": value.pop("variable"),
|
||||
"propertyerror": False,
|
||||
}
|
||||
if "{{ suffix }}" not in key:
|
||||
new_root[key + "{{ suffix }}"] = new_root.pop(key)
|
||||
update_root = True
|
||||
self._update_1_1(value)
|
||||
for typ, obj in {
|
||||
"boolean": bool,
|
||||
"number": int,
|
||||
"string": str,
|
||||
"float": float,
|
||||
}.items():
|
||||
if value.get("type") == typ:
|
||||
default = value.get("default")
|
||||
if default is None or default == []:
|
||||
continue
|
||||
if isinstance(default, obj):
|
||||
del value["type"]
|
||||
elif isinstance(default, list) and isinstance(default[0], obj):
|
||||
del value["type"]
|
||||
if value.get("multi") and isinstance(value.get("default"), list):
|
||||
del value["multi"]
|
||||
if update_root:
|
||||
root.clear()
|
||||
root.update(new_root)
|
||||
|
||||
def update_1_1(
|
||||
self,
|
||||
root,
|
||||
upgrade_help: dict,
|
||||
namespace: str,
|
||||
xmlsrc: str,
|
||||
ext: str,
|
||||
):
|
||||
self._update_1_1(root)
|
||||
return root, None, "yml"
|
||||
|
||||
def update_1_0(
|
||||
self,
|
||||
root: "Element",
|
||||
|
|
@ -906,22 +1003,12 @@ class RougailUpgrade:
|
|||
objects = root.find(typ)
|
||||
if objects is None:
|
||||
objects = []
|
||||
new_objects = self._xml_to_yaml(objects, typ, variables, "")
|
||||
new_objects = self._xml_to_yaml(objects, typ, variables, namespace)
|
||||
if new_objects[typ]:
|
||||
new_root.update(new_objects)
|
||||
# services = root.find('services')
|
||||
# if services is None:
|
||||
# services = []
|
||||
# new_services = self._xml_to_yaml_service(services)
|
||||
# if new_services:
|
||||
# new_root['services'] = new_services
|
||||
# paths = self._get_path_variables(variables,
|
||||
# namespace == 'configuration',
|
||||
# namespace,
|
||||
# )
|
||||
else:
|
||||
new_root = root
|
||||
variables, services = upgrade_010_to_100(new_root, namespace, xmlsrc).get()
|
||||
variables, services = upgrade_010_to_10(new_root, namespace, xmlsrc).get()
|
||||
return variables, services, "yml"
|
||||
|
||||
def update_0_10(
|
||||
|
|
@ -966,7 +1053,6 @@ class RougailUpgrade:
|
|||
if not has_value:
|
||||
value = SubElement(variable, "value")
|
||||
value.text = choices[0]
|
||||
variable.attrib["mandatory"] = "True"
|
||||
|
||||
# convert group to leadership
|
||||
groups = []
|
||||
|
|
@ -11,25 +11,24 @@ Copyright (C) 2019-2021
|
|||
Silique (https://www.silique.fr)
|
||||
Copyright (C) 2022-2024
|
||||
|
||||
distribued with GPL-2 or later license
|
||||
This program is free software: you can redistribute it and/or modify it
|
||||
under the terms of the GNU Lesser 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 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 2 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 Lesser General Public License for more
|
||||
details.
|
||||
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from typing import List, Union
|
||||
from unicodedata import normalize, combining
|
||||
import re
|
||||
from itertools import chain
|
||||
|
||||
from importlib.machinery import SourceFileLoader
|
||||
from importlib.util import spec_from_loader, module_from_spec
|
||||
|
|
@ -37,7 +36,9 @@ from importlib.util import spec_from_loader, module_from_spec
|
|||
from jinja2 import DictLoader, TemplateSyntaxError
|
||||
from jinja2.sandbox import SandboxedEnvironment
|
||||
from jinja2.parser import Parser
|
||||
from jinja2.nodes import Getattr
|
||||
from jinja2.nodes import Name, Getattr
|
||||
|
||||
from tiramisu.config import get_common_path
|
||||
|
||||
from .i18n import _
|
||||
from .error import DictConsistencyError
|
||||
|
|
@ -52,9 +53,8 @@ def valid_variable_family_name(
|
|||
match = NAME_REGEXP.search(name)
|
||||
if not match:
|
||||
msg = _(
|
||||
f'invalid variable or family name "{name}" must only contains '
|
||||
"lowercase ascii character, number or _"
|
||||
)
|
||||
'invalid variable or family name "{0}" must only contains lowercase ascii character, number or _'
|
||||
).format(name)
|
||||
raise DictConsistencyError(msg, 76, xmlfiles)
|
||||
|
||||
|
||||
|
|
@ -62,15 +62,16 @@ def normalize_family(family_name: str) -> str:
|
|||
"""replace space, accent, uppercase, ... by valid character"""
|
||||
if not family_name:
|
||||
return
|
||||
family_name = family_name.lower()
|
||||
family_name = family_name.replace("-", "_").replace(" ", "_").replace(".", "_")
|
||||
nfkd_form = normalize("NFKD", family_name)
|
||||
family_name = "".join([c for c in nfkd_form if not combining(c)])
|
||||
return family_name.lower()
|
||||
|
||||
|
||||
def load_modules(eosfunc_file) -> List[str]:
|
||||
"""list all functions in eosfunc"""
|
||||
loader = SourceFileLoader("eosfunc", eosfunc_file)
|
||||
def load_modules(name, module) -> List[str]:
|
||||
"""list all functions in a module"""
|
||||
loader = SourceFileLoader(name, module)
|
||||
spec = spec_from_loader(loader.name, loader)
|
||||
eosfunc = module_from_spec(spec)
|
||||
loader.exec_module(eosfunc)
|
||||
|
|
@ -87,11 +88,14 @@ def get_realpath(
|
|||
|
||||
|
||||
def get_jinja_variable_to_param(
|
||||
current_path: str,
|
||||
jinja_text,
|
||||
objectspace,
|
||||
xmlfiles,
|
||||
functions,
|
||||
path_prefix,
|
||||
version,
|
||||
namespace,
|
||||
):
|
||||
try:
|
||||
env = SandboxedEnvironment(loader=DictLoader({"tmpl": jinja_text}))
|
||||
|
|
@ -104,16 +108,60 @@ def get_jinja_variable_to_param(
|
|||
return g.node.name + "." + g.attr
|
||||
|
||||
variables = set()
|
||||
if objectspace.namespace is None:
|
||||
for n in parsed_content.find_all(Name):
|
||||
variables.add(n.name)
|
||||
for g in parsed_content.find_all(Getattr):
|
||||
variables.add(recurse_getattr(g))
|
||||
except TemplateSyntaxError as err:
|
||||
msg = _(f'error in jinja "{jinja_text}": {err}')
|
||||
raise Exception(msg) from err
|
||||
msg = _('error in jinja "{0}" for the variable "{1}": {2}').format(
|
||||
jinja_text, current_path, err
|
||||
)
|
||||
raise DictConsistencyError(msg, 39, xmlfiles) from err
|
||||
variables = list(variables)
|
||||
variables.sort()
|
||||
variables.sort(reverse=True)
|
||||
founded_variables = {}
|
||||
unknown_variables = []
|
||||
for variable_path in variables:
|
||||
variable, suffix, dynamic = objectspace.paths.get_with_dynamic(
|
||||
get_realpath(variable_path, path_prefix)
|
||||
variable, identifier = objectspace.paths.get_with_dynamic(
|
||||
variable_path,
|
||||
path_prefix,
|
||||
current_path,
|
||||
version,
|
||||
namespace,
|
||||
xmlfiles,
|
||||
)
|
||||
if variable and variable.path in objectspace.variables:
|
||||
yield variable, suffix, variable_path, dynamic
|
||||
founded_variables[variable_path] = (identifier, variable)
|
||||
else:
|
||||
sub_family = variable_path + "."
|
||||
for founded_variable in chain(founded_variables, unknown_variables):
|
||||
if founded_variable.startswith(sub_family):
|
||||
break
|
||||
else:
|
||||
unknown_variables.append(variable_path)
|
||||
|
||||
for variable_path in unknown_variables:
|
||||
for v in founded_variables:
|
||||
if get_common_path(v, variable_path) == v:
|
||||
break
|
||||
else:
|
||||
root_path = None
|
||||
vpath = variable_path
|
||||
while "." in vpath:
|
||||
vpath = vpath.rsplit(".", 1)[0]
|
||||
variable, identifier = objectspace.paths.get_with_dynamic(
|
||||
vpath,
|
||||
path_prefix,
|
||||
current_path,
|
||||
version,
|
||||
namespace,
|
||||
xmlfiles,
|
||||
)
|
||||
if variable and variable.path in objectspace.families:
|
||||
root_path = vpath
|
||||
break
|
||||
if root_path:
|
||||
yield {}, None, root_path
|
||||
for variable_path, data in founded_variables.items():
|
||||
yield data[1], data[0], variable_path
|
||||
|
|
|
|||
7
tests/custom.py
Normal file
7
tests/custom.py
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
from os import environ
|
||||
environ['TIRAMISU_LOCALE'] = 'en'
|
||||
from tiramisu import StrOption
|
||||
|
||||
|
||||
class CustomOption(StrOption):
|
||||
pass
|
||||
5
tests/data/dict1/dict.yml
Normal file
5
tests/data/dict1/dict.yml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
# dict with a correct version declared
|
||||
#version: "1.1"
|
||||
hello:
|
||||
type: string
|
||||
default: world
|
||||
5
tests/data/dict2/dict.yml
Normal file
5
tests/data/dict2/dict.yml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
# dict with a correct version declared
|
||||
version: "1.0"
|
||||
hello:
|
||||
type: string
|
||||
default: world
|
||||
13
tests/dictionaries/00_0empty/tiramisu/base.py
Normal file
13
tests/dictionaries/00_0empty/tiramisu/base.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[])
|
||||
15
tests/dictionaries/00_0empty/tiramisu/multi.py
Normal file
15
tests/dictionaries/00_0empty/tiramisu/multi.py
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
optiondescription_1 = OptionDescription(name="1", doc="1", children=[], properties=frozenset({"advanced"}))
|
||||
optiondescription_2 = OptionDescription(name="2", doc="2", children=[], properties=frozenset({"advanced"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1, optiondescription_2])
|
||||
9
tests/dictionaries/00_0empty/tiramisu/no_namespace.py
Normal file
9
tests/dictionaries/00_0empty/tiramisu/no_namespace.py
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[])
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
---
|
||||
_version: '1.1'
|
||||
version: # a variable
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"rougail.version": {
|
||||
"owner": "default",
|
||||
"value": null
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"rougail.version": null
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"rougail.version": {
|
||||
"owner": "default",
|
||||
"value": null
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
["rougail.version"]
|
||||
15
tests/dictionaries/00_0version_underscore/tiramisu/base.py
Normal file
15
tests/dictionaries/00_0version_underscore/tiramisu/base.py
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_2 = StrOption(name="version", doc="a variable", properties=frozenset({"basic", "mandatory"}), informations={'type': 'string'})
|
||||
optiondescription_1 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_2], properties=frozenset({"basic"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1])
|
||||
19
tests/dictionaries/00_0version_underscore/tiramisu/multi.py
Normal file
19
tests/dictionaries/00_0version_underscore/tiramisu/multi.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_3 = StrOption(name="version", doc="a variable", properties=frozenset({"basic", "mandatory"}), informations={'type': 'string'})
|
||||
optiondescription_2 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_3], properties=frozenset({"basic"}))
|
||||
optiondescription_1 = OptionDescription(name="1", doc="1", children=[optiondescription_2], properties=frozenset({"basic"}))
|
||||
option_6 = StrOption(name="version", doc="a variable", properties=frozenset({"basic", "mandatory"}), informations={'type': 'string'})
|
||||
optiondescription_5 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_6], properties=frozenset({"basic"}))
|
||||
optiondescription_4 = OptionDescription(name="2", doc="2", children=[optiondescription_5], properties=frozenset({"basic"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1, optiondescription_4])
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_1 = StrOption(name="version", doc="a variable", properties=frozenset({"basic", "mandatory"}), informations={'type': 'string'})
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[option_1])
|
||||
3
tests/dictionaries/00_1empty_variable/makedict/base.json
Normal file
3
tests/dictionaries/00_1empty_variable/makedict/base.json
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"rougail.empty": null
|
||||
}
|
||||
15
tests/dictionaries/00_1empty_variable/tiramisu/base.py
Normal file
15
tests/dictionaries/00_1empty_variable/tiramisu/base.py
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_2 = StrOption(name="empty", doc="empty", properties=frozenset({"basic", "mandatory"}), informations={'type': 'string'})
|
||||
optiondescription_1 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_2], properties=frozenset({"basic"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1])
|
||||
19
tests/dictionaries/00_1empty_variable/tiramisu/multi.py
Normal file
19
tests/dictionaries/00_1empty_variable/tiramisu/multi.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_3 = StrOption(name="empty", doc="empty", properties=frozenset({"basic", "mandatory"}), informations={'type': 'string'})
|
||||
optiondescription_2 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_3], properties=frozenset({"basic"}))
|
||||
optiondescription_1 = OptionDescription(name="1", doc="1", children=[optiondescription_2], properties=frozenset({"basic"}))
|
||||
option_6 = StrOption(name="empty", doc="empty", properties=frozenset({"basic", "mandatory"}), informations={'type': 'string'})
|
||||
optiondescription_5 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_6], properties=frozenset({"basic"}))
|
||||
optiondescription_4 = OptionDescription(name="2", doc="2", children=[optiondescription_5], properties=frozenset({"basic"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1, optiondescription_4])
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_1 = StrOption(name="empty", doc="empty", properties=frozenset({"basic", "mandatory"}), informations={'type': 'string'})
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[option_1])
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
---
|
||||
version: 1.1
|
||||
var1: "no" # a first variable
|
||||
var2:
|
||||
description: a second variable
|
||||
multi: true
|
||||
default:
|
||||
jinja: |
|
||||
{{ _.var1 }}
|
||||
description: the value of var1
|
||||
17
tests/dictionaries/00_2default_calculated/tiramisu/base.py
Normal file
17
tests/dictionaries/00_2default_calculated/tiramisu/base.py
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
dict_env['default_rougail.var2'] = "{{ _.var1 }}\n"
|
||||
option_2 = StrOption(name="var1", doc="a first variable", default="no", properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_3 = StrOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['jinja_to_function'], Params((), kwargs={'__internal_jinja': ParamValue("default_rougail.var2"), '__internal_type': ParamValue("string"), '__internal_multi': ParamValue(True), '__internal_files': ParamValue(['tests/dictionaries/00_2default_calculated/dictionaries/rougail/00-base.yml']), '__internal_attribute': ParamValue("default"), '__internal_variable': ParamValue("rougail.var2"), '_.var1': ParamOption(option_2, notraisepropertyerror=True)})), properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
optiondescription_1 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_2, option_3], properties=frozenset({"standard"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1])
|
||||
23
tests/dictionaries/00_2default_calculated/tiramisu/multi.py
Normal file
23
tests/dictionaries/00_2default_calculated/tiramisu/multi.py
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
dict_env['default_1.rougail.var2'] = "{{ _.var1 }}\n"
|
||||
dict_env['default_2.rougail.var2'] = "{{ _.var1 }}\n"
|
||||
option_3 = StrOption(name="var1", doc="a first variable", default="no", properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_4 = StrOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['jinja_to_function'], Params((), kwargs={'__internal_jinja': ParamValue("default_1.rougail.var2"), '__internal_type': ParamValue("string"), '__internal_multi': ParamValue(True), '__internal_files': ParamValue(['tests/dictionaries/00_2default_calculated/dictionaries/rougail/00-base.yml']), '__internal_attribute': ParamValue("default"), '__internal_variable': ParamValue("1.rougail.var2"), '_.var1': ParamOption(option_3, notraisepropertyerror=True)})), properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
optiondescription_2 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_3, option_4], properties=frozenset({"standard"}))
|
||||
optiondescription_1 = OptionDescription(name="1", doc="1", children=[optiondescription_2], properties=frozenset({"standard"}))
|
||||
option_7 = StrOption(name="var1", doc="a first variable", default="no", properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_8 = StrOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['jinja_to_function'], Params((), kwargs={'__internal_jinja': ParamValue("default_2.rougail.var2"), '__internal_type': ParamValue("string"), '__internal_multi': ParamValue(True), '__internal_files': ParamValue(['tests/dictionaries/00_2default_calculated/dictionaries/rougail/00-base.yml']), '__internal_attribute': ParamValue("default"), '__internal_variable': ParamValue("2.rougail.var2"), '_.var1': ParamOption(option_7, notraisepropertyerror=True)})), properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
optiondescription_6 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_7, option_8], properties=frozenset({"standard"}))
|
||||
optiondescription_5 = OptionDescription(name="2", doc="2", children=[optiondescription_6], properties=frozenset({"standard"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1, optiondescription_5])
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
dict_env['default_var2'] = "{{ _.var1 }}\n"
|
||||
option_1 = StrOption(name="var1", doc="a first variable", default="no", properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_2 = StrOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['jinja_to_function'], Params((), kwargs={'__internal_jinja': ParamValue("default_var2"), '__internal_type': ParamValue("string"), '__internal_multi': ParamValue(True), '__internal_files': ParamValue(['tests/dictionaries/00_2default_calculated/dictionaries/rougail/00-base.yml']), '__internal_attribute': ParamValue("default"), '__internal_variable': ParamValue("var2"), '_.var1': ParamOption(option_1, notraisepropertyerror=True)})), properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[option_1, option_2])
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
---
|
||||
version: 1.1
|
||||
var1: # a first variable
|
||||
- 'no'
|
||||
- 'yes'
|
||||
- maybe
|
||||
var2:
|
||||
description: a second variable
|
||||
multi: true
|
||||
default:
|
||||
jinja: |
|
||||
{% for val in _.var1 %}
|
||||
{{ val }}
|
||||
{% endfor %}
|
||||
description: the value of _.var1
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
dict_env['default_rougail.var2'] = "{% for val in _.var1 %}\n{{ val }}\n{% endfor %}\n"
|
||||
option_2 = StrOption(name="var1", doc="a first variable", multi=True, default=["no", "yes", "maybe"], default_multi="no", properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_3 = StrOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['jinja_to_function'], Params((), kwargs={'__internal_jinja': ParamValue("default_rougail.var2"), '__internal_type': ParamValue("string"), '__internal_multi': ParamValue(True), '__internal_files': ParamValue(['tests/dictionaries/00_2default_calculated_multi/dictionaries/rougail/00-base.yml']), '__internal_attribute': ParamValue("default"), '__internal_variable': ParamValue("rougail.var2"), '_.var1': ParamOption(option_2, notraisepropertyerror=True)})), properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
optiondescription_1 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_2, option_3], properties=frozenset({"standard"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1])
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
dict_env['default_1.rougail.var2'] = "{% for val in _.var1 %}\n{{ val }}\n{% endfor %}\n"
|
||||
dict_env['default_2.rougail.var2'] = "{% for val in _.var1 %}\n{{ val }}\n{% endfor %}\n"
|
||||
option_3 = StrOption(name="var1", doc="a first variable", multi=True, default=["no", "yes", "maybe"], default_multi="no", properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_4 = StrOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['jinja_to_function'], Params((), kwargs={'__internal_jinja': ParamValue("default_1.rougail.var2"), '__internal_type': ParamValue("string"), '__internal_multi': ParamValue(True), '__internal_files': ParamValue(['tests/dictionaries/00_2default_calculated_multi/dictionaries/rougail/00-base.yml']), '__internal_attribute': ParamValue("default"), '__internal_variable': ParamValue("1.rougail.var2"), '_.var1': ParamOption(option_3, notraisepropertyerror=True)})), properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
optiondescription_2 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_3, option_4], properties=frozenset({"standard"}))
|
||||
optiondescription_1 = OptionDescription(name="1", doc="1", children=[optiondescription_2], properties=frozenset({"standard"}))
|
||||
option_7 = StrOption(name="var1", doc="a first variable", multi=True, default=["no", "yes", "maybe"], default_multi="no", properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_8 = StrOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['jinja_to_function'], Params((), kwargs={'__internal_jinja': ParamValue("default_2.rougail.var2"), '__internal_type': ParamValue("string"), '__internal_multi': ParamValue(True), '__internal_files': ParamValue(['tests/dictionaries/00_2default_calculated_multi/dictionaries/rougail/00-base.yml']), '__internal_attribute': ParamValue("default"), '__internal_variable': ParamValue("2.rougail.var2"), '_.var1': ParamOption(option_7, notraisepropertyerror=True)})), properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
optiondescription_6 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_7, option_8], properties=frozenset({"standard"}))
|
||||
optiondescription_5 = OptionDescription(name="2", doc="2", children=[optiondescription_6], properties=frozenset({"standard"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1, optiondescription_5])
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
dict_env['default_var2'] = "{% for val in _.var1 %}\n{{ val }}\n{% endfor %}\n"
|
||||
option_1 = StrOption(name="var1", doc="a first variable", multi=True, default=["no", "yes", "maybe"], default_multi="no", properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_2 = StrOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['jinja_to_function'], Params((), kwargs={'__internal_jinja': ParamValue("default_var2"), '__internal_type': ParamValue("string"), '__internal_multi': ParamValue(True), '__internal_files': ParamValue(['tests/dictionaries/00_2default_calculated_multi/dictionaries/rougail/00-base.yml']), '__internal_attribute': ParamValue("default"), '__internal_variable': ParamValue("var2"), '_.var1': ParamOption(option_1, notraisepropertyerror=True)})), properties=frozenset({"mandatory", "standard"}), informations={'type': 'string'})
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[option_1, option_2])
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
---
|
||||
version: 1.1
|
||||
|
||||
var1:
|
||||
description: a first variable
|
||||
multi: true
|
||||
type: domainname
|
||||
params:
|
||||
allow_ip: true
|
||||
|
||||
var2:
|
||||
description: a second variable
|
||||
default:
|
||||
type: variable
|
||||
variable: _.var1
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"rougail.var1": {
|
||||
"owner": "default",
|
||||
"value": []
|
||||
},
|
||||
"rougail.var2": {
|
||||
"owner": "default",
|
||||
"value": []
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"rougail.var1": [],
|
||||
"rougail.var2": []
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"rougail.var1": {
|
||||
"owner": "default",
|
||||
"value": []
|
||||
},
|
||||
"rougail.var2": {
|
||||
"owner": "default",
|
||||
"value": []
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
["rougail.var1", "rougail.var2"]
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_2 = DomainnameOption(name="var1", doc="a first variable", multi=True, type="domainname", allow_ip=True, properties=frozenset({"basic", "mandatory"}), informations={'type': 'domainname'})
|
||||
option_3 = DomainnameOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['calc_value'], Params((ParamOption(option_2)))), type="domainname", allow_ip=True, properties=frozenset({"mandatory", "standard"}), informations={'type': 'domainname'})
|
||||
optiondescription_1 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_2, option_3], properties=frozenset({"basic"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1])
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
try:
|
||||
groups.namespace
|
||||
except:
|
||||
groups.addgroup('namespace')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_3 = DomainnameOption(name="var1", doc="a first variable", multi=True, type="domainname", allow_ip=True, properties=frozenset({"basic", "mandatory"}), informations={'type': 'domainname'})
|
||||
option_4 = DomainnameOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['calc_value'], Params((ParamOption(option_3)))), type="domainname", allow_ip=True, properties=frozenset({"mandatory", "standard"}), informations={'type': 'domainname'})
|
||||
optiondescription_2 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_3, option_4], properties=frozenset({"basic"}))
|
||||
optiondescription_1 = OptionDescription(name="1", doc="1", children=[optiondescription_2], properties=frozenset({"basic"}))
|
||||
option_7 = DomainnameOption(name="var1", doc="a first variable", multi=True, type="domainname", allow_ip=True, properties=frozenset({"basic", "mandatory"}), informations={'type': 'domainname'})
|
||||
option_8 = DomainnameOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['calc_value'], Params((ParamOption(option_7)))), type="domainname", allow_ip=True, properties=frozenset({"mandatory", "standard"}), informations={'type': 'domainname'})
|
||||
optiondescription_6 = OptionDescription(name="rougail", doc="Rougail", group_type=groups.namespace, children=[option_7, option_8], properties=frozenset({"basic"}))
|
||||
optiondescription_5 = OptionDescription(name="2", doc="2", children=[optiondescription_6], properties=frozenset({"basic"}))
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[optiondescription_1, optiondescription_5])
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
from tiramisu import *
|
||||
from tiramisu.setting import ALLOWED_LEADER_PROPERTIES
|
||||
from re import compile as re_compile
|
||||
from rougail.tiramisu import func, dict_env, load_functions, ConvertDynOptionDescription
|
||||
load_functions('tests/dictionaries/../eosfunc/test.py')
|
||||
ALLOWED_LEADER_PROPERTIES.add("basic")
|
||||
ALLOWED_LEADER_PROPERTIES.add("standard")
|
||||
ALLOWED_LEADER_PROPERTIES.add("advanced")
|
||||
option_1 = DomainnameOption(name="var1", doc="a first variable", multi=True, type="domainname", allow_ip=True, properties=frozenset({"basic", "mandatory"}), informations={'type': 'domainname'})
|
||||
option_2 = DomainnameOption(name="var2", doc="a second variable", multi=True, default=Calculation(func['calc_value'], Params((ParamOption(option_1)))), type="domainname", allow_ip=True, properties=frozenset({"mandatory", "standard"}), informations={'type': 'domainname'})
|
||||
option_0 = OptionDescription(name="baseoption", doc="baseoption", children=[option_1, option_2])
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
---
|
||||
version: '1.0'
|
||||
var1:
|
||||
description: a variable
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
---
|
||||
version: "1.0"
|
||||
var2:
|
||||
description: a variable
|
||||
10
tests/dictionaries/00_4load_subfolder/makedict/after.json
Normal file
10
tests/dictionaries/00_4load_subfolder/makedict/after.json
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"rougail.var1": {
|
||||
"owner": "default",
|
||||
"value": null
|
||||
},
|
||||
"rougail.var2": {
|
||||
"owner": "default",
|
||||
"value": null
|
||||
}
|
||||
}
|
||||
4
tests/dictionaries/00_4load_subfolder/makedict/base.json
Normal file
4
tests/dictionaries/00_4load_subfolder/makedict/base.json
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"rougail.var1": null,
|
||||
"rougail.var2": null
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue