feat: black + improvement

This commit is contained in:
egarette@silique.fr 2024-11-01 11:17:14 +01:00
parent db53c752dc
commit 1bbfb0fc7d
14 changed files with 1148 additions and 562 deletions

208
LICENSE
View file

@ -1,117 +1,165 @@
GNU GENERAL PUBLIC LICENSE GNU LESSER GENERAL PUBLIC LICENSE
Version 2, June 1991 Version 3, 29 June 2007
Copyright (C) 1989, 1991 Free Software Foundation, Inc. Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 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 licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. 0. Additional Definitions.
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 this service 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. 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.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. "The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 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.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. 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".
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. 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.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. 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.
The precise terms and conditions for copying, distribution and modification follow. 1. Exception to Section 3 of the GNU GPL.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". 2. Conveying Modified Versions.
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 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:
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. 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
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 3. Object Code Incorporating Material from Library Header Files.
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. 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:
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. 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.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) b) Accompany the object code with a copy of the GNU GPL and this license
document.
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 4. Combined Works.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. 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:
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 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.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 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.
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, d) Do one of the following:
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) 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.
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 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.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 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.)
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. Combined Libraries.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 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:
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 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.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. 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.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. 6. Revised Versions of the GNU Lesser General Public License.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 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.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 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.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
9. The Free Software Foundation may publish revised and/or new versions of the 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. apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. Library.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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.
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 convey 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 an idea of what it does. Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice

Binary file not shown.

View file

@ -0,0 +1,151 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: \n"
"POT-Creation-Date: 2024-11-01 11:42+0100\n"
"PO-Revision-Date: 2024-11-01 11:42+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/output_doc/__init__.py:40
msgid "the domain name can starts by a dot"
msgstr "le nom de domaine peut commencé par un point"
#: src/rougail/output_doc/__init__.py:41
msgid "the domain name can be a hostname"
msgstr "le nom de domaine peut être un nom d'hôte"
#: src/rougail/output_doc/__init__.py:42
msgid "the domain name can be an IP"
msgstr "le nom de domaine peut être une IP"
#: src/rougail/output_doc/__init__.py:43
msgid "the domain name can be network in CIDR format"
msgstr "le nom de domaine peut être un réseau au format CIDR"
#: src/rougail/output_doc/__init__.py:48
msgid "the minimum value is {0}"
msgstr "le valeur minimal est {0}"
#: src/rougail/output_doc/__init__.py:49
msgid "the maximum value is {0}"
msgstr "le valeur maximal est {0}"
#: src/rougail/output_doc/__init__.py:55
msgid "IP must be in CIDR format"
msgstr "IP doit être au format CIDR"
#: src/rougail/output_doc/__init__.py:56
msgid "private IP are allowed"
msgstr "les IP privées sont autorisés"
#: src/rougail/output_doc/__init__.py:57
msgid "reserved IP are allowed"
msgstr "les IP réservés sont autorisés"
#: src/rougail/output_doc/__init__.py:62
msgid "the host name can be an IP"
msgstr "le nom d'hôte peut être une IP"
#: src/rougail/output_doc/__init__.py:67
msgid "the domain name in web address can be an IP"
msgstr "le nom de domaine dans l'adresse web peut être une IP"
#: src/rougail/output_doc/__init__.py:68
msgid "the domain name in web address can be only a hostname"
msgstr "le nom de domaine dans l'adresse web ne peut être qu'un nom d'hôte"
#: src/rougail/output_doc/__init__.py:75
msgid "can be range of port"
msgstr "peut être un range de port"
#: src/rougail/output_doc/__init__.py:76
msgid "can have the protocol"
msgstr "peut avoir un protocole"
#: src/rougail/output_doc/__init__.py:77
msgid "port 0 is allowed"
msgstr "le port 0 est autorisé"
#: src/rougail/output_doc/__init__.py:78
msgid "ports 1 to 1023 are allowed"
msgstr "les ports entre 1 et 1023 sont autorisés"
#: src/rougail/output_doc/__init__.py:79
msgid "ports 1024 to 49151 are allowed"
msgstr "les ports entre 1024 et 49151 sont autorisés"
#: src/rougail/output_doc/__init__.py:80
msgid "ports greater than 49152 are allowed"
msgstr "les ports supérieurs à 49152 sont autorisés"
#: src/rougail/output_doc/__init__.py:125
msgid "mandatory"
msgstr "obligatoire"
#: src/rougail/output_doc/__init__.py:126
msgid "hidden"
msgstr "caché"
#: src/rougail/output_doc/__init__.py:127
msgid "disabled"
msgstr "désactivé"
#: src/rougail/output_doc/__init__.py:128
msgid "unique"
msgstr "unique"
#: src/rougail/output_doc/__init__.py:129
msgid "auto modified"
msgstr "auto modifiée"
#: src/rougail/output_doc/__init__.py:163
msgid "Variables for \"{0}\""
msgstr "Variables pour \"{0}\""
#: src/rougail/output_doc/__init__.py:180
msgid "Variables"
msgstr "Variables"
#: src/rougail/output_doc/__init__.py:187
msgid "Example with mandatory variables not filled in"
msgstr "Exemple avec des variables obligatoire non renseignée"
#: src/rougail/output_doc/__init__.py:493
msgid "(default)"
msgstr "(defaut)"
#: src/rougail/output_doc/__init__.py:498
msgid "Choices"
msgstr "Choix"
#: src/rougail/output_doc/__init__.py:501
msgid "Default"
msgstr "Défaut"
#: src/rougail/output_doc/__init__.py:559
msgid "the value of the variable \"{0}\""
msgstr "la valeur de la variable \"{0}\""
#: src/rougail/output_doc/__init__.py:564
#: src/rougail/output_doc/__init__.py:566
msgid "value of the {0}"
msgstr "la valeur de {0}"
#: src/rougail/output_doc/__init__.py:638
#: src/rougail/output_doc/__init__.py:651
msgid "Example"
msgstr "Exemple"
#: src/rougail/output_doc/__init__.py:649
msgid "Examples"
msgstr "Exemples"

View file

@ -0,0 +1,151 @@
# 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-01 11:42+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/output_doc/__init__.py:40
msgid "the domain name can starts by a dot"
msgstr ""
#: src/rougail/output_doc/__init__.py:41
msgid "the domain name can be a hostname"
msgstr ""
#: src/rougail/output_doc/__init__.py:42
msgid "the domain name can be an IP"
msgstr ""
#: src/rougail/output_doc/__init__.py:43
msgid "the domain name can be network in CIDR format"
msgstr ""
#: src/rougail/output_doc/__init__.py:48
msgid "the minimum value is {0}"
msgstr ""
#: src/rougail/output_doc/__init__.py:49
msgid "the maximum value is {0}"
msgstr ""
#: src/rougail/output_doc/__init__.py:55
msgid "IP must be in CIDR format"
msgstr ""
#: src/rougail/output_doc/__init__.py:56
msgid "private IP are allowed"
msgstr ""
#: src/rougail/output_doc/__init__.py:57
msgid "reserved IP are allowed"
msgstr ""
#: src/rougail/output_doc/__init__.py:62
msgid "the host name can be an IP"
msgstr ""
#: src/rougail/output_doc/__init__.py:67
msgid "the domain name in web address can be an IP"
msgstr ""
#: src/rougail/output_doc/__init__.py:68
msgid "the domain name in web address can be only a hostname"
msgstr ""
#: src/rougail/output_doc/__init__.py:75
msgid "can be range of port"
msgstr ""
#: src/rougail/output_doc/__init__.py:76
msgid "can have the protocol"
msgstr ""
#: src/rougail/output_doc/__init__.py:77
msgid "port 0 is allowed"
msgstr ""
#: src/rougail/output_doc/__init__.py:78
msgid "ports 1 to 1023 are allowed"
msgstr ""
#: src/rougail/output_doc/__init__.py:79
msgid "ports 1024 to 49151 are allowed"
msgstr ""
#: src/rougail/output_doc/__init__.py:80
msgid "ports greater than 49152 are allowed"
msgstr ""
#: src/rougail/output_doc/__init__.py:125
msgid "mandatory"
msgstr ""
#: src/rougail/output_doc/__init__.py:126
msgid "hidden"
msgstr ""
#: src/rougail/output_doc/__init__.py:127
msgid "disabled"
msgstr ""
#: src/rougail/output_doc/__init__.py:128
msgid "unique"
msgstr ""
#: src/rougail/output_doc/__init__.py:129
msgid "auto modified"
msgstr ""
#: src/rougail/output_doc/__init__.py:163
msgid "Variables for \"{0}\""
msgstr ""
#: src/rougail/output_doc/__init__.py:180
msgid "Variables"
msgstr ""
#: src/rougail/output_doc/__init__.py:187
msgid "Example with mandatory variables not filled in"
msgstr ""
#: src/rougail/output_doc/__init__.py:493
msgid "(default)"
msgstr ""
#: src/rougail/output_doc/__init__.py:498
msgid "Choices"
msgstr ""
#: src/rougail/output_doc/__init__.py:501
msgid "Default"
msgstr ""
#: src/rougail/output_doc/__init__.py:559
msgid "the value of the variable \"{0}\""
msgstr ""
#: src/rougail/output_doc/__init__.py:564
#: src/rougail/output_doc/__init__.py:566
msgid "value of the {0}"
msgstr ""
#: src/rougail/output_doc/__init__.py:638
#: src/rougail/output_doc/__init__.py:651
msgid "Example"
msgstr ""
#: src/rougail/output_doc/__init__.py:649
msgid "Examples"
msgstr ""

41
pyproject.toml Normal file
View file

@ -0,0 +1,41 @@
[build-system]
build-backend = "flit_core.buildapi"
requires = ["flit_core >=3.8.0,<4"]
[project]
name = "rougail.output_doc"
version = "0.0.0"
authors = [{name = "Emmanuel Garette", email = "gnunux@gnunux.info"}]
readme = "README.md"
description = "Rougail output doc"
requires-python = ">=3.8"
license = {file = "LICENSE"}
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",
"Natural Language :: French",
]
dependencies = [
"rougail ~= 1.1.0",
"tabulate ~= 0.9.0",
]
[project.urls]
Home = "https://forge.cloud.silique.fr/stove/rougail-output-exporter"
[tool.commitizen]
name = "cz_conventional_commits"
tag_format = "$version"
version_scheme = "pep440"
version_provider = "pep621"
update_changelog_on_bump = true
changelog_merge_prerelease = true

View file

@ -1,25 +1,22 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
Silique (https://www.silique.fr) Silique (https://www.silique.fr)
Copyright (C) 2022-2024 Copyright (C) 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 This program is distributed in the hope that it will be useful, but WITHOUT
it under the terms of the GNU General Public License as published by ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
the Free Software Foundation; either version 2 of the License, or FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
(at your option) any later version. details.
This program is distributed in the hope that it will be useful, You should have received a copy of the GNU Lesser General Public License
but WITHOUT ANY WARRANTY; without even the implied warranty of along with this program. If not, see <http://www.gnu.org/licenses/>.
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
""" """
#FIXME si plusieurs example dont le 1er est none tester les autres : tests/dictionaries/00_8test_none # FIXME si plusieurs example dont le 1er est none tester les autres : tests/dictionaries/00_8test_none
from tiramisu import Calculation from tiramisu import Calculation
from tiramisu.error import display_list from tiramisu.error import display_list
import tabulate as tabulate_module import tabulate as tabulate_module
@ -27,62 +24,62 @@ from tabulate import tabulate
from warnings import warn from warnings import warn
from typing import Optional from typing import Optional
from gettext import gettext as _
from rougail.error import display_xmlfiles from rougail.error import display_xmlfiles
from rougail import RougailConfig, Rougail, CONVERT_OPTION from rougail import RougailConfig, Rougail, CONVERT_OPTION
from rougail.object_model import PROPERTY_ATTRIBUTE from rougail.object_model import PROPERTY_ATTRIBUTE
from .config import OutPuts from .config import OutPuts
from .i18n import _
ENTER = "\n\n" ENTER = "\n\n"
DocTypes = { DocTypes = {
'domainname': { "domainname": {
'params': { "params": {
'allow_startswith_dot': _('the domain name can starts by a dot'), "allow_startswith_dot": _("the domain name can starts by a dot"),
'allow_without_dot': _('the domain name can be only a hostname'), "allow_without_dot": _("the domain name can be a hostname"),
'allow_ip': _('the domain name can be an IP'), "allow_ip": _("the domain name can be an IP"),
'allow_cidr_network': _('the domain name can be network in CIDR format'), "allow_cidr_network": _("the domain name can be network in CIDR format"),
}, },
}, },
'number': { "number": {
'params': { "params": {
'min_number': _('the minimum value is {value}'), "min_number": _("the minimum value is {0}"),
'max_number': _('the maximum value is {value}'), "max_number": _("the maximum value is {0}"),
}, },
}, },
'ip': { "ip": {
'msg': 'IP', "msg": "IP",
'params': { "params": {
'cidr': _('IP must be in CIDR format'), "cidr": _("IP must be in CIDR format"),
'private_only': _('private IP are allowed'), "private_only": _("private IP are allowed"),
'allow_reserved': _('reserved IP are allowed'), "allow_reserved": _("reserved IP are allowed"),
}, },
}, },
'hostname': { "hostname": {
'params': { "params": {
'allow_ip': _('the host name can be an IP'), "allow_ip": _("the host name can be an IP"),
}, },
}, },
'web_address': { "web_address": {
'params': { "params": {
'allow_ip': _('the domain name in web address can be an IP'), "allow_ip": _("the domain name in web address can be an IP"),
'allow_without_dot': _('the domain name in web address can be only a hostname'), "allow_without_dot": _(
"the domain name in web address can be only a hostname"
),
}, },
}, },
'port': { "port": {
'params': { "params": {
'allow_range': _('can be range of port'), "allow_range": _("can be range of port"),
'allow_protocol': _('can have the protocol'), "allow_protocol": _("can have the protocol"),
'allow_zero': _('port 0 is allowed'), "allow_zero": _("port 0 is allowed"),
'allow_wellknown': _('ports 1 to 1023 are allowed'), "allow_wellknown": _("ports 1 to 1023 are allowed"),
'allow_registred': _('ports 1024 to 49151 are allowed'), "allow_registred": _("ports 1024 to 49151 are allowed"),
'allow_private': _('ports greater than 49152 are allowed'), "allow_private": _("ports greater than 49152 are allowed"),
}, },
}, },
} }
@ -92,37 +89,49 @@ ROUGAIL_VARIABLE_TYPE = (
class RougailOutputDoc: class RougailOutputDoc:
def __init__(self, def __init__(
self,
*, *,
config: 'Config'=None, config: "Config" = None,
rougailconfig: RougailConfig=None, rougailconfig: RougailConfig = None,
**kwarg,
): ):
if rougailconfig is None: if rougailconfig is None:
rougailconfig = RougailConfig rougailconfig = RougailConfig
if rougailconfig["step.output"] != "doc":
rougailconfig["step.output"] = "doc"
if rougailconfig["step.output"] != "doc":
raise Exception("doc is not set as step.output")
self.rougailconfig = rougailconfig self.rougailconfig = rougailconfig
outputs = OutPuts().get() outputs = OutPuts().get()
output = self.rougailconfig['doc.output_format'] output = self.rougailconfig["doc.output_format"]
if output not in outputs: if output not in outputs:
raise Exception(f'cannot find output "{output}", available outputs: {list(outputs)}') raise Exception(
f'cannot find output "{output}", available outputs: {list(outputs)}'
)
if config is None: if config is None:
rougail = Rougail(self.rougailconfig) rougail = Rougail(self.rougailconfig)
rougail.converted.plugins.append('output_doc') rougail.converted.plugins.append("output_doc")
config = rougail.get_config() config = rougail.get_config()
self.conf = config self.conf = config
self.conf.property.setdefault(frozenset({'advanced'}), 'read_write', 'append') self.conf.property.setdefault(frozenset({"advanced"}), "read_write", "append")
self.conf.property.read_write() self.conf.property.read_write()
self.conf.property.remove("cache") self.conf.property.remove("cache")
self.dynamic_paths = {} self.dynamic_paths = {}
self.formater = outputs[output]() self.formater = outputs[output]()
self.level = self.rougailconfig['doc.title_level'] self.level = self.rougailconfig["doc.title_level"]
#self.property_to_string = [('mandatory', 'obligatoire'), ('hidden', 'cachée'), ('disabled', 'désactivée'), ('unique', 'unique'), ('force_store_value', 'modifié automatiquement')] # self.property_to_string = [('mandatory', 'obligatoire'), ('hidden', 'cachée'), ('disabled', 'désactivée'), ('unique', 'unique'), ('force_store_value', 'modifié automatiquement')]
self.property_to_string = [('mandatory', _('mandatory')), self.property_to_string = [
('hidden', _('hidden')), ("mandatory", _("mandatory")),
('disabled', _('disabled')), ("hidden", _("hidden")),
('unique', _('unique')), ("disabled", _("disabled")),
('force_store_value', _('auto modified')), ("unique", _("unique")),
("force_store_value", _("auto modified")),
] ]
def run(self):
print(self.gen_doc())
def gen_doc(self): def gen_doc(self):
tabulate_module.PRESERVE_WHITESPACE = True tabulate_module.PRESERVE_WHITESPACE = True
examples_mini = {} examples_mini = {}
@ -133,7 +142,8 @@ class RougailOutputDoc:
name = namespace.name() name = namespace.name()
examples_mini[name] = {} examples_mini[name] = {}
examples_all[name] = {} examples_all[name] = {}
doc = self._display_doc( doc = (
self._display_doc(
self.display_families( self.display_families(
namespace, namespace,
self.level + 1, self.level + 1,
@ -141,16 +151,21 @@ class RougailOutputDoc:
examples_all[name], examples_all[name],
), ),
[], [],
) + '\n' )
+ "\n"
)
if not examples_mini[name]: if not examples_mini[name]:
del examples_mini[name] del examples_mini[name]
if not examples_all[name]: if not examples_all[name]:
del examples_all[name] del examples_all[name]
else: else:
return_string += self.formater.title(_(f'Variables for "{namespace.name()}"'), self.level) return_string += self.formater.title(
_('Variables for "{0}"').format(namespace.name()), self.level
)
return_string += doc return_string += doc
else: else:
doc = self._display_doc( doc = (
self._display_doc(
self.display_families( self.display_families(
self.conf.unrestraint, self.conf.unrestraint,
self.level + 1, self.level + 1,
@ -158,26 +173,29 @@ class RougailOutputDoc:
examples_all, examples_all,
), ),
[], [],
) + '\n' )
+ "\n"
)
if examples_all: if examples_all:
return_string += self.formater.title(_(f'Variables'), self.level) return_string += self.formater.title(_("Variables"), self.level)
return_string += doc return_string += doc
if not examples_all: if not examples_all:
return '' return ""
if self.rougailconfig["doc.with_example"]:
if examples_mini: if examples_mini:
#"Exemple avec les variables obligatoires non renseignées"
return_string += self.formater.title( return_string += self.formater.title(
_("Example with mandatory variables not filled in"), self.level _("Example with mandatory variables not filled in"), self.level
) )
return_string += self.formater.yaml(examples_mini) return_string += self.formater.yaml(examples_mini)
if examples_all: if examples_all:
#"Exemple avec tous les variables modifiables" return_string += self.formater.title(
return_string += self.formater.title("Example with all variables modifiable", self.level) "Example with all variables modifiable", self.level
)
return_string += self.formater.yaml(examples_all) return_string += self.formater.yaml(examples_all)
return return_string return return_string
def _display_doc(self, variables, add_paths): def _display_doc(self, variables, add_paths):
return_string = '' return_string = ""
for variable in variables: for variable in variables:
typ = variable["type"] typ = variable["type"]
path = variable["path"] path = variable["path"]
@ -189,21 +207,50 @@ class RougailOutputDoc:
else: else:
for idx, path in enumerate(variable["paths"]): for idx, path in enumerate(variable["paths"]):
if path in self.dynamic_paths: if path in self.dynamic_paths:
paths_msg = display_list([self.formater.bold(path_) for path_ in self.dynamic_paths[path]['paths']], separator='or') paths_msg = display_list(
variable["objects"][idx][0] = variable["objects"][idx][0].replace('{{ ROUGAIL_PATH }}', paths_msg) [
suffixes = self.dynamic_paths[path]['suffixes'] self.formater.bold(path_)
for path_ in self.dynamic_paths[path]["paths"]
],
separator="or",
)
variable["objects"][idx][0] = variable["objects"][idx][
0
].replace("{{ ROUGAIL_PATH }}", paths_msg)
identifiers = self.dynamic_paths[path]["identifiers"]
description = variable["objects"][idx][1][0] description = variable["objects"][idx][1][0]
if "{{ suffix }}" in description: if "{{ identifier }}" in description:
if description.endswith('.'): if description.endswith("."):
description = description[:-1] description = description[:-1]
comment_msg = self.to_phrase(display_list([description.replace('{{ suffix }}', self.formater.italic(suffix)) for suffix in suffixes], separator='or', add_quote=True)) comment_msg = self.to_phrase(
display_list(
[
description.replace(
"{{ identifier }}",
self.formater.italic(identifier),
)
for identifier in identifiers
],
separator="or",
add_quote=True,
)
)
variable["objects"][idx][1][0] = comment_msg variable["objects"][idx][1][0] = comment_msg
variable["objects"][idx][1] = self.formater.join(variable["objects"][idx][1]) variable["objects"][idx][1] = self.formater.join(
return_string += self.formater.table(tabulate( variable["objects"][idx][1]
)
return_string += (
self.formater.table(
tabulate(
variable["objects"], variable["objects"],
headers=self.formater.table_header(['Variable', 'Description']), headers=self.formater.table_header(
["Variable", "Description"]
),
tablefmt=self.formater.name, tablefmt=self.formater.name,
)) + '\n\n' )
)
+ "\n\n"
)
add_paths.append(path) add_paths.append(path)
return return_string return return_string
@ -236,8 +283,12 @@ class RougailOutputDoc:
continue continue
path = child.path(uncalculated=True) path = child.path(uncalculated=True)
if child.isdynamic(): if child.isdynamic():
self.dynamic_paths.setdefault(path, {'paths': [], 'suffixes': []})['paths'].append(child.path()) self.dynamic_paths.setdefault(
self.dynamic_paths[path]['suffixes'].append(child.suffixes()[-1]) path, {"paths": [], "identifiers": []}
)["paths"].append(child.path())
self.dynamic_paths[path]["identifiers"].append(
child.identifiers()[-1]
)
if not variables or variables[-1]["type"] != "variables": if not variables or variables[-1]["type"] != "variables":
variables.append( variables.append(
{ {
@ -298,9 +349,18 @@ class RougailOutputDoc:
title = f"{family.path()}" title = f"{family.path()}"
isdynamic = family.isdynamic(only_self=True) isdynamic = family.isdynamic(only_self=True)
if isdynamic: if isdynamic:
suffixes = family.suffixes(only_self=True) identifiers = family.identifiers(only_self=True)
if '{{ suffix }}' in title: if "{{ identifier }}" in title:
title = display_list([title.replace('{{ suffix }}', self.formater.italic(suffix)) for suffix in suffixes], separator='or', add_quote=True) title = display_list(
[
title.replace(
"{{ identifier }}", self.formater.italic(identifier)
)
for identifier in identifiers
],
separator="or",
add_quote=True,
)
msg = self.formater.title(title, level) msg = self.formater.title(title, level)
subparameter = [] subparameter = []
self.manage_properties(family, subparameter) self.manage_properties(family, subparameter)
@ -309,8 +369,8 @@ class RougailOutputDoc:
comment = [] comment = []
self.subparameter_to_parameter(subparameter, comment) self.subparameter_to_parameter(subparameter, comment)
if comment: if comment:
msg += '\n'.join(comment) + ENTER msg += "\n".join(comment) + ENTER
help = self.to_phrase(family.information.get('help', "")) help = self.to_phrase(family.information.get("help", ""))
if help: if help:
msg += "\n" + help + ENTER msg += "\n" + help + ENTER
if family.isleadership(): if family.isleadership():
@ -318,39 +378,43 @@ class RougailOutputDoc:
help = "This family contains lists of variable blocks." help = "This family contains lists of variable blocks."
msg += "\n" + help + ENTER msg += "\n" + help + ENTER
if isdynamic: if isdynamic:
suffixes = family.suffixes(only_self=True , uncalculated=True) identifiers = family.identifiers(only_self=True, uncalculated=True)
if isinstance(suffixes, Calculation): if isinstance(identifiers, Calculation):
suffixes = self.to_string(family, 'dynamic') identifiers = self.to_string(family, "dynamic")
if isinstance(suffixes, list): if isinstance(identifiers, list):
for idx, val in enumerate(suffixes): for idx, val in enumerate(identifiers):
if not isinstance(val, Calculation): if not isinstance(val, Calculation):
continue continue
suffixes[idx] = self.to_string(family, 'dynamic', f'_{idx}') identifiers[idx] = self.to_string(family, "dynamic", f"_{idx}")
suffixes = self.formater.list(suffixes) identifiers = self.formater.list(identifiers)
#help = f"Cette famille construit des familles dynamiquement.\n\n{self.formater.bold('Suffixes')}: {suffixes}" # help = f"Cette famille construit des familles dynamiquement.\n\n{self.formater.bold('Identifiers')}: {identifiers}"
help = f"This family builds families dynamically.\n\n{self.formater.bold('Suffixes')}: {suffixes}" help = f"This family builds families dynamically.\n\n{self.formater.bold('Identifiers')}: {identifiers}"
msg += "\n" + help + ENTER msg += "\n" + help + ENTER
return msg return msg
def manage_properties(self, def manage_properties(
self,
variable, variable,
subparameter, subparameter,
): ):
properties = variable.property.get(uncalculated=True) properties = variable.property.get(uncalculated=True)
for mode in self.rougailconfig['modes_level']: for mode in self.rougailconfig["modes_level"]:
if mode in properties: if mode in properties:
subparameter.append((self.formater.prop(mode), None, None)) subparameter.append((self.formater.prop(mode), None, None))
break break
for prop, msg in self.property_to_string: for prop, msg in self.property_to_string:
if prop in properties: if prop in properties:
subparameter.append((self.formater.prop(msg), None, None)) subparameter.append((self.formater.prop(msg), None, None))
elif variable.information.get(f'{prop}_calculation', False): elif variable.information.get(f"{prop}_calculation", False):
subparameter.append((self.formater.prop(msg), msg, self.to_string(variable, prop))) subparameter.append(
(self.formater.prop(msg), msg, self.to_string(variable, prop))
)
def subparameter_to_string(self, def subparameter_to_string(
self,
subparameter, subparameter,
): ):
subparameter_str = '' subparameter_str = ""
for param in subparameter: for param in subparameter:
if param[1]: if param[1]:
subparameter_str += f"_{param[0]}_ " subparameter_str += f"_{param[0]}_ "
@ -358,7 +422,8 @@ class RougailOutputDoc:
subparameter_str += f"{param[0]} " subparameter_str += f"{param[0]} "
return subparameter_str[:-1] return subparameter_str[:-1]
def subparameter_to_parameter(self, def subparameter_to_parameter(
self,
subparameter, subparameter,
comment, comment,
): ):
@ -370,10 +435,10 @@ class RougailOutputDoc:
def to_phrase(self, msg): def to_phrase(self, msg):
if not msg: if not msg:
return '' return ""
msg = str(msg).strip() msg = str(msg).strip()
if not msg.endswith('.'): if not msg.endswith("."):
msg += '.' msg += "."
return msg[0].upper() + msg[1:] return msg[0].upper() + msg[1:]
def display_variable( def display_variable(
@ -389,14 +454,16 @@ class RougailOutputDoc:
subparameter = [] subparameter = []
description = variable.description(uncalculated=True) description = variable.description(uncalculated=True)
comment = [self.to_phrase(description)] comment = [self.to_phrase(description)]
help_ = self.to_phrase(variable.information.get("help", '')) help_ = self.to_phrase(variable.information.get("help", ""))
if help_: if help_:
comment.append(help_) comment.append(help_)
self.type_to_string(variable, self.type_to_string(
variable,
subparameter, subparameter,
comment, comment,
) )
self.manage_properties(variable, self.manage_properties(
variable,
subparameter, subparameter,
) )
if variable.ismulti(): if variable.ismulti():
@ -410,28 +477,30 @@ class RougailOutputDoc:
if variable.name() == description: if variable.name() == description:
warning = f'No attribute "description" for variable "{variable.path()}" in {display_xmlfiles(variable.information.get("dictionaries"))}' warning = f'No attribute "description" for variable "{variable.path()}" in {display_xmlfiles(variable.information.get("dictionaries"))}'
warn(warning) warn(warning)
default = self.get_default(variable, default = self.get_default(
variable,
comment, comment,
) )
default_in_choices = False default_in_choices = False
if variable.information.get("type") == 'choice': if variable.information.get("type") == "choice":
choices = variable.value.list(uncalculated=True) choices = variable.value.list(uncalculated=True)
if isinstance(choices, Calculation): if isinstance(choices, Calculation):
choices = self.to_string(variable, 'choice') choices = self.to_string(variable, "choice")
if isinstance(choices, list): if isinstance(choices, list):
for idx, val in enumerate(choices): for idx, val in enumerate(choices):
if not isinstance(val, Calculation): if not isinstance(val, Calculation):
if default is not None and val == default: if default is not None and val == default:
choices[idx] = str(val) + '' + _("(default)") choices[idx] = str(val) + "" + _("(default)")
default_in_choices = True default_in_choices = True
continue continue
choices[idx] = self.to_string(variable, 'choice', f'_{idx}') choices[idx] = self.to_string(variable, "choice", f"_{idx}")
choices = self.formater.list(choices) choices = self.formater.list(choices)
comment.append(f'{self.formater.bold(_("Choices"))}: {choices}') comment.append(f'{self.formater.bold(_("Choices"))}: {choices}')
# choice # choice
if default is not None and not default_in_choices: if default is not None and not default_in_choices:
comment.append(f"{self.formater.bold(_('Default'))}: {default}") comment.append(f"{self.formater.bold(_('Default'))}: {default}")
self.manage_exemples(multi, self.manage_exemples(
multi,
variable, variable,
examples_all, examples_all,
examples_mini, examples_mini,
@ -441,83 +510,113 @@ class RougailOutputDoc:
self.formater.columns(parameter, comment) self.formater.columns(parameter, comment)
return [self.formater.join(parameter), comment] return [self.formater.join(parameter), comment]
def get_default(self, def get_default(
self,
variable, variable,
comment, comment,
): ):
if variable.information.get('fake_default', False): if variable.information.get("fake_default", False):
default = None default = None
else: else:
default = variable.value.get(uncalculated=True) default = variable.value.get(uncalculated=True)
if default in [None, []]: if default in [None, []]:
return return
if isinstance(default, Calculation): if isinstance(default, Calculation):
default = self.to_string(variable, 'default') default = self.to_string(variable, "default")
if isinstance(default, list): if isinstance(default, list):
for idx, val in enumerate(default): for idx, val in enumerate(default):
if not isinstance(val, Calculation): if not isinstance(val, Calculation):
continue continue
default[idx] = self.to_string(variable, 'default', f'_{idx}') default[idx] = self.to_string(variable, "default", f"_{idx}")
default = self.formater.list(default) default = self.formater.list(default)
return default return default
def to_string(self, def to_string(
self,
variable, variable,
prop, prop,
suffix='', identifier="",
): ):
calculation_type = variable.information.get(f'{prop}_calculation_type{suffix}', None) calculation_type = variable.information.get(
f"{prop}_calculation_type{identifier}", None
)
if not calculation_type: if not calculation_type:
raise Exception(f'cannot find {prop}_calculation_type{suffix} information, do you have declare doc has a plugins?') raise Exception(
calculation = variable.information.get(f'{prop}_calculation{suffix}') f"cannot find {prop}_calculation_type{identifier} information, do you have declare doc has a plugins?"
if calculation_type == 'jinja': )
calculation = variable.information.get(f"{prop}_calculation{identifier}")
if calculation_type == "jinja":
if calculation is not True: if calculation is not True:
values = self.formater.to_string(calculation) values = self.formater.to_string(calculation)
else: else:
values = "issu d'un calcul" values = "depends on a calculation"
warning = f'"{prop}" is a calculation for {variable.path()} but has no description in {display_xmlfiles(variable.information.get("dictionaries"))}' warning = f'"{prop}" is a calculation for {variable.path()} but has no description in {display_xmlfiles(variable.information.get("dictionaries"))}'
warn(warning) warn(warning)
elif calculation_type == 'variable': elif calculation_type == "variable":
if prop in PROPERTY_ATTRIBUTE: if prop in PROPERTY_ATTRIBUTE:
values = self.formater.to_string(calculation) values = self.formater.to_string(calculation)
else: else:
values = _(f'the value of the variable "{calculation}"') values = _('the value of the variable "{0}"').format(calculation)
elif calculation_type == "identifier":
if prop in PROPERTY_ATTRIBUTE:
values = self.formater.to_string(calculation)
else: else:
values = _(f"value of the {calculation_type}") values = _("value of the {0}").format(calculation_type)
if not values.endswith('.'): else:
values += '.' values = _("value of the {0}").format(calculation_type)
if not values.endswith("."):
values += "."
return values return values
def type_to_string(self, def type_to_string(
self,
variable, variable,
subparameter, subparameter,
comment, comment,
): ):
variable_type = variable.information.get("type") variable_type = variable.information.get("type")
doc_type = DocTypes.get(variable_type, {'params': {}}) doc_type = DocTypes.get(variable_type, {"params": {}})
subparameter.append((self.formater.link(doc_type.get('msg', variable_type), ROUGAIL_VARIABLE_TYPE), None)) subparameter.append(
(
self.formater.link(
doc_type.get("msg", variable_type), ROUGAIL_VARIABLE_TYPE
),
None,
)
)
option = variable.get() option = variable.get()
validators = [] validators = []
for param, msg in doc_type['params'].items(): for param, msg in doc_type["params"].items():
value = option.impl_get_extra(f'_{param}') value = option.impl_get_extra(f"_{param}")
if value is None: if value is None:
value = option.impl_get_extra(param) value = option.impl_get_extra(param)
if value is not None and value is not False: if value is not None and value is not False:
validators.append(msg.format(value=value)) validators.append(msg.format(value))
valids = [name for name in variable.information.list() if name.startswith('validators_calculation_type_')] valids = [
name
for name in variable.information.list()
if name.startswith("validators_calculation_type_")
]
if valids: if valids:
for idx in range(len(valids)): for idx in range(len(valids)):
validators.append(self.to_string(variable, validators.append(
'validators', self.to_string(
f'_{idx}', variable,
)) "validators",
f"_{idx}",
)
)
if validators: if validators:
if len(validators) == 1: if len(validators) == 1:
comment.append(f'{self.formater.bold("Validator")}: ' + validators[0]) comment.append(f'{self.formater.bold("Validator")}: ' + validators[0])
else: else:
comment.append(f'{self.formater.bold("Validators")}:' + self.formater.list(validators)) comment.append(
f'{self.formater.bold("Validators")}:'
+ self.formater.list(validators)
)
def manage_exemples(self, def manage_exemples(
self,
multi, multi,
variable, variable,
examples_all, examples_all,
@ -526,11 +625,13 @@ class RougailOutputDoc:
): ):
example_mini = None example_mini = None
example_all = None example_all = None
example = variable.information.get("examples", None)
if example is None:
example = variable.information.get("test", None) example = variable.information.get("test", None)
default = variable.value.get() default = variable.value.get()
if isinstance(example, tuple): if isinstance(example, tuple):
example = list(example) example = list(example)
mandatory = 'mandatory' in variable.property.get(uncalculated=True) mandatory = "mandatory" in variable.property.get(uncalculated=True)
if example: if example:
if not multi: if not multi:
example = example[0] example = example[0]
@ -547,14 +648,16 @@ class RougailOutputDoc:
if len_test > 1: if len_test > 1:
title = _("Examples") title = _("Examples")
else: else:
title = _("Exemple") title = _("Example")
comment.append(f"{self.formater.bold(title)}: {example}") comment.append(f"{self.formater.bold(title)}: {example}")
elif default not in [None, []]: elif default not in [None, []]:
example_all = default example_all = default
else: else:
example = CONVERT_OPTION.get(variable.information.get("type"), {}).get('example', None) example = CONVERT_OPTION.get(variable.information.get("type"), {}).get(
"example", None
)
if example is None: if example is None:
example = 'xxx' example = "xxx"
if multi: if multi:
example = [example] example = [example]
if mandatory: if mandatory:
@ -578,3 +681,7 @@ class RougailOutputDoc:
if example_mini is not None: if example_mini is not None:
examples_mini[variable.name()] = example_mini examples_mini[variable.name()] = example_mini
examples_all[variable.name()] = example_all examples_all[variable.name()] = example_all
RougailOutput = RougailOutputDoc
__all__ = ("RougailOutputDoc",)

View file

@ -19,14 +19,24 @@ You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" """
from tiramisu import undefined from tiramisu import undefined
from rougail.annotator.variable import Walk from rougail.annotator.variable import Walk
from rougail.i18n import _ from rougail.i18n import _
from rougail.error import DictConsistencyError from rougail.error import DictConsistencyError
from rougail.object_model import Calculation, JinjaCalculation, VariableCalculation, \ from rougail.object_model import (
InformationCalculation, IndexCalculation, SuffixCalculation, CONVERT_OPTION, \ Calculation,
PROPERTY_ATTRIBUTE JinjaCalculation,
VariableCalculation,
VariablePropertyCalculation,
IdentifierCalculation,
IdentifierPropertyCalculation,
InformationCalculation,
IndexCalculation,
CONVERT_OPTION,
PROPERTY_ATTRIBUTE,
)
class Annotator(Walk): class Annotator(Walk):
@ -45,21 +55,33 @@ class Annotator(Walk):
self.populate_family() self.populate_family()
self.populate_variable() self.populate_variable()
def add_default_value(self, def get_examples_values(self, variable):
values = self.objectspace.informations.get(variable.path).get("examples", None)
if not values:
values = self.objectspace.informations.get(variable.path).get("test", None)
return values
def add_default_value(
self,
family, family,
value, value,
*, *,
inside_list=False, inside_list=False,
) -> None: ) -> None:
if isinstance(value, Calculation): if isinstance(value, Calculation):
default_values ='example' default_values = "example"
if not inside_list: if not inside_list:
default_values = [default_values] default_values = [default_values]
if isinstance(value, VariableCalculation): if isinstance(value, (VariableCalculation, VariablePropertyCalculation)):
variable, suffix = self.objectspace.paths.get_with_dynamic( variable, identifier = self.objectspace.paths.get_with_dynamic(
value.variable, value.path_prefix, family.path, value.version, value.namespace, value.xmlfiles value.variable,
value.path_prefix,
family.path,
value.version,
value.namespace,
value.xmlfiles,
) )
values = self.objectspace.informations.get(variable.path).get('test', None) values = self.get_examples_values(variable)
if values: if values:
if inside_list: if inside_list:
default_values = list(values) default_values = list(values)
@ -81,8 +103,9 @@ class Annotator(Walk):
else: else:
for value in family.dynamic: for value in family.dynamic:
self.add_default_value(family, value, inside_list=True) self.add_default_value(family, value, inside_list=True)
self.calculation_to_information(family.path, self.calculation_to_information(
'dynamic', family.path,
"dynamic",
family.dynamic, family.dynamic,
family.version, family.version,
) )
@ -93,29 +116,31 @@ class Annotator(Walk):
if variable.type == "symlink": if variable.type == "symlink":
continue continue
if variable.type == "choice": if variable.type == "choice":
self.calculation_to_information(variable.path, self.calculation_to_information(
'choice', variable.path,
"choice",
variable.choices, variable.choices,
variable.version, variable.version,
) )
self.calculation_to_information(variable.path, self.calculation_to_information(
'default', variable.path,
"default",
variable.default, variable.default,
variable.version, variable.version,
) )
self.calculation_to_information(variable.path, self.calculation_to_information(
'validators', variable.path,
"validators",
variable.validators, variable.validators,
variable.version, variable.version,
) )
if variable.path in self.objectspace.leaders and \ if variable.path in self.objectspace.leaders and not variable.default:
not variable.default: values = self.get_examples_values(variable)
values = self.objectspace.informations.get(variable.path).get('test', None)
if values: if values:
variable.default = list(values) variable.default = list(values)
else: else:
variable.default = [CONVERT_OPTION[variable.type]['example']] variable.default = [CONVERT_OPTION[variable.type]["example"]]
self.objectspace.informations.add(variable.path, 'fake_default', True) self.objectspace.informations.add(variable.path, "fake_default", True)
self.objectspace.informations.add( self.objectspace.informations.add(
variable.path, "dictionaries", variable.xmlfiles variable.path, "dictionaries", variable.xmlfiles
) )
@ -126,43 +151,48 @@ class Annotator(Walk):
variable: dict, variable: dict,
) -> None: ) -> None:
"""convert properties""" """convert properties"""
for prop in ['hidden', 'disabled', 'mandatory']: for prop in ["hidden", "disabled", "mandatory"]:
prop_value = getattr(variable, prop, None) prop_value = getattr(variable, prop, None)
if not prop_value: if not prop_value:
continue continue
self.calculation_to_information(variable.path, self.calculation_to_information(
variable.path,
prop, prop,
prop_value, prop_value,
variable.version, variable.version,
) )
def calculation_to_information(self, def calculation_to_information(
self,
path: str, path: str,
prop: str, prop: str,
values, values,
version: str, version: str,
): ):
self._calculation_to_information(path, self._calculation_to_information(
path,
prop, prop,
values, values,
version, version,
) )
if isinstance(values, list): if isinstance(values, list):
for idx, val in enumerate(values): for idx, val in enumerate(values):
self._calculation_to_information(path, self._calculation_to_information(
path,
prop, prop,
val, val,
version, version,
suffix=f'_{idx}', identifier=f"_{idx}",
) )
def _calculation_to_information(self, def _calculation_to_information(
self,
path: str, path: str,
prop: str, prop: str,
values, values,
version: str, version: str,
*, *,
suffix: str='', identifier: str = "",
): ):
if not isinstance(values, Calculation): if not isinstance(values, Calculation):
return return
@ -170,12 +200,13 @@ class Annotator(Walk):
if isinstance(values, JinjaCalculation): if isinstance(values, JinjaCalculation):
if values.description: if values.description:
values_calculation = values.description values_calculation = values.description
values_calculation_type = 'jinja' values_calculation_type = "jinja"
elif isinstance(values, VariableCalculation): elif isinstance(values, (VariableCalculation, VariablePropertyCalculation)):
values_calculation = values.variable values_calculation = values.variable
paths = self.objectspace.paths paths = self.objectspace.paths
if version != '1.0' and paths.regexp_relative.search(values_calculation): if version != "1.0" and paths.regexp_relative.search(values_calculation):
calculation_path = paths.get_relative_path(values_calculation, calculation_path = paths.get_full_path(
values_calculation,
path, path,
) )
if prop in PROPERTY_ATTRIBUTE: if prop in PROPERTY_ATTRIBUTE:
@ -187,18 +218,27 @@ class Annotator(Walk):
values_calculation = f'when the variable "{calculation_path}" has the value "True"' values_calculation = f'when the variable "{calculation_path}" has the value "True"'
else: else:
values_calculation = calculation_path values_calculation = calculation_path
values_calculation_type = 'variable' values_calculation_type = "variable"
elif isinstance(values, InformationCalculation): elif isinstance(values, InformationCalculation):
values_calculation_type = 'information' values_calculation_type = "information"
elif isinstance(values, SuffixCalculation): elif isinstance(values, (IdentifierCalculation, IdentifierPropertyCalculation)):
values_calculation_type = 'suffix' if version != "1.0" and prop in PROPERTY_ATTRIBUTE:
if values.when is not undefined:
values_calculation = f'when the identifier is "{values.when}"'
elif values.when_not is not undefined:
values_calculation = (
f'when the identifier is not "{values.when_not}"'
)
values_calculation_type = "identifier"
elif isinstance(values, IndexCalculation): elif isinstance(values, IndexCalculation):
values_calculation_type = 'index' values_calculation_type = "index"
self.objectspace.informations.add(path, self.objectspace.informations.add(
f'{prop}_calculation_type{suffix}', path,
f"{prop}_calculation_type{identifier}",
values_calculation_type, values_calculation_type,
) )
self.objectspace.informations.add(path, self.objectspace.informations.add(
f'{prop}_calculation{suffix}', path,
f"{prop}_calculation{identifier}",
values_calculation, values_calculation,
) )

View file

@ -1,36 +0,0 @@
"""
Cli code for Rougail-output-doc
Silique (https://www.silique.fr)
Copyright (C) 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 . import RougailOutputDoc
def run(rougailconfig,
config,
user_data,
):
inventory = RougailOutputDoc(config=config,
rougailconfig=rougailconfig,
)
print(inventory.gen_doc())
__all__ = ('run',)

View file

@ -4,43 +4,42 @@ Config file for Rougail-doc
Silique (https://www.silique.fr) Silique (https://www.silique.fr)
Copyright (C) 2024 Copyright (C) 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 This program is distributed in the hope that it will be useful, but WITHOUT
it under the terms of the GNU General Public License as published by ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
the Free Software Foundation; either version 2 of the License, or FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
(at your option) any later version. details.
This program is distributed in the hope that it will be useful, You should have received a copy of the GNU Lesser General Public License
but WITHOUT ANY WARRANTY; without even the implied warranty of along with this program. If not, see <http://www.gnu.org/licenses/>.
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 pathlib import Path from pathlib import Path
from rougail.utils import load_modules from rougail.utils import load_modules
# from .utils import _
OUTPUTS = None OUTPUTS = None
def get_outputs() -> None: def get_outputs() -> None:
module_name = 'rougail.doc.output' module_name = "rougail.doc.output"
outputs = {} outputs = {}
for path in (Path(__file__).parent / 'output').iterdir(): for path in (Path(__file__).parent / "output").iterdir():
name = path.name name = path.name
if not name.endswith(".py") or name.endswith("__.py"): if not name.endswith(".py") or name.endswith("__.py"):
continue continue
module = load_modules(module_name + '.' + name, str(path)) module = load_modules(module_name + "." + name, str(path))
if "Formater" not in dir(module): if "Formater" not in dir(module):
continue continue
level = module.Formater.level level = module.Formater.level
if level in outputs: if level in outputs:
raise Exception(f'duplicated level rougail-doc for output "{level}": {module.Formater.name} and {outputs[level].name}') raise Exception(
f'duplicated level rougail-doc for output "{level}": {module.Formater.name} and {outputs[level].name}'
)
outputs[module.Formater.level] = module.Formater outputs[module.Formater.level] = module.Formater
return {outputs[level].name: outputs[level] for level in sorted(outputs)} return {outputs[level].name: outputs[level] for level in sorted(outputs)}
@ -59,9 +58,10 @@ class OutPuts: # pylint: disable=R0903
return OUTPUTS return OUTPUTS
def get_rougail_config(*, def get_rougail_config(
*,
backward_compatibility=True, backward_compatibility=True,
) -> dict: ) -> dict:
outputs = list(OutPuts().get()) outputs = list(OutPuts().get())
output_format_default = outputs[0] output_format_default = outputs[0]
rougail_options = """ rougail_options = """
@ -77,20 +77,28 @@ doc:
description: Start title level description: Start title level
alternative_name: dt alternative_name: dt
default: 1 default: 1
with_example:
description: Display example in documentation
negative_description: Hide example in documentation
alternative_name: de
default: false
output_format: output_format:
description: Generate document in format description: Generate document in format
alternative_name: do alternative_name: do
default: output_format_default default: output_format_default
choices: choices:
""".replace('output_format_default', output_format_default) """.replace(
"output_format_default", output_format_default
)
for output in outputs: for output in outputs:
rougail_options += f" - {output}\n" rougail_options += f" - {output}\n"
return {'name': 'doc', return {
'process': 'output', "name": "doc",
'options': rougail_options, "process": "output",
'allow_user_data': False, "options": rougail_options,
'level': 50, "allow_user_data": False,
"level": 50,
} }
__all__ = ("OutPuts", 'get_rougail_config') __all__ = ("OutPuts", "get_rougail_config")

View file

@ -0,0 +1,24 @@
"""Internationalisation utilities
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 gettext import translation
from pathlib import Path
t = translation("rougail_output_doc", str(Path(__file__).parent / "locale"), fallback=True)
_ = t.gettext

View file

@ -2,24 +2,16 @@
Silique (https://www.silique.fr) Silique (https://www.silique.fr)
Copyright (C) 2024 Copyright (C) 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 This program is distributed in the hope that it will be useful, but WITHOUT
it under the terms of the GNU General Public License as published by ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
the Free Software Foundation; either version 2 of the License, or FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
(at your option) any later version. details.
This program is distributed in the hope that it will be useful, You should have received a copy of the GNU Lesser General Public License
but WITHOUT ANY WARRANTY; without even the implied warranty of along with this program. If not, see <http://www.gnu.org/licenses/>.
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
""" """
def echo(msg):
return msg
_ = echo

View file

@ -1,3 +1,21 @@
"""
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 io import BytesIO from io import BytesIO
from typing import List from typing import List
from itertools import chain from itertools import chain
@ -5,7 +23,7 @@ from ruamel.yaml import YAML
class Formater: class Formater:
name = 'asciidoc' name = "asciidoc"
level = 40 level = 40
def __init__(self): def __init__(self):
@ -13,9 +31,10 @@ class Formater:
self._yaml.indent(mapping=2, sequence=4, offset=2) self._yaml.indent(mapping=2, sequence=4, offset=2)
def header(self): def header(self):
return '' return ""
def title(self, def title(
self,
title: str, title: str,
level: int, level: int,
) -> str: ) -> str:
@ -30,47 +49,53 @@ class Formater:
stable = table.split("\n", 1) stable = table.split("\n", 1)
return stable[0].replace("<", "a") + "\n" + stable[1] return stable[0].replace("<", "a") + "\n" + stable[1]
def link(self, def link(
self,
comment: str, comment: str,
link: str, link: str,
) -> str: ) -> str:
return f"`{link}[{comment}]`" return f"`{link}[{comment}]`"
def prop(self, def prop(
self,
prop: str, prop: str,
) -> str: ) -> str:
return f'`{prop}`' return f"`{prop}`"
def list(self, def list(
self,
choices: list, choices: list,
) -> str: ) -> str:
prefix = "\n\n* " prefix = "\n\n* "
char = "\n* " char = "\n* "
return prefix + char.join([self.dump(choice) for choice in choices]) return prefix + char.join([self.dump(choice) for choice in choices])
def is_list(self, def is_list(
self,
txt: str, txt: str,
) -> str: ) -> str:
return txt.startswith('* ') return txt.startswith("* ")
def columns(self, def columns(
self,
col1: List[str], col1: List[str],
col2: List[str], col2: List[str],
) -> None: ) -> None:
self.max_line = 0 self.max_line = 0
for params in chain(col1, col2): for params in chain(col1, col2):
for param in params.split('\n'): for param in params.split("\n"):
self.max_line = max(self.max_line, len(param)) self.max_line = max(self.max_line, len(param))
self.max_line += 1 self.max_line += 1
def join(self, def join(
self,
lst: List[str], lst: List[str],
) -> str: ) -> str:
string = "" string = ""
previous = '' previous = ""
for line in lst: for line in lst:
if string: if string:
if self.is_list(previous.split('\n')[-1]): if self.is_list(previous.split("\n")[-1]):
string += "\n\n" string += "\n\n"
else: else:
string += " +\n" string += " +\n"
@ -79,22 +104,28 @@ class Formater:
previous = line previous = line
return "\n" + string return "\n" + string
def to_string(self, def to_string(
self,
text: str, text: str,
) -> str: ) -> str:
return text return text
def table_header(self, def table_header(
self,
lst, lst,
): ):
return lst[0] + " " * (self.max_line - len(lst[0])), lst[1] + " " * (self.max_line - len(lst[1])) return lst[0] + " " * (self.max_line - len(lst[0])), lst[1] + " " * (
self.max_line - len(lst[1])
)
def bold(self, def bold(
self,
msg: str, msg: str,
) -> str: ) -> str:
return f"**{msg}**" return f"**{msg}**"
def italic(self, def italic(
self,
msg: str, msg: str,
) -> str: ) -> str:
return f"_{msg}_" return f"_{msg}_"
@ -102,7 +133,7 @@ class Formater:
def dump(self, dico): def dump(self, dico):
with BytesIO() as ymlfh: with BytesIO() as ymlfh:
self._yaml.dump(dico, ymlfh) self._yaml.dump(dico, ymlfh)
ret = ymlfh.getvalue().decode('utf-8').strip() ret = ymlfh.getvalue().decode("utf-8").strip()
if ret.endswith('...'): if ret.endswith("..."):
ret = ret[:-3].strip() ret = ret[:-3].strip()
return ret return ret

View file

@ -1,3 +1,21 @@
"""
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 io import BytesIO from io import BytesIO
from typing import List from typing import List
from itertools import chain from itertools import chain
@ -5,7 +23,7 @@ from ruamel.yaml import YAML
class Formater: class Formater:
name = 'github' name = "github"
level = 50 level = 50
def __init__(self): def __init__(self):
@ -15,11 +33,12 @@ class Formater:
def header(self): def header(self):
if self.header_setted: if self.header_setted:
return '' return ""
self.header_setted = True self.header_setted = True
return "---\ngitea: none\ninclude_toc: true\n---\n" return "---\ngitea: none\ninclude_toc: true\n---\n"
def title(self, def title(
self,
title: str, title: str,
level: int, level: int,
) -> str: ) -> str:
@ -32,59 +51,69 @@ class Formater:
def table(self, table): def table(self, table):
return table return table
def link(self, def link(
self,
comment: str, comment: str,
link: str, link: str,
) -> str: ) -> str:
return f"[`{comment}`]({link})" return f"[`{comment}`]({link})"
def prop(self, def prop(
self,
prop: str, prop: str,
) -> str: ) -> str:
return f'`{prop}`' return f"`{prop}`"
def list(self, def list(
self,
choices, choices,
): ):
prefix = "<br/>- " prefix = "<br/>- "
char = "<br/>- " char = "<br/>- "
return prefix + char.join([self.dump(choice) for choice in choices]) return prefix + char.join([self.dump(choice) for choice in choices])
def is_list(self, def is_list(
self,
txt: str, txt: str,
) -> str: ) -> str:
return txt.startswith('* ') return txt.startswith("* ")
def columns(self, def columns(
self,
col1: List[str], col1: List[str],
col2: List[str], col2: List[str],
) -> None: ) -> None:
self.max_line = 0 self.max_line = 0
for params in chain(col1, col2): for params in chain(col1, col2):
for param in params.split('\n'): for param in params.split("\n"):
self.max_line = max(self.max_line, len(param)) self.max_line = max(self.max_line, len(param))
self.max_line += 1 self.max_line += 1
def join(self, def join(
self,
lst: List[str], lst: List[str],
) -> str: ) -> str:
return "<br/>".join(lst) return "<br/>".join(lst)
def to_string(self, def to_string(
self,
text: str, text: str,
) -> str: ) -> str:
return text.strip().replace('\n', '<br/>') return text.strip().replace("\n", "<br/>")
def table_header(self, def table_header(self, lst):
lst): return lst[0] + "&nbsp;" * (self.max_line - len(lst[0])), lst[1] + "&nbsp;" * (
return lst[0] + "&nbsp;" * (self.max_line - len(lst[0])), lst[1] + "&nbsp;" * (self.max_line - len(lst[1])) self.max_line - len(lst[1])
)
def bold(self, def bold(
self,
msg: str, msg: str,
) -> str: ) -> str:
return f"**{msg}**" return f"**{msg}**"
def italic(self, def italic(
self,
msg: str, msg: str,
) -> str: ) -> str:
return f"*{msg}*" return f"*{msg}*"
@ -92,7 +121,7 @@ class Formater:
def dump(self, dico): def dump(self, dico):
with BytesIO() as ymlfh: with BytesIO() as ymlfh:
self._yaml.dump(dico, ymlfh) self._yaml.dump(dico, ymlfh)
ret = ymlfh.getvalue().decode('utf-8').strip() ret = ymlfh.getvalue().decode("utf-8").strip()
if ret.endswith('...'): if ret.endswith("..."):
ret = ret[:-3].strip() ret = ret[:-3].strip()
return ret return ret