diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..913638f --- /dev/null +++ b/.gitignore @@ -0,0 +1,134 @@ +# SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +# SPDX-License-Identifier: CC0-1.0 + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +.idea/ diff --git a/LICENSES/CC-BY-SA-4.0.txt b/LICENSES/CC-BY-SA-4.0.txt new file mode 100644 index 0000000..835a683 --- /dev/null +++ b/LICENSES/CC-BY-SA-4.0.txt @@ -0,0 +1,170 @@ +Creative Commons Attribution-ShareAlike 4.0 International + + Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. + +Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. + +Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. + +Creative Commons Attribution-ShareAlike 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + + a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + + e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + + i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. + + k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + + 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. Downstream recipients. + + A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. + + C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. + + 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; + + b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + + a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. + + b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. + + c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + + a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + + d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +Section 8 – Interpretation. + + a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + + c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + + d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/LGPL-2.1-or-later.txt b/LICENSES/LGPL-2.1-or-later.txt new file mode 100644 index 0000000..c9aa530 --- /dev/null +++ b/LICENSES/LGPL-2.1-or-later.txt @@ -0,0 +1,175 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +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. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, 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 and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, 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 library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete 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 distribute a copy of this License along with the Library. + +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. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, 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 Library, 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. + +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 Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you 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. + +If distribution of 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 satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be 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. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. 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 not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library 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. + +9. 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 Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library 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 with this License. + +11. 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 Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library 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 Library. + +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. + +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. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library 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. + +13. The Free Software Foundation may publish revised and/or new versions of the 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 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 Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, 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 + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. 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 LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. 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 library's name and an idea of what it does. + Copyright (C) year name of author + + This library 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 2.1 of the License, or (at your option) any later version. + + This library 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 library; 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. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/README.md b/README.md new file mode 100644 index 0000000..b4e7a76 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ + + +# mdit-py-i18n + +Markdown i18n and l10n using markdown-it-py. + +CommonMark compliant. All core Markdown elements are supported, as well as +table, and definition list. Front matter handlers are left for users to +implement. + +## Install + +```bash +pip install mdit-py-i18n +``` + +## Notes + +Some notes about how different elements are handled: +- Inlines: newlines and consecutive spaces are not kept; +- Content of each HTML block isn't parsed into finer tokens but processed +as a whole; +- Fenced code blocks: only `//` single comments are processed; + +## Development + +### Environment + +- With Conda + +```bash +conda env create -f environment.yml +conda activate mpi +poetry install +``` + +### Usage + +#### Extraction +- Follow `I18NEntryProtocol` and `DomainExtractionProtocol` +- Subclass `RendererMarkdownI18N` + +#### Generation +- Follow `DomainGenerationProtocol` +- Subclass `RendererMarkdownL10N` \ No newline at end of file diff --git a/environment.yml b/environment.yml new file mode 100644 index 0000000..7b204c7 --- /dev/null +++ b/environment.yml @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +# SPDX-License-Identifier: CC0-1.0 + +name: mpi +channels: + - conda-forge + - defaults +dependencies: + - python=3.8 diff --git a/mdit_py_i18n/__init__.py b/mdit_py_i18n/__init__.py new file mode 100644 index 0000000..45675aa --- /dev/null +++ b/mdit_py_i18n/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +# SPDX-License-Identifier: LGPL-2.1-or-later diff --git a/mdit_py_i18n/renderer_i18n.py b/mdit_py_i18n/renderer_i18n.py new file mode 100644 index 0000000..d2ff2bb --- /dev/null +++ b/mdit_py_i18n/renderer_i18n.py @@ -0,0 +1,126 @@ +# SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +# SPDX-License-Identifier: LGPL-2.1-or-later + +import inspect +from typing import Sequence + +import pygments.token +from markdown_it import MarkdownIt +from markdown_it.token import Token +from markdown_it.utils import OptionsDict, EnvType +from pygments import lexers, util + +from . import utils +from .utils import DomainExtractionProtocol + + +class _MdCtx: + def __init__(self, env: EnvType): + self.path: str = env['path'] + self.domain_e: DomainExtractionProtocol = env['domain_extraction'] + + def add_entry(self, msgid: str, line_number: int, comment: str = '', msgctxt: str = ''): + self.domain_e.add_entry(self.path, msgid, line_number, comment, msgctxt) + + +def _link_ref(env: EnvType, md_ctx: _MdCtx): + refs = env.get('references', {}).items() + if len(refs) == 0: + return + for ref, details in refs: + if title := details.get('title', ''): + # TODO: line number? + md_ctx.add_entry(title, 0) + + +class RendererMarkdownI18N: + """ + Implements `RendererProtocol` + """ + __output__ = 'pot' + + def __init__(self, mdi: MarkdownIt): + self.rules = { + k: v + for k, v in inspect.getmembers(self, predicate=inspect.ismethod) + if not (k.startswith("render") or k.startswith("_")) + } + self.mdi = mdi + + def render(self, tokens: Sequence[Token], _options: OptionsDict, env: EnvType): + """ + :param tokens: list of block tokens to render + :param _options: properties of parser instance + :param env: containing: + - 'path': path of the source file + - 'domain_extraction': an object compatible with `DomainExtractionProtocol` + :return: None + """ + md_ctx = _MdCtx(env) + + for i, token in enumerate(tokens): + if token.type in self.rules: + r = self.rules[token.type](tokens, i, md_ctx) + if r == -1: + break + + _link_ref(env, md_ctx) + + @classmethod + def front_matter(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx): + token = tokens[idx] + md_ctx.domain_e.render_front_matter(md_ctx.path, token.content, token.markup) + + @classmethod + def inline(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx): + token = tokens[idx] + content = utils.SPACES_PATTERN.sub(' ', token.content.replace('\n', ' ')) + if content and not utils.SPACES_PATTERN.fullmatch(content): + md_ctx.add_entry(content, token.map[0] + 1) + + @classmethod + def fence(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx): + token = tokens[idx] + try: + lexer = lexers.get_lexer_by_name(token.info) + except util.ClassNotFound: + lexer = lexers.guess_lexer(token.content) + code_toks = lexer.get_tokens(token.content) + + # temporary content of the comment being parsed + # also indicates whether we are parsing a comment or not + comment = '' + # number of the line where the comment starts + comment_line_num = 0 + # number of the last line with a comment token + last_comment_line_num = 0 + # the token starts with one line of the fence, then the content. +1: 0-base -> 1-base + line_num = token.map[0] + 1 + 1 + + # concatenate comment tokens until either a non-comment token or a blank line or end of token stream + for tok_type, tok_val in code_toks: + if tok_type == pygments.token.Token.Comment.Single: + # when another comment is already being parsed and there's a blank line + if comment and line_num - last_comment_line_num > 1: + md_ctx.add_entry(comment, comment_line_num) + comment = '' + comment_line_num = 0 + if comment != '': + comment += ' ' + if comment_match := utils.SINGLE_COMMENT_PATTERN.match(tok_val): + comment += comment_match.group(2).strip() + if comment_line_num == 0: + comment_line_num = line_num + last_comment_line_num = line_num + elif tok_val.strip() and comment: + md_ctx.add_entry(comment, comment_line_num) + comment = '' + comment_line_num = 0 + line_num += tok_val.count('\n') + if comment: + md_ctx.add_entry(comment, comment_line_num) + + @classmethod + def html_block(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx): + token = tokens[idx] + md_ctx.add_entry(token.content, token.map[0] + 1) diff --git a/mdit_py_i18n/renderer_l10n.py b/mdit_py_i18n/renderer_l10n.py new file mode 100644 index 0000000..94142b0 --- /dev/null +++ b/mdit_py_i18n/renderer_l10n.py @@ -0,0 +1,382 @@ +# SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +# SPDX-License-Identifier: LGPL-2.1-or-later + +"""Render localized markdown""" + +import inspect +import textwrap +from dataclasses import dataclass +from typing import Sequence, Tuple, List + +import pygments.token +from markdown_it import MarkdownIt +from markdown_it.token import Token +from markdown_it.utils import OptionsDict, EnvType +from pygments import lexers, util + +from . import utils +from .utils import L10NResult, DomainGenerationProtocol + +SETEXT_HEADING_MARKUPS = {'-', '='} +ORDERED_LIST_MARKUPS = {'.', ')'} + + +class _MdCtx: + def __init__(self, env: EnvType): + self.line_indent = '' + self.indent_1st_line = '' # list item, definition detail, atx heading + self.indent_1st_line_len = 0 + self.indents: List[int] = [] + self.setext_heading = '' + self.table_sep = '' + self.in_table = False + self.domain_g: DomainGenerationProtocol = env['domain_generation'] + + def get_line_indent(self): + if not self.indent_1st_line: + return self.line_indent + if self.indent_1st_line_len > 0: + line_indent = self.line_indent[:-self.indent_1st_line_len] + self.indent_1st_line + else: + line_indent = self.line_indent + self.indent_1st_line + self.indent_1st_line = '' + self.indent_1st_line_len = 0 + return line_indent + + +@dataclass +class _FenceCtx: + localized: str = '' # the l10n result + # temporary content of the comment being parsed + # also indicates whether we are parsing a comment or not + comment: str = '' + indent: str = '' # things on the same line before the comment + next_indent: str = '' # a second field when 'indent' is busy + + +# TODO: parameterize: fence code comment i18n, wrap width, comment identifiers +# TODO: multiline comment? +def _fence_comment(fence_ctx: _FenceCtx, md_ctx: _MdCtx, content_result: L10NResult): + localized_comment = md_ctx.domain_g.l10n_func(fence_ctx.comment) + if localized_comment is not fence_ctx.comment: + content_result.l10n_count += 1 + content_result.total_count += 1 + subsequent_indent = ' ' * len(fence_ctx.indent) if fence_ctx.indent.strip() else fence_ctx.indent + comment_lines = textwrap.wrap(localized_comment, + 100, + initial_indent=f'{fence_ctx.indent}// ', + subsequent_indent=f'{subsequent_indent}// ') + for line in comment_lines: + fence_ctx.localized += f'{line}\n' + fence_ctx.comment = '' + + +def _fence(token: Token, md_ctx: _MdCtx, content_result: L10NResult): + try: + lexer = lexers.get_lexer_by_name(token.info) + except util.ClassNotFound: + lexer = lexers.guess_lexer(token.content) + code_toks = lexer.get_tokens(token.content) + + # values to use in _fence_comment function + fence_ctx = _FenceCtx() + # number of the last line with a comment token + last_comment_line_num = 0 + # the token starts with one line of the fence, then the content. +1: 0-base -> 1-base + line_num = token.map[0] + 1 + 1 + + # concatenate comment tokens until either a non-comment token or a blank line or end of token stream + for tok_type, tok_val in code_toks: + if tok_type == pygments.token.Token.Comment.Single: + # when another comment is already being parsed and there's a blank line + if fence_ctx.comment and line_num - last_comment_line_num > 1: + _fence_comment(fence_ctx, md_ctx, content_result) + last_nl = fence_ctx.next_indent.rfind('\n') + fence_ctx.localized += fence_ctx.next_indent[:last_nl + 1] + fence_ctx.indent = fence_ctx.next_indent[last_nl + 1:] + if fence_ctx.comment != '': + fence_ctx.comment += ' ' + if comment_match := utils.SINGLE_COMMENT_PATTERN.match(tok_val): + fence_ctx.comment += comment_match.group(2).strip() + last_comment_line_num = line_num + else: + if fence_ctx.comment: + if tok_val.strip(): + _fence_comment(fence_ctx, md_ctx, content_result) + fence_ctx.indent = fence_ctx.next_indent + tok_val + fence_ctx.next_indent = '' + else: + fence_ctx.next_indent = tok_val + else: + last_nl = tok_val.rfind('\n') + if last_nl != -1: + fence_ctx.localized += fence_ctx.indent + tok_val[:last_nl + 1] + fence_ctx.indent = tok_val[last_nl + 1:] + else: + fence_ctx.indent += tok_val + line_num += tok_val.count('\n') + if fence_ctx.comment: + _fence_comment(fence_ctx, md_ctx, content_result) + return fence_ctx.localized + + +def _front_matter(token: Token, env: EnvType) -> L10NResult: + domain_g: DomainGenerationProtocol = env['domain_generation'] + fm_result = domain_g.render_front_matter(token.content, token.markup) + return fm_result + + +def _link_ref(env: EnvType, md_ctx: _MdCtx, content_result: L10NResult): + refs = env.get('references', {}).items() + if len(refs) == 0: + return + content_result.localized += '\n' + for ref, details in refs: + href = details['href'] + content_result.localized += f'[{ref}]: {href}' + if title := details.get('title', ''): + localized_title = md_ctx.domain_g.l10n_func(title) + if localized_title is not title: + content_result.l10n_count += 1 + content_result.total_count += 1 + content_result.localized += f' "{localized_title}"' + content_result.localized += '\n' + + +class RendererMarkdownL10N: + """ + Implements `RendererProtocol` + """ + __output__ = 'md' + + def __init__(self, mdi: MarkdownIt): + self.rules = { + k: v + for k, v in inspect.getmembers(self, predicate=inspect.ismethod) + if not (k.startswith("render") or k.startswith("_")) + } + self.mdi = mdi + + def render(self, tokens: Sequence[Token], _options: OptionsDict, env: EnvType) -> Tuple[L10NResult, L10NResult]: + """ + :param tokens: list of block tokens to render + :param _options: properties of parser instance + :param env: containing 'domain_generation' an object compatible with `DomainGenerationProtocol` + :return: an `L10NResult` + """ + if tokens[0].type == 'front_matter': + fm_result = _front_matter(tokens[0], env) + tokens = tokens[1:] + else: + fm_result = L10NResult('', 0, 0) + + md_ctx = _MdCtx(env) + content_result = L10NResult('', 0, 0) + + for i, token in enumerate(tokens): + if token.type in self.rules: + r = self.rules[token.type](tokens, i, md_ctx, content_result) + if r == -1: + break + + _link_ref(env, md_ctx, content_result) + + return fm_result, content_result + + @classmethod + def inline(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult): + token = tokens[idx] + content = utils.SPACES_PATTERN.sub(' ', token.content.replace('\n', ' ')) + if content and not utils.SPACES_PATTERN.fullmatch(content): + localized_content = md_ctx.domain_g.l10n_func(content) + else: + localized_content = content + if localized_content is not content: + content_result.l10n_count += 1 + content_result.total_count += 1 + if md_ctx.in_table: + content_result.localized += localized_content + else: + content_result.localized += f'{md_ctx.get_line_indent()}{localized_content}' + + # blockquote + # TODO: blockquote inside list + @classmethod + def blockquote_open(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, _content_result: L10NResult): + token = tokens[idx] + md_ctx.line_indent = f'{md_ctx.get_line_indent()}{token.markup} ' + + @classmethod + def blockquote_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult): + md_ctx.line_indent = md_ctx.line_indent[:-2] + content_result.localized += f'{md_ctx.line_indent}\n' + + # heading + @classmethod + def heading_open(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, _content_result: L10NResult): + token = tokens[idx] + if token.markup not in SETEXT_HEADING_MARKUPS: + md_ctx.indent_1st_line += f'{token.markup} ' + # md_ctx.indent_1st_line_len += 0 + # md_ctx.line_indent += ' ' * 0 + md_ctx.indents.append(0) + else: + md_ctx.setext_heading = token.markup + + @classmethod + def heading_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult): + if md_ctx.setext_heading: + content_result.localized += f'\n{md_ctx.get_line_indent()}{md_ctx.setext_heading}' + md_ctx.setext_heading = '' + else: + md_ctx.indents.pop() + # the added len is 0, so line_indent remains the same + content_result.localized += '\n' + + # thematic break + @classmethod + def hr(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult): + token = tokens[idx] + # always use '_' here to differentiate this from setext headings and bullet list items + content_result.localized += f'{md_ctx.get_line_indent()}{len(token.markup) * "_"}\n' + + # list + # TODO: loose lists? + @classmethod + def list_item_open(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, _content_result: L10NResult): + token = tokens[idx] + markup = f'{token.info}{token.markup}' if token.markup in ORDERED_LIST_MARKUPS else f'{token.markup}' + md_ctx.indent_1st_line += f'{markup} ' + added_len = len(markup) + 1 + md_ctx.indent_1st_line_len += added_len + md_ctx.line_indent += ' ' * added_len + md_ctx.indents.append(added_len) + + @classmethod + def list_item_close(cls, + _tokens: Sequence[Token], + _idx: int, + md_ctx: _MdCtx, + _content_result: L10NResult): + latest_len = md_ctx.indents.pop() + md_ctx.line_indent = md_ctx.line_indent[:-latest_len] + + @classmethod + def bullet_list_close(cls, + tokens: Sequence[Token], + idx: int, + md_ctx: _MdCtx, + content_result: L10NResult): + # add a blank line when next token is not a closing one + if idx < len(tokens) - 1 and tokens[idx + 1].nesting != -1: + content_result.localized += f'{md_ctx.line_indent}\n' + + @classmethod + def ordered_list_close(cls, + tokens: Sequence[Token], + idx: int, + md_ctx: _MdCtx, + content_result: L10NResult): + # add a blank line when next token is not a closing one + if idx < len(tokens) - 1 and tokens[idx + 1].nesting != -1: + content_result.localized += f'{md_ctx.line_indent}\n' + + # paragraph + @classmethod + def paragraph_close(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult): + content_result.localized += '\n' + if idx < len(tokens) - 1: + next_token = tokens[idx + 1] + # add a blank line when next token is a setext heading_open, an indented code block, a paragraph open, + # or a definition list open + if (next_token.type == 'heading_open' and next_token.markup in SETEXT_HEADING_MARKUPS) \ + or next_token.type in {'code_block', 'paragraph_open', 'dl_open'}: + content_result.localized += f'{md_ctx.line_indent}\n' + + # indented code block + @classmethod + def code_block(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult): + token = tokens[idx] + localized_code_block = token.content.replace('\n', f'\n{md_ctx.line_indent} ') + content_result.localized += f'{md_ctx.get_line_indent()} {localized_code_block}\n' + + # fenced code block + @classmethod + def fence(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult): + token = tokens[idx] + localized_fence = _fence(token, md_ctx, content_result) + localized_fence = localized_fence.replace('\n', f'\n{md_ctx.line_indent}') + # a newline is at the end of token.content already, so we only need to append token.markup there + content_result.localized += f'''{md_ctx.get_line_indent()}{token.markup}{token.info} +{md_ctx.line_indent}{localized_fence}{token.markup} +''' + + # html block + @classmethod + def html_block(cls, tokens: Sequence[Token], idx: int, md_ctx: _MdCtx, content_result: L10NResult): + token = tokens[idx] + localized_html = md_ctx.domain_g.l10n_func(token.content) + if localized_html is not token.content: + content_result.l10n_count += 1 + content_result.total_count += 1 + localized_html = localized_html.replace('\n', f'\n{md_ctx.line_indent}') + content_result.localized += f'{md_ctx.get_line_indent()}{localized_html}\n' + + # table + @classmethod + def table_open(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, _content_result: L10NResult): + md_ctx.in_table = True + + @classmethod + def tr_open(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult): + content_result.localized += f'{md_ctx.get_line_indent()}|' + + @classmethod + def th_open(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult): + content_result.localized += ' ' + md_ctx.table_sep += '| --- ' + + @classmethod + def th_close(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult): + content_result.localized += ' |' + + @classmethod + def thead_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult): + md_ctx.table_sep += '|\n' + content_result.localized += f'{md_ctx.line_indent}{md_ctx.table_sep}' + md_ctx.table_sep = '' + + @classmethod + def td_open(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult): + content_result.localized += ' ' + + @classmethod + def td_close(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult): + content_result.localized += ' |' + + @classmethod + def tr_close(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult): + content_result.localized += '\n' + + @classmethod + def table_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult): + content_result.localized += f'{md_ctx.line_indent}\n' + md_ctx.in_table = False + + # definition list + @classmethod + def dd_open(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, _content_result: L10NResult): + md_ctx.indent_1st_line += f': ' + md_ctx.indent_1st_line_len += 2 + md_ctx.line_indent += ' ' * 2 + md_ctx.indents.append(2) + + @classmethod + def dd_close(cls, _tokens: Sequence[Token], _idx: int, md_ctx: _MdCtx, content_result: L10NResult): + latest_len = md_ctx.indents.pop() + md_ctx.line_indent = md_ctx.line_indent[:-latest_len] + content_result.localized += f'{md_ctx.line_indent}\n' + + @classmethod + def dt_close(cls, _tokens: Sequence[Token], _idx: int, _md_ctx: _MdCtx, content_result: L10NResult): + content_result.localized += '\n' diff --git a/mdit_py_i18n/utils.py b/mdit_py_i18n/utils.py new file mode 100644 index 0000000..526b44a --- /dev/null +++ b/mdit_py_i18n/utils.py @@ -0,0 +1,61 @@ +# SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +# SPDX-License-Identifier: LGPL-2.1-or-later + +import re + +from typing import Callable, Protocol, Tuple, List + +SPACES_PATTERN = re.compile(r'\s+') +SINGLE_COMMENT_PATTERN = re.compile('(// *)(.*)') + + +# extraction +class I18NEntryProtocol(Protocol): + msgid: str + occurrences: List[Tuple[str, int]] + comment: str + msgctxt: str + + +class DomainExtractionProtocol(Protocol): + entries: List[I18NEntryProtocol] + + def add_entry(self, path: str, msgid: str, line_num: int, comment: str = '', msgctxt: str = ''): + ... + + def render_front_matter(self, path: str, content: str, markup: str): + ... + + +# generation +class L10NResult: + """Localized content, total number of messages, number of translations. + If there are no messages, rate will be -1 + """ + def __init__(self, localized, total_count: int, l10n_count: int): + self.localized = localized + self.total_count = total_count + self.l10n_count = l10n_count + + def __str__(self): + return f'({self.l10n_count}/{self.total_count})' + + def __add__(self, other: 'L10NResult'): + localized = self.localized + other.localized + total_count = self.total_count + other.total_count + l10n_count = self.l10n_count + other.l10n_count + return L10NResult(localized, total_count, l10n_count) + + @property + def rate(self): + return self.l10n_count / self.total_count if self.total_count > 0 else -1 + + +L10NFunc = Callable[[str], str] + + +class DomainGenerationProtocol(Protocol): + l10n_func: L10NFunc + + def render_front_matter(self, content: str, markup: str): + ... diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 0000000..8c1cca5 --- /dev/null +++ b/poetry.lock @@ -0,0 +1,79 @@ +[[package]] +name = "markdown-it-py" +version = "3.0.0" +description = "Python port of markdown-it. Markdown parsing, done right!" +category = "main" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +mdit-py-plugins = {version = "*", optional = true, markers = "extra == \"plugins\""} +mdurl = ">=0.1,<1.0" + +[package.extras] +benchmarking = ["psutil", "pytest", "pytest-benchmark"] +code_style = ["pre-commit (>=3.0,<4.0)"] +compare = ["commonmark (>=0.9,<1.0)", "markdown (>=3.4,<4.0)", "mistletoe (>=1.0,<2.0)", "mistune (>=2.0,<3.0)", "panflute (>=2.3,<3.0)"] +linkify = ["linkify-it-py (>=1,<3)"] +plugins = ["mdit-py-plugins"] +profiling = ["gprof2dot"] +rtd = ["mdit-py-plugins", "myst-parser", "pyyaml", "sphinx", "sphinx-copybutton", "sphinx-design", "sphinx-book-theme", "jupyter-sphinx"] +testing = ["coverage", "pytest", "pytest-cov", "pytest-regressions"] + +[[package]] +name = "mdit-py-plugins" +version = "0.4.0" +description = "Collection of plugins for markdown-it-py" +category = "main" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +markdown-it-py = ">=1.0.0,<4.0.0" + +[package.extras] +code_style = ["pre-commit"] +rtd = ["myst-parser", "sphinx-book-theme"] +testing = ["coverage", "pytest", "pytest-cov", "pytest-regressions"] + +[[package]] +name = "mdurl" +version = "0.1.2" +description = "Markdown URL utilities" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "pygments" +version = "2.16.1" +description = "Pygments is a syntax highlighting package written in Python." +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +plugins = ["importlib-metadata"] + +[metadata] +lock-version = "1.1" +python-versions = "^3.8" +content-hash = "21bcccfcae8d8c7459dfd50c4dbe958d9cc163cfeba7145ed9d755faf1180924" + +[metadata.files] +markdown-it-py = [ + {file = "markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb"}, + {file = "markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1"}, +] +mdit-py-plugins = [ + {file = "mdit_py_plugins-0.4.0-py3-none-any.whl", hash = "sha256:b51b3bb70691f57f974e257e367107857a93b36f322a9e6d44ca5bf28ec2def9"}, + {file = "mdit_py_plugins-0.4.0.tar.gz", hash = "sha256:d8ab27e9aed6c38aa716819fedfde15ca275715955f8a185a8e1cf90fb1d2c1b"}, +] +mdurl = [ + {file = "mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8"}, + {file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"}, +] +pygments = [ + {file = "Pygments-2.16.1-py3-none-any.whl", hash = "sha256:13fc09fa63bc8d8671a6d247e1eb303c4b343eaee81d861f3404db2935653692"}, + {file = "Pygments-2.16.1.tar.gz", hash = "sha256:1daff0494820c69bc8941e407aa20f577374ee88364ee10a98fdbe0aece96e29"}, +] diff --git a/poetry.lock.license b/poetry.lock.license new file mode 100644 index 0000000..15dd17b --- /dev/null +++ b/poetry.lock.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +SPDX-License-Identifier: CC0-1.0 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..50c8f3d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +# SPDX-License-Identifier: CC0-1.0 + +[tool.poetry] +name = "mdit-py-i18n" +version = "0.1.0" +description = "Markdown i18n and l10n using markdown-it-py" +authors = ["Phu Hung Nguyen "] +license = "LGPL-2.1-or-later" +readme = "README.md" +repository = "https://github.com/phunh/mdit-py-i18n" +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Internationalization", + "Programming Language :: Python", + "Programming Language :: Python :: 3" +] +packages = [{include = "mdit_py_i18n"}] + +[tool.poetry.dependencies] +python = "^3.8" +markdown-it-py = {extras = ["plugins"], version = "^3.0.0"} +Pygments = "^2.16.1" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/resources/__init__.py b/tests/resources/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/resources/blockquotes.md b/tests/resources/blockquotes.md new file mode 100644 index 0000000..1067ed9 --- /dev/null +++ b/tests/resources/blockquotes.md @@ -0,0 +1,91 @@ +--- +authors: +- SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +SPDX-License-Identifier: CC0-1.0 +--- +> simple blockquote + +> consecutive second blockquote + +> blockquote first line +> and second line with a marker + +> blockquote first line +and second line without a marker + +> blockquote first paragraph +> +> and second paragraph + +> blockquote +> nested coming +> +> > second level +> still second level but another line +> +> back to first level +> +> > > third level +> +> 1. ordered list item 1 +> 2. ordered list item 2 +> in a new line +> +> - bullet list item 1 +> - bullet list item 2 +> - bullet list item 3 +> +> 1. ordered list item 1 containing bullet list +> - bullet list item 1 inside ordered list item 1 +> - bullet list item 2 inside ordered list item 1 +> 2. ordered list item 2 after item 1 containing bullet list +> +> 1) # atx heading in list in blockquote +> +> # atx heading level 1 +> +> #### atx heading level 4 +> +> setext heading level 1 +> = +> +> setext heading level 2 +> - +> +> not a paragraph +> prepended to setext heading level 1 +> = +> +> paragraph separated from +> +> setext heading level 2 +> - +> +> paragraph before a thematic break +> +> --- +> paragraph after a thematic break +> +> int main(): +> return 0 +> +> ```python +> def main(): +> return None +> ``` +> +>
+>

html block

+>
+> +> | head | head2 | +> |------|-------| +> | body | body2 | +> +> term number 1 +> : details number 1 +> +> term number 2 +> : details number 2 +> +> last paragraph \ No newline at end of file diff --git a/tests/resources/definition_list.md b/tests/resources/definition_list.md new file mode 100644 index 0000000..2736dbe --- /dev/null +++ b/tests/resources/definition_list.md @@ -0,0 +1,39 @@ +--- +authors: +- SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +SPDX-License-Identifier: CC0-1.0 +--- +term number 1 +: details number 1 + +term number 2 +: details number 2 +onto the next line, without indentation + +term number 3 +: details number 3 + onto the next line, with indentation + +term with indented code block +: details with indented code block + + before the code block + + def main: + pass + after the code block + +term with html block +: details with html block +
+

html block

+
+
+ +complex term +: complex details + > 1. list inside blockquote + + 1. --- + 2. # heading inside blockquote inside list item 2 + paragraph after heading \ No newline at end of file diff --git a/tests/resources/lists.md b/tests/resources/lists.md new file mode 100644 index 0000000..26a59bc --- /dev/null +++ b/tests/resources/lists.md @@ -0,0 +1,80 @@ +--- +authors: +- SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +SPDX-License-Identifier: CC0-1.0 +--- +* bullet 1 +* bullet 2 +bullet 2 second line +* bullet 3 + +1. ordered 1 +2. ordered 2 +3. ordered 3 +4. ordered 4 + +* bullet 1 + * nested bullet 1 + * nested nested bullet 1 + * nested nested bullet 2 + * nested bullet 2 +* bullet 2 + +1) ordered 1 + 1) nested ordered 1 + 2) nested ordered 2 + 1) nested nested ordered 1 + 3) nested ordered 3 +2) ordered 2 + 1) nested 2.1 + 2) nested 2.2 + +1. mixed list + - bullet inside 1 + - bullet 2 inside 1 + 1. ordered inside bullet 2 inside 1 +2. second item + +1) ordered 1 with bullet list + + bullet 1 inside 1 + + bullet 2 inside 1 + +1) ordered 2 after a blank line + +1. 1. list right at beginning of an item +2. second item + +1) list with blockquote + > inside blockquote + > 1. list inside blockquote + > 2. another list item + +1. list with code + + int main(): + return 0 +2. fence in item + + ```python + def main(): + return None + ``` + +3. # can an atx heading be here? + --- + now a table + + | head | head2 | + |------|-------| + | body | body2 | +4. two paragraphs + + in one list item +5. term number 2 + : details number 2 + onto the next line, without indentation +6. can a setext heading be here? + - + [foo]: /url "title" + + this is a reference [foo]. and after the reference. \ No newline at end of file diff --git a/tests/resources/renderer.md b/tests/resources/renderer.md new file mode 100644 index 0000000..2e88f16 --- /dev/null +++ b/tests/resources/renderer.md @@ -0,0 +1,58 @@ +--- +authors: +- SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +SPDX-License-Identifier: CC0-1.0 +--- +# atx heading + +setext heading +== + +--- + +paragraph here + +and more + + int main() { + int a = 1; + return(a) + } + +```c +#include "header.h" +// comment 1 +#include "header2.h" +// comment 2 +int main() { + +// Comment spreaded +// on 2 lines, not indented + + // Comment spreaded + // on 2 lines, indented + + + + // A super long long comment + // on multiple lines + // trying to make it into 3 lines + // now the fourth one here + return 0; + +// Last comment +} +``` + +
+

html block

+
+
+ +[foo]: /url "title" + +this is a reference [foo]. and after the reference. + +| head | head2 | +|------|-------| +| body | body2 | \ No newline at end of file diff --git a/tests/test_renderer_i18n.py b/tests/test_renderer_i18n.py new file mode 100644 index 0000000..3f87db4 --- /dev/null +++ b/tests/test_renderer_i18n.py @@ -0,0 +1,51 @@ +# SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +# SPDX-License-Identifier: LGPL-2.1-or-later + +import importlib.resources as pkg_resources +import unittest +from dataclasses import dataclass, field +from typing import List, Tuple + +from markdown_it import MarkdownIt +from mdit_py_plugins.deflist import deflist_plugin +from mdit_py_plugins.front_matter import front_matter_plugin + +from mdit_py_i18n.renderer_i18n import RendererMarkdownI18N + + +@dataclass +class I18NEntry: + msgid: str + occurrences: List[Tuple[str, int]] = field(default_factory=list) + comment: str = '' + msgctxt: str = '' + + +class DomainExtraction: + def __init__(self): + self.entries: List[I18NEntry] = [] + + def add_entry(self, path: str, msgid: str, line_num: int, comment: str = '', msgctxt: str = ''): + self.entries.append(I18NEntry(msgid, [(path, line_num)], comment, msgctxt)) + + +class RendererMarkdownI18NTestCase(unittest.TestCase): + mdi = MarkdownIt(renderer_cls=RendererMarkdownI18N).use(front_matter_plugin)\ + .enable('table').use(deflist_plugin) + + def test_renderer(self): + path = 'renderer.md' + domain_e = DomainExtraction() + with pkg_resources.open_text('tests.resources', path) as f_obj: + env = { + 'path': path, + 'domain_extraction': domain_e + } + tokens = self.mdi.parse(f_obj.read(), env) + # skip front matter + self.mdi.renderer.render(tokens[1:], self.mdi.options, env) + self.assertEqual(17, len(domain_e.entries)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_renderer_l10n.py b/tests/test_renderer_l10n.py new file mode 100644 index 0000000..c3f7845 --- /dev/null +++ b/tests/test_renderer_l10n.py @@ -0,0 +1,55 @@ +# SPDX-FileCopyrightText: 2023 Phu Hung Nguyen +# SPDX-License-Identifier: LGPL-2.1-or-later + +import importlib.resources as pkg_resources +import unittest + +from markdown_it import MarkdownIt +from mdit_py_plugins.deflist import deflist_plugin +from mdit_py_plugins.front_matter import front_matter_plugin + +from mdit_py_i18n.renderer_l10n import RendererMarkdownL10N + + +class DomainGeneration: + def __init__(self, l10n_func): + self.l10n_func = l10n_func + + +class RendererMarkdownL10NTestCase(unittest.TestCase): + mdi = MarkdownIt(renderer_cls=RendererMarkdownL10N).use(front_matter_plugin)\ + .enable('table').use(deflist_plugin) + + def _prep_test(self, f_obj): + env = { + 'domain_generation': DomainGeneration(lambda s: s) + } + # skip front matter + tokens = self.mdi.parse(f_obj.read(), env)[1:] + _, content_result = self.mdi.renderer.render(tokens, self.mdi.options, env) + localized_tokens = self.mdi.parse(content_result.localized) + return tokens, content_result, localized_tokens + + def test_blockquotes(self): + with pkg_resources.open_text('tests.resources', 'blockquotes.md') as f_obj: + tokens, content_result, localized_tokens = self._prep_test(f_obj) + self.assertEqual([token.type for token in tokens], [token.type for token in localized_tokens]) + + def test_lists(self): + with pkg_resources.open_text('tests.resources', 'lists.md') as f_obj: + tokens, content_result, localized_tokens = self._prep_test(f_obj) + self.assertEqual([token.type for token in tokens], [token.type for token in localized_tokens]) + + def test_definition_list(self): + with pkg_resources.open_text('tests.resources', 'definition_list.md') as f_obj: + tokens, content_result, localized_tokens = self._prep_test(f_obj) + self.assertEqual([token.type for token in tokens], [token.type for token in localized_tokens]) + + def test_others(self): + with pkg_resources.open_text('tests.resources', 'renderer.md') as f_obj: + tokens, content_result, localized_tokens = self._prep_test(f_obj) + self.assertEqual([token.type for token in tokens], [token.type for token in localized_tokens]) + + +if __name__ == '__main__': + unittest.main()