From 36d22d82aa202bb199967e9512281e9a53db42c9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 21:33:14 +0200 Subject: Adding upstream version 115.7.0esr. Signed-off-by: Daniel Baumann --- .../yamllint/yamllint-1.23.0.dist-info/LICENSE | 674 +++++++++++++++++++++ .../yamllint/yamllint-1.23.0.dist-info/METADATA | 34 ++ .../yamllint/yamllint-1.23.0.dist-info/RECORD | 37 ++ .../yamllint/yamllint-1.23.0.dist-info/WHEEL | 6 + .../yamllint-1.23.0.dist-info/entry_points.txt | 3 + .../yamllint-1.23.0.dist-info/top_level.txt | 1 + third_party/python/yamllint/yamllint/__init__.py | 31 + third_party/python/yamllint/yamllint/__main__.py | 4 + third_party/python/yamllint/yamllint/cli.py | 207 +++++++ .../python/yamllint/yamllint/conf/default.yaml | 33 + .../python/yamllint/yamllint/conf/relaxed.yaml | 29 + third_party/python/yamllint/yamllint/config.py | 205 +++++++ third_party/python/yamllint/yamllint/linter.py | 240 ++++++++ third_party/python/yamllint/yamllint/parser.py | 161 +++++ .../python/yamllint/yamllint/rules/__init__.py | 70 +++ .../python/yamllint/yamllint/rules/braces.py | 143 +++++ .../python/yamllint/yamllint/rules/brackets.py | 145 +++++ .../python/yamllint/yamllint/rules/colons.py | 105 ++++ .../python/yamllint/yamllint/rules/commas.py | 131 ++++ .../python/yamllint/yamllint/rules/comments.py | 104 ++++ .../yamllint/rules/comments_indentation.py | 139 +++++ .../python/yamllint/yamllint/rules/common.py | 89 +++ .../python/yamllint/yamllint/rules/document_end.py | 107 ++++ .../yamllint/yamllint/rules/document_start.py | 93 +++ .../python/yamllint/yamllint/rules/empty_lines.py | 108 ++++ .../python/yamllint/yamllint/rules/empty_values.py | 96 +++ .../python/yamllint/yamllint/rules/hyphens.py | 88 +++ .../python/yamllint/yamllint/rules/indentation.py | 575 ++++++++++++++++++ .../yamllint/yamllint/rules/key_duplicates.py | 100 +++ .../python/yamllint/yamllint/rules/key_ordering.py | 109 ++++ .../python/yamllint/yamllint/rules/line_length.py | 149 +++++ .../yamllint/rules/new_line_at_end_of_file.py | 37 ++ .../python/yamllint/yamllint/rules/new_lines.py | 46 ++ .../python/yamllint/yamllint/rules/octal_values.py | 95 +++ .../yamllint/yamllint/rules/quoted_strings.py | 230 +++++++ .../yamllint/yamllint/rules/trailing_spaces.py | 62 ++ .../python/yamllint/yamllint/rules/truthy.py | 149 +++++ 37 files changed, 4635 insertions(+) create mode 100644 third_party/python/yamllint/yamllint-1.23.0.dist-info/LICENSE create mode 100644 third_party/python/yamllint/yamllint-1.23.0.dist-info/METADATA create mode 100644 third_party/python/yamllint/yamllint-1.23.0.dist-info/RECORD create mode 100644 third_party/python/yamllint/yamllint-1.23.0.dist-info/WHEEL create mode 100644 third_party/python/yamllint/yamllint-1.23.0.dist-info/entry_points.txt create mode 100644 third_party/python/yamllint/yamllint-1.23.0.dist-info/top_level.txt create mode 100644 third_party/python/yamllint/yamllint/__init__.py create mode 100644 third_party/python/yamllint/yamllint/__main__.py create mode 100644 third_party/python/yamllint/yamllint/cli.py create mode 100644 third_party/python/yamllint/yamllint/conf/default.yaml create mode 100644 third_party/python/yamllint/yamllint/conf/relaxed.yaml create mode 100644 third_party/python/yamllint/yamllint/config.py create mode 100644 third_party/python/yamllint/yamllint/linter.py create mode 100644 third_party/python/yamllint/yamllint/parser.py create mode 100644 third_party/python/yamllint/yamllint/rules/__init__.py create mode 100644 third_party/python/yamllint/yamllint/rules/braces.py create mode 100644 third_party/python/yamllint/yamllint/rules/brackets.py create mode 100644 third_party/python/yamllint/yamllint/rules/colons.py create mode 100644 third_party/python/yamllint/yamllint/rules/commas.py create mode 100644 third_party/python/yamllint/yamllint/rules/comments.py create mode 100644 third_party/python/yamllint/yamllint/rules/comments_indentation.py create mode 100644 third_party/python/yamllint/yamllint/rules/common.py create mode 100644 third_party/python/yamllint/yamllint/rules/document_end.py create mode 100644 third_party/python/yamllint/yamllint/rules/document_start.py create mode 100644 third_party/python/yamllint/yamllint/rules/empty_lines.py create mode 100644 third_party/python/yamllint/yamllint/rules/empty_values.py create mode 100644 third_party/python/yamllint/yamllint/rules/hyphens.py create mode 100644 third_party/python/yamllint/yamllint/rules/indentation.py create mode 100644 third_party/python/yamllint/yamllint/rules/key_duplicates.py create mode 100644 third_party/python/yamllint/yamllint/rules/key_ordering.py create mode 100644 third_party/python/yamllint/yamllint/rules/line_length.py create mode 100644 third_party/python/yamllint/yamllint/rules/new_line_at_end_of_file.py create mode 100644 third_party/python/yamllint/yamllint/rules/new_lines.py create mode 100644 third_party/python/yamllint/yamllint/rules/octal_values.py create mode 100644 third_party/python/yamllint/yamllint/rules/quoted_strings.py create mode 100644 third_party/python/yamllint/yamllint/rules/trailing_spaces.py create mode 100644 third_party/python/yamllint/yamllint/rules/truthy.py (limited to 'third_party/python/yamllint') diff --git a/third_party/python/yamllint/yamllint-1.23.0.dist-info/LICENSE b/third_party/python/yamllint/yamllint-1.23.0.dist-info/LICENSE new file mode 100644 index 0000000000..94a9ed024d --- /dev/null +++ b/third_party/python/yamllint/yamllint-1.23.0.dist-info/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/third_party/python/yamllint/yamllint-1.23.0.dist-info/METADATA b/third_party/python/yamllint/yamllint-1.23.0.dist-info/METADATA new file mode 100644 index 0000000000..f97b581a3d --- /dev/null +++ b/third_party/python/yamllint/yamllint-1.23.0.dist-info/METADATA @@ -0,0 +1,34 @@ +Metadata-Version: 2.1 +Name: yamllint +Version: 1.23.0 +Summary: A linter for YAML files. +Home-page: https://github.com/adrienverge/yamllint +Author: Adrien Vergé +License: GPLv3 +Keywords: yaml,lint,linter,syntax,checker +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Debuggers +Classifier: Topic :: Software Development :: Quality Assurance +Classifier: Topic :: Software Development :: Testing +Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* +Requires-Dist: pathspec (>=0.5.3) +Requires-Dist: pyyaml + +A linter for YAML files. + +yamllint does not only check for syntax validity, but for weirdnesses like key +repetition and cosmetic problems such as lines length, trailing spaces, +indentation, etc. + diff --git a/third_party/python/yamllint/yamllint-1.23.0.dist-info/RECORD b/third_party/python/yamllint/yamllint-1.23.0.dist-info/RECORD new file mode 100644 index 0000000000..57b2adaa42 --- /dev/null +++ b/third_party/python/yamllint/yamllint-1.23.0.dist-info/RECORD @@ -0,0 +1,37 @@ +yamllint/__init__.py,sha256=09UdMyFnq1ObJn5Q-OyN0bVxnqlNdeTOGCH0DBALZKM,1098 +yamllint/__main__.py,sha256=yUeYsN2w7fyIjcnleh2ow0u_hG6YO1BfnumvApBDWXQ,67 +yamllint/cli.py,sha256=PUphAVxTsXCKHMMvyUsuhwiELnDqVMRWX7xnWMZ5adw,7880 +yamllint/config.py,sha256=-Y4QnDKAcZD6DpRhvhSo89t9IGs_2ZAkJrP_c8ZPrVQ,7877 +yamllint/linter.py,sha256=yDkPv41mMmbdCBNyvblYs7Ds4P1F_jDAgy0LzeyyUMU,8773 +yamllint/parser.py,sha256=3MwMASIm3v6z5zKwlQFPJtt7rv4i4zD6_KgHABP3_oE,5191 +yamllint/conf/default.yaml,sha256=wsK6rYJ2A1sv-0ln3Ckvr8Tgbj4asvk42vD4OZQcEfc,587 +yamllint/conf/relaxed.yaml,sha256=Bz743etRSwggNRc8hMgxMmyr-5JazJrCPv3KNhjOu28,505 +yamllint/rules/__init__.py,sha256=b-32xKjsRiUqMaLAguHTBtxjV2zCEMwa-0hfC4dIcI0,1924 +yamllint/rules/braces.py,sha256=BLjn8qlo_3BCAGqi19qJUt2eVd-TKoNrqzV1R_d0Gfc,4542 +yamllint/rules/brackets.py,sha256=IwsOdigK2pPPDyA3gup8LhgHdaUIfeP8P4ApO0PuLU4,4583 +yamllint/rules/colons.py,sha256=DtN1lRBMq58r8M1aeAcU4TAhNx7qNCsa6isVpk_ukNM,2826 +yamllint/rules/commas.py,sha256=VBIO52n0DsFrdw_v0_F76tLSrQnwSbARsSAnfUKCCyo,3737 +yamllint/rules/comments.py,sha256=WfTYRnI8nZS0je1zlVzkhC-rtXR23krvUzS0cEQI_BI,3381 +yamllint/rules/comments_indentation.py,sha256=pCS5gSOZWc4wGHr7LlnwcReuSWax4WV0Ec_0G1RvoiI,3425 +yamllint/rules/common.py,sha256=_572eFYdjdTCMrzVGpuRDTi42OazsBYezcwlFMdsDPg,3226 +yamllint/rules/document_end.py,sha256=9rMdNmLDacI3sQopFYzRuGrc6Hj68GAkX5s8a5X1UWg,2686 +yamllint/rules/document_start.py,sha256=LJFunt4mqC_Cruq316hymg9uTKorfoOA2klHqdJiKH8,2437 +yamllint/rules/empty_lines.py,sha256=C5JoI-jtTDkApiBpcT_AeVt97xfR2jlyvkTfvFBpFqA,3259 +yamllint/rules/empty_values.py,sha256=iXuIjQkUyEQ_9kiXAbYjA32BsK8oxMUQgGo1xrPIVqg,2601 +yamllint/rules/hyphens.py,sha256=OfNUNWyGiABHnZwbqDtQTEBihmeJBmVEQgg2DVIllFo,1990 +yamllint/rules/indentation.py,sha256=82DOfCNnxBxFI0TX_6VF05HxUX0CEw6nRxcnhCprFfs,19067 +yamllint/rules/key_duplicates.py,sha256=dEYrBcG68MGG7iC6OBGsA9ZPbIX2rTYt-85Yf2Z2BJU,2890 +yamllint/rules/key_ordering.py,sha256=wbATImHwoojXPcrmG8RaGrvyPLmM7Dvvlz7U14uCrxs,3083 +yamllint/rules/line_length.py,sha256=FwI_8ShkiKzfjICo4RqG7WSAJKM87op5O-MDncPOvDI,4809 +yamllint/rules/new_line_at_end_of_file.py,sha256=X0T0jPojEkxTfDQiQrWVydXn_jPj0srd9hFOLm5t9wA,1357 +yamllint/rules/new_lines.py,sha256=bZCSz9PUVIn__PkgLx1R-iWUnXyfrQ5ZfXDh9qQ7WEM,1633 +yamllint/rules/octal_values.py,sha256=cCbDT4U0qCE0_wWoJUFgnvOxv1Ydv2bVDzTH-i0aK2Q,2792 +yamllint/rules/quoted_strings.py,sha256=bUIkpR-8i5Of18RrSvCi5lmffMiFchwNnkNkHQe3wqs,7468 +yamllint/rules/trailing_spaces.py,sha256=GH8RTvR-FXA0GbtRkFWymp_LzK2mJuROhcDoJcvQ4ns,1634 +yamllint/rules/truthy.py,sha256=K_or0_h7U2ymVe0_G_5IZ2GgMJhfcCklh4ojvABN4Tw,4011 +yamllint-1.23.0.dist-info/LICENSE,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147 +yamllint-1.23.0.dist-info/METADATA,sha256=I6VrDjA7fBGgMpppaPTQnfiZwWnE9zVhN9GIoDJuBu8,1318 +yamllint-1.23.0.dist-info/WHEEL,sha256=HX-v9-noUkyUoxyZ1PMSuS7auUxDAR4VBdoYLqD0xws,110 +yamllint-1.23.0.dist-info/entry_points.txt,sha256=_aTkgNklEhR_lTZHrYseFHam-CSHZSqnhYtlYFb-72k,47 +yamllint-1.23.0.dist-info/top_level.txt,sha256=ivPsPeZUDHOuLbd603ZxKClOQ1bATyMYNx3GfHQmt4g,9 +yamllint-1.23.0.dist-info/RECORD,, diff --git a/third_party/python/yamllint/yamllint-1.23.0.dist-info/WHEEL b/third_party/python/yamllint/yamllint-1.23.0.dist-info/WHEEL new file mode 100644 index 0000000000..c8240f03e8 --- /dev/null +++ b/third_party/python/yamllint/yamllint-1.23.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.33.1) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/third_party/python/yamllint/yamllint-1.23.0.dist-info/entry_points.txt b/third_party/python/yamllint/yamllint-1.23.0.dist-info/entry_points.txt new file mode 100644 index 0000000000..a1b443ba38 --- /dev/null +++ b/third_party/python/yamllint/yamllint-1.23.0.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +yamllint = yamllint.cli:run + diff --git a/third_party/python/yamllint/yamllint-1.23.0.dist-info/top_level.txt b/third_party/python/yamllint/yamllint-1.23.0.dist-info/top_level.txt new file mode 100644 index 0000000000..b2c729ca4d --- /dev/null +++ b/third_party/python/yamllint/yamllint-1.23.0.dist-info/top_level.txt @@ -0,0 +1 @@ +yamllint diff --git a/third_party/python/yamllint/yamllint/__init__.py b/third_party/python/yamllint/yamllint/__init__.py new file mode 100644 index 0000000000..b78fe9c29e --- /dev/null +++ b/third_party/python/yamllint/yamllint/__init__.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +"""A linter for YAML files. + +yamllint does not only check for syntax validity, but for weirdnesses like key +repetition and cosmetic problems such as lines length, trailing spaces, +indentation, etc.""" + + +APP_NAME = 'yamllint' +APP_VERSION = '1.23.0' +APP_DESCRIPTION = __doc__ + +__author__ = u'Adrien Vergé' +__copyright__ = u'Copyright 2016, Adrien Vergé' +__license__ = 'GPLv3' +__version__ = APP_VERSION diff --git a/third_party/python/yamllint/yamllint/__main__.py b/third_party/python/yamllint/yamllint/__main__.py new file mode 100644 index 0000000000..bc16534ec7 --- /dev/null +++ b/third_party/python/yamllint/yamllint/__main__.py @@ -0,0 +1,4 @@ +from yamllint.cli import run + +if __name__ == '__main__': + run() diff --git a/third_party/python/yamllint/yamllint/cli.py b/third_party/python/yamllint/yamllint/cli.py new file mode 100644 index 0000000000..e99fd2ca84 --- /dev/null +++ b/third_party/python/yamllint/yamllint/cli.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import print_function + +import argparse +import io +import os +import platform +import sys + +from yamllint import APP_DESCRIPTION, APP_NAME, APP_VERSION +from yamllint import linter +from yamllint.config import YamlLintConfig, YamlLintConfigError +from yamllint.linter import PROBLEM_LEVELS + + +def find_files_recursively(items, conf): + for item in items: + if os.path.isdir(item): + for root, dirnames, filenames in os.walk(item): + for f in filenames: + filepath = os.path.join(root, f) + if conf.is_yaml_file(filepath): + yield filepath + else: + yield item + + +def supports_color(): + supported_platform = not (platform.system() == 'Windows' and not + ('ANSICON' in os.environ or + ('TERM' in os.environ and + os.environ['TERM'] == 'ANSI'))) + return (supported_platform and + hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()) + + +class Format(object): + @staticmethod + def parsable(problem, filename): + return ('%(file)s:%(line)s:%(column)s: [%(level)s] %(message)s' % + {'file': filename, + 'line': problem.line, + 'column': problem.column, + 'level': problem.level, + 'message': problem.message}) + + @staticmethod + def standard(problem, filename): + line = ' %d:%d' % (problem.line, problem.column) + line += max(12 - len(line), 0) * ' ' + line += problem.level + line += max(21 - len(line), 0) * ' ' + line += problem.desc + if problem.rule: + line += ' (%s)' % problem.rule + return line + + @staticmethod + def standard_color(problem, filename): + line = ' \033[2m%d:%d\033[0m' % (problem.line, problem.column) + line += max(20 - len(line), 0) * ' ' + if problem.level == 'warning': + line += '\033[33m%s\033[0m' % problem.level + else: + line += '\033[31m%s\033[0m' % problem.level + line += max(38 - len(line), 0) * ' ' + line += problem.desc + if problem.rule: + line += ' \033[2m(%s)\033[0m' % problem.rule + return line + + +def show_problems(problems, file, args_format, no_warn): + max_level = 0 + first = True + + for problem in problems: + max_level = max(max_level, PROBLEM_LEVELS[problem.level]) + if no_warn and (problem.level != 'error'): + continue + if args_format == 'parsable': + print(Format.parsable(problem, file)) + elif args_format == 'colored' or \ + (args_format == 'auto' and supports_color()): + if first: + print('\033[4m%s\033[0m' % file) + first = False + print(Format.standard_color(problem, file)) + else: + if first: + print(file) + first = False + print(Format.standard(problem, file)) + + if not first and args_format != 'parsable': + print('') + + return max_level + + +def run(argv=None): + parser = argparse.ArgumentParser(prog=APP_NAME, + description=APP_DESCRIPTION) + files_group = parser.add_mutually_exclusive_group(required=True) + files_group.add_argument('files', metavar='FILE_OR_DIR', nargs='*', + default=(), + help='files to check') + files_group.add_argument('-', action='store_true', dest='stdin', + help='read from standard input') + config_group = parser.add_mutually_exclusive_group() + config_group.add_argument('-c', '--config-file', dest='config_file', + action='store', + help='path to a custom configuration') + config_group.add_argument('-d', '--config-data', dest='config_data', + action='store', + help='custom configuration (as YAML source)') + parser.add_argument('-f', '--format', + choices=('parsable', 'standard', 'colored', 'auto'), + default='auto', help='format for parsing output') + parser.add_argument('-s', '--strict', + action='store_true', + help='return non-zero exit code on warnings ' + 'as well as errors') + parser.add_argument('--no-warnings', + action='store_true', + help='output only error level problems') + parser.add_argument('-v', '--version', action='version', + version='{} {}'.format(APP_NAME, APP_VERSION)) + + args = parser.parse_args(argv) + + # User-global config is supposed to be in ~/.config/yamllint/config + if 'XDG_CONFIG_HOME' in os.environ: + user_global_config = os.path.join( + os.environ['XDG_CONFIG_HOME'], 'yamllint', 'config') + else: + user_global_config = os.path.expanduser('~/.config/yamllint/config') + + try: + if args.config_data is not None: + if args.config_data != '' and ':' not in args.config_data: + args.config_data = 'extends: ' + args.config_data + conf = YamlLintConfig(content=args.config_data) + elif args.config_file is not None: + conf = YamlLintConfig(file=args.config_file) + elif os.path.isfile('.yamllint'): + conf = YamlLintConfig(file='.yamllint') + elif os.path.isfile('.yamllint.yaml'): + conf = YamlLintConfig(file='.yamllint.yaml') + elif os.path.isfile('.yamllint.yml'): + conf = YamlLintConfig(file='.yamllint.yml') + elif os.path.isfile(user_global_config): + conf = YamlLintConfig(file=user_global_config) + else: + conf = YamlLintConfig('extends: default') + except YamlLintConfigError as e: + print(e, file=sys.stderr) + sys.exit(-1) + + max_level = 0 + + for file in find_files_recursively(args.files, conf): + filepath = file[2:] if file.startswith('./') else file + try: + with io.open(file, newline='') as f: + problems = linter.run(f, conf, filepath) + except EnvironmentError as e: + print(e, file=sys.stderr) + sys.exit(-1) + prob_level = show_problems(problems, file, args_format=args.format, + no_warn=args.no_warnings) + max_level = max(max_level, prob_level) + + # read yaml from stdin + if args.stdin: + try: + problems = linter.run(sys.stdin, conf, '') + except EnvironmentError as e: + print(e, file=sys.stderr) + sys.exit(-1) + prob_level = show_problems(problems, 'stdin', args_format=args.format, + no_warn=args.no_warnings) + max_level = max(max_level, prob_level) + + if max_level == PROBLEM_LEVELS['error']: + return_code = 1 + elif max_level == PROBLEM_LEVELS['warning']: + return_code = 2 if args.strict else 0 + else: + return_code = 0 + + sys.exit(return_code) diff --git a/third_party/python/yamllint/yamllint/conf/default.yaml b/third_party/python/yamllint/yamllint/conf/default.yaml new file mode 100644 index 0000000000..0720dede32 --- /dev/null +++ b/third_party/python/yamllint/yamllint/conf/default.yaml @@ -0,0 +1,33 @@ +--- + +yaml-files: + - '*.yaml' + - '*.yml' + - '.yamllint' + +rules: + braces: enable + brackets: enable + colons: enable + commas: enable + comments: + level: warning + comments-indentation: + level: warning + document-end: disable + document-start: + level: warning + empty-lines: enable + empty-values: disable + hyphens: enable + indentation: enable + key-duplicates: enable + key-ordering: disable + line-length: enable + new-line-at-end-of-file: enable + new-lines: enable + octal-values: disable + quoted-strings: disable + trailing-spaces: enable + truthy: + level: warning diff --git a/third_party/python/yamllint/yamllint/conf/relaxed.yaml b/third_party/python/yamllint/yamllint/conf/relaxed.yaml new file mode 100644 index 0000000000..83f5340c7f --- /dev/null +++ b/third_party/python/yamllint/yamllint/conf/relaxed.yaml @@ -0,0 +1,29 @@ +--- + +extends: default + +rules: + braces: + level: warning + max-spaces-inside: 1 + brackets: + level: warning + max-spaces-inside: 1 + colons: + level: warning + commas: + level: warning + comments: disable + comments-indentation: disable + document-start: disable + empty-lines: + level: warning + hyphens: + level: warning + indentation: + level: warning + indent-sequences: consistent + line-length: + level: warning + allow-non-breakable-inline-mappings: true + truthy: disable diff --git a/third_party/python/yamllint/yamllint/config.py b/third_party/python/yamllint/yamllint/config.py new file mode 100644 index 0000000000..a955d8e62b --- /dev/null +++ b/third_party/python/yamllint/yamllint/config.py @@ -0,0 +1,205 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import os.path + +import pathspec +import yaml + +import yamllint.rules + + +class YamlLintConfigError(Exception): + pass + + +class YamlLintConfig(object): + def __init__(self, content=None, file=None): + assert (content is None) ^ (file is None) + + self.ignore = None + + self.yaml_files = pathspec.PathSpec.from_lines( + 'gitwildmatch', ['*.yaml', '*.yml', '.yamllint']) + + if file is not None: + with open(file) as f: + content = f.read() + + self.parse(content) + self.validate() + + def is_file_ignored(self, filepath): + return self.ignore and self.ignore.match_file(filepath) + + def is_yaml_file(self, filepath): + return self.yaml_files.match_file(filepath) + + def enabled_rules(self, filepath): + return [yamllint.rules.get(id) for id, val in self.rules.items() + if val is not False and ( + filepath is None or 'ignore' not in val or + not val['ignore'].match_file(filepath))] + + def extend(self, base_config): + assert isinstance(base_config, YamlLintConfig) + + for rule in self.rules: + if (isinstance(self.rules[rule], dict) and + rule in base_config.rules and + base_config.rules[rule] is not False): + base_config.rules[rule].update(self.rules[rule]) + else: + base_config.rules[rule] = self.rules[rule] + + self.rules = base_config.rules + + if base_config.ignore is not None: + self.ignore = base_config.ignore + + def parse(self, raw_content): + try: + conf = yaml.safe_load(raw_content) + except Exception as e: + raise YamlLintConfigError('invalid config: %s' % e) + + if not isinstance(conf, dict): + raise YamlLintConfigError('invalid config: not a dict') + + self.rules = conf.get('rules', {}) + for rule in self.rules: + if self.rules[rule] == 'enable': + self.rules[rule] = {} + elif self.rules[rule] == 'disable': + self.rules[rule] = False + + # Does this conf override another conf that we need to load? + if 'extends' in conf: + path = get_extended_config_file(conf['extends']) + base = YamlLintConfig(file=path) + try: + self.extend(base) + except Exception as e: + raise YamlLintConfigError('invalid config: %s' % e) + + if 'ignore' in conf: + if not isinstance(conf['ignore'], str): + raise YamlLintConfigError( + 'invalid config: ignore should contain file patterns') + self.ignore = pathspec.PathSpec.from_lines( + 'gitwildmatch', conf['ignore'].splitlines()) + + if 'yaml-files' in conf: + if not (isinstance(conf['yaml-files'], list) + and all(isinstance(i, str) for i in conf['yaml-files'])): + raise YamlLintConfigError( + 'invalid config: yaml-files ' + 'should be a list of file patterns') + self.yaml_files = pathspec.PathSpec.from_lines('gitwildmatch', + conf['yaml-files']) + + def validate(self): + for id in self.rules: + try: + rule = yamllint.rules.get(id) + except Exception as e: + raise YamlLintConfigError('invalid config: %s' % e) + + self.rules[id] = validate_rule_conf(rule, self.rules[id]) + + +def validate_rule_conf(rule, conf): + if conf is False: # disable + return False + + if isinstance(conf, dict): + if ('ignore' in conf and + not isinstance(conf['ignore'], pathspec.pathspec.PathSpec)): + if not isinstance(conf['ignore'], str): + raise YamlLintConfigError( + 'invalid config: ignore should contain file patterns') + conf['ignore'] = pathspec.PathSpec.from_lines( + 'gitwildmatch', conf['ignore'].splitlines()) + + if 'level' not in conf: + conf['level'] = 'error' + elif conf['level'] not in ('error', 'warning'): + raise YamlLintConfigError( + 'invalid config: level should be "error" or "warning"') + + options = getattr(rule, 'CONF', {}) + options_default = getattr(rule, 'DEFAULT', {}) + for optkey in conf: + if optkey in ('ignore', 'level'): + continue + if optkey not in options: + raise YamlLintConfigError( + 'invalid config: unknown option "%s" for rule "%s"' % + (optkey, rule.ID)) + # Example: CONF = {option: (bool, 'mixed')} + # → {option: true} → {option: mixed} + if isinstance(options[optkey], tuple): + if (conf[optkey] not in options[optkey] and + type(conf[optkey]) not in options[optkey]): + raise YamlLintConfigError( + 'invalid config: option "%s" of "%s" should be in %s' + % (optkey, rule.ID, options[optkey])) + # Example: CONF = {option: ['flag1', 'flag2', int]} + # → {option: [flag1]} → {option: [42, flag1, flag2]} + elif isinstance(options[optkey], list): + if (type(conf[optkey]) is not list or + any(flag not in options[optkey] and + type(flag) not in options[optkey] + for flag in conf[optkey])): + raise YamlLintConfigError( + ('invalid config: option "%s" of "%s" should only ' + 'contain values in %s') + % (optkey, rule.ID, str(options[optkey]))) + # Example: CONF = {option: int} + # → {option: 42} + else: + if not isinstance(conf[optkey], options[optkey]): + raise YamlLintConfigError( + 'invalid config: option "%s" of "%s" should be %s' + % (optkey, rule.ID, options[optkey].__name__)) + for optkey in options: + if optkey not in conf: + conf[optkey] = options_default[optkey] + + if hasattr(rule, 'VALIDATE'): + res = rule.VALIDATE(conf) + if res: + raise YamlLintConfigError('invalid config: %s: %s' % + (rule.ID, res)) + else: + raise YamlLintConfigError(('invalid config: rule "%s": should be ' + 'either "enable", "disable" or a dict') + % rule.ID) + + return conf + + +def get_extended_config_file(name): + # Is it a standard conf shipped with yamllint... + if '/' not in name: + std_conf = os.path.join(os.path.dirname(os.path.realpath(__file__)), + 'conf', name + '.yaml') + + if os.path.isfile(std_conf): + return std_conf + + # or a custom conf on filesystem? + return name diff --git a/third_party/python/yamllint/yamllint/linter.py b/third_party/python/yamllint/yamllint/linter.py new file mode 100644 index 0000000000..c687f142ec --- /dev/null +++ b/third_party/python/yamllint/yamllint/linter.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import re + +import yaml + +from yamllint import parser + + +PROBLEM_LEVELS = { + 0: None, + 1: 'warning', + 2: 'error', + None: 0, + 'warning': 1, + 'error': 2, +} + + +class LintProblem(object): + """Represents a linting problem found by yamllint.""" + def __init__(self, line, column, desc='', rule=None): + #: Line on which the problem was found (starting at 1) + self.line = line + #: Column on which the problem was found (starting at 1) + self.column = column + #: Human-readable description of the problem + self.desc = desc + #: Identifier of the rule that detected the problem + self.rule = rule + self.level = None + + @property + def message(self): + if self.rule is not None: + return '{} ({})'.format(self.desc, self.rule) + return self.desc + + def __eq__(self, other): + return (self.line == other.line and + self.column == other.column and + self.rule == other.rule) + + def __lt__(self, other): + return (self.line < other.line or + (self.line == other.line and self.column < other.column)) + + def __repr__(self): + return '%d:%d: %s' % (self.line, self.column, self.message) + + +def get_cosmetic_problems(buffer, conf, filepath): + rules = conf.enabled_rules(filepath) + + # Split token rules from line rules + token_rules = [r for r in rules if r.TYPE == 'token'] + comment_rules = [r for r in rules if r.TYPE == 'comment'] + line_rules = [r for r in rules if r.TYPE == 'line'] + + context = {} + for rule in token_rules: + context[rule.ID] = {} + + class DisableDirective: + def __init__(self): + self.rules = set() + self.all_rules = {r.ID for r in rules} + + def process_comment(self, comment): + try: + comment = str(comment) + except UnicodeError: + return # this certainly wasn't a yamllint directive comment + + if re.match(r'^# yamllint disable( rule:\S+)*\s*$', comment): + rules = [item[5:] for item in comment[18:].split(' ')][1:] + if len(rules) == 0: + self.rules = self.all_rules.copy() + else: + for id in rules: + if id in self.all_rules: + self.rules.add(id) + + elif re.match(r'^# yamllint enable( rule:\S+)*\s*$', comment): + rules = [item[5:] for item in comment[17:].split(' ')][1:] + if len(rules) == 0: + self.rules.clear() + else: + for id in rules: + self.rules.discard(id) + + def is_disabled_by_directive(self, problem): + return problem.rule in self.rules + + class DisableLineDirective(DisableDirective): + def process_comment(self, comment): + try: + comment = str(comment) + except UnicodeError: + return # this certainly wasn't a yamllint directive comment + + if re.match(r'^# yamllint disable-line( rule:\S+)*\s*$', comment): + rules = [item[5:] for item in comment[23:].split(' ')][1:] + if len(rules) == 0: + self.rules = self.all_rules.copy() + else: + for id in rules: + if id in self.all_rules: + self.rules.add(id) + + # Use a cache to store problems and flush it only when a end of line is + # found. This allows the use of yamllint directive to disable some rules on + # some lines. + cache = [] + disabled = DisableDirective() + disabled_for_line = DisableLineDirective() + disabled_for_next_line = DisableLineDirective() + + for elem in parser.token_or_comment_or_line_generator(buffer): + if isinstance(elem, parser.Token): + for rule in token_rules: + rule_conf = conf.rules[rule.ID] + for problem in rule.check(rule_conf, + elem.curr, elem.prev, elem.next, + elem.nextnext, + context[rule.ID]): + problem.rule = rule.ID + problem.level = rule_conf['level'] + cache.append(problem) + elif isinstance(elem, parser.Comment): + for rule in comment_rules: + rule_conf = conf.rules[rule.ID] + for problem in rule.check(rule_conf, elem): + problem.rule = rule.ID + problem.level = rule_conf['level'] + cache.append(problem) + + disabled.process_comment(elem) + if elem.is_inline(): + disabled_for_line.process_comment(elem) + else: + disabled_for_next_line.process_comment(elem) + elif isinstance(elem, parser.Line): + for rule in line_rules: + rule_conf = conf.rules[rule.ID] + for problem in rule.check(rule_conf, elem): + problem.rule = rule.ID + problem.level = rule_conf['level'] + cache.append(problem) + + # This is the last token/comment/line of this line, let's flush the + # problems found (but filter them according to the directives) + for problem in cache: + if not (disabled_for_line.is_disabled_by_directive(problem) or + disabled.is_disabled_by_directive(problem)): + yield problem + + disabled_for_line = disabled_for_next_line + disabled_for_next_line = DisableLineDirective() + cache = [] + + +def get_syntax_error(buffer): + try: + list(yaml.parse(buffer, Loader=yaml.BaseLoader)) + except yaml.error.MarkedYAMLError as e: + problem = LintProblem(e.problem_mark.line + 1, + e.problem_mark.column + 1, + 'syntax error: ' + e.problem + ' (syntax)') + problem.level = 'error' + return problem + + +def _run(buffer, conf, filepath): + assert hasattr(buffer, '__getitem__'), \ + '_run() argument must be a buffer, not a stream' + + first_line = next(parser.line_generator(buffer)).content + if re.match(r'^#\s*yamllint disable-file\s*$', first_line): + return + + # If the document contains a syntax error, save it and yield it at the + # right line + syntax_error = get_syntax_error(buffer) + + for problem in get_cosmetic_problems(buffer, conf, filepath): + # Insert the syntax error (if any) at the right place... + if (syntax_error and syntax_error.line <= problem.line and + syntax_error.column <= problem.column): + yield syntax_error + + # If there is already a yamllint error at the same place, discard + # it as it is probably redundant (and maybe it's just a 'warning', + # in which case the script won't even exit with a failure status). + if (syntax_error.line == problem.line and + syntax_error.column == problem.column): + syntax_error = None + continue + + syntax_error = None + + yield problem + + if syntax_error: + yield syntax_error + + +def run(input, conf, filepath=None): + """Lints a YAML source. + + Returns a generator of LintProblem objects. + + :param input: buffer, string or stream to read from + :param conf: yamllint configuration object + """ + if conf.is_file_ignored(filepath): + return () + + if isinstance(input, (type(b''), type(u''))): # compat with Python 2 & 3 + return _run(input, conf, filepath) + elif hasattr(input, 'read'): # Python 2's file or Python 3's io.IOBase + # We need to have everything in memory to parse correctly + content = input.read() + return _run(content, conf, filepath) + else: + raise TypeError('input should be a string or a stream') diff --git a/third_party/python/yamllint/yamllint/parser.py b/third_party/python/yamllint/yamllint/parser.py new file mode 100644 index 0000000000..de331f4729 --- /dev/null +++ b/third_party/python/yamllint/yamllint/parser.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import yaml + + +class Line(object): + def __init__(self, line_no, buffer, start, end): + self.line_no = line_no + self.start = start + self.end = end + self.buffer = buffer + + @property + def content(self): + return self.buffer[self.start:self.end] + + +class Token(object): + def __init__(self, line_no, curr, prev, next, nextnext): + self.line_no = line_no + self.curr = curr + self.prev = prev + self.next = next + self.nextnext = nextnext + + +class Comment(object): + def __init__(self, line_no, column_no, buffer, pointer, + token_before=None, token_after=None, comment_before=None): + self.line_no = line_no + self.column_no = column_no + self.buffer = buffer + self.pointer = pointer + self.token_before = token_before + self.token_after = token_after + self.comment_before = comment_before + + def __str__(self): + end = self.buffer.find('\n', self.pointer) + if end == -1: + end = self.buffer.find('\0', self.pointer) + if end != -1: + return self.buffer[self.pointer:end] + return self.buffer[self.pointer:] + + def __eq__(self, other): + return (isinstance(other, Comment) and + self.line_no == other.line_no and + self.column_no == other.column_no and + str(self) == str(other)) + + def is_inline(self): + return ( + not isinstance(self.token_before, yaml.StreamStartToken) and + self.line_no == self.token_before.end_mark.line + 1 and + # sometimes token end marks are on the next line + self.buffer[self.token_before.end_mark.pointer - 1] != '\n' + ) + + +def line_generator(buffer): + line_no = 1 + cur = 0 + next = buffer.find('\n') + while next != -1: + if next > 0 and buffer[next - 1] == '\r': + yield Line(line_no, buffer, start=cur, end=next - 1) + else: + yield Line(line_no, buffer, start=cur, end=next) + cur = next + 1 + next = buffer.find('\n', cur) + line_no += 1 + + yield Line(line_no, buffer, start=cur, end=len(buffer)) + + +def comments_between_tokens(token1, token2): + """Find all comments between two tokens""" + if token2 is None: + buf = token1.end_mark.buffer[token1.end_mark.pointer:] + elif (token1.end_mark.line == token2.start_mark.line and + not isinstance(token1, yaml.StreamStartToken) and + not isinstance(token2, yaml.StreamEndToken)): + return + else: + buf = token1.end_mark.buffer[token1.end_mark.pointer: + token2.start_mark.pointer] + + line_no = token1.end_mark.line + 1 + column_no = token1.end_mark.column + 1 + pointer = token1.end_mark.pointer + + comment_before = None + for line in buf.split('\n'): + pos = line.find('#') + if pos != -1: + comment = Comment(line_no, column_no + pos, + token1.end_mark.buffer, pointer + pos, + token1, token2, comment_before) + yield comment + + comment_before = comment + + pointer += len(line) + 1 + line_no += 1 + column_no = 1 + + +def token_or_comment_generator(buffer): + yaml_loader = yaml.BaseLoader(buffer) + + try: + prev = None + curr = yaml_loader.get_token() + while curr is not None: + next = yaml_loader.get_token() + nextnext = (yaml_loader.peek_token() + if yaml_loader.check_token() else None) + + yield Token(curr.start_mark.line + 1, curr, prev, next, nextnext) + + for comment in comments_between_tokens(curr, next): + yield comment + + prev = curr + curr = next + + except yaml.scanner.ScannerError: + pass + + +def token_or_comment_or_line_generator(buffer): + """Generator that mixes tokens and lines, ordering them by line number""" + tok_or_com_gen = token_or_comment_generator(buffer) + line_gen = line_generator(buffer) + + tok_or_com = next(tok_or_com_gen, None) + line = next(line_gen, None) + + while tok_or_com is not None or line is not None: + if tok_or_com is None or (line is not None and + tok_or_com.line_no > line.line_no): + yield line + line = next(line_gen, None) + else: + yield tok_or_com + tok_or_com = next(tok_or_com_gen, None) diff --git a/third_party/python/yamllint/yamllint/rules/__init__.py b/third_party/python/yamllint/yamllint/rules/__init__.py new file mode 100644 index 0000000000..a084d6ee16 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/__init__.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from yamllint.rules import ( + braces, + brackets, + colons, + commas, + comments, + comments_indentation, + document_end, + document_start, + empty_lines, + empty_values, + hyphens, + indentation, + key_duplicates, + key_ordering, + line_length, + new_line_at_end_of_file, + new_lines, + octal_values, + quoted_strings, + trailing_spaces, + truthy, +) + +_RULES = { + braces.ID: braces, + brackets.ID: brackets, + colons.ID: colons, + commas.ID: commas, + comments.ID: comments, + comments_indentation.ID: comments_indentation, + document_end.ID: document_end, + document_start.ID: document_start, + empty_lines.ID: empty_lines, + empty_values.ID: empty_values, + hyphens.ID: hyphens, + indentation.ID: indentation, + key_duplicates.ID: key_duplicates, + key_ordering.ID: key_ordering, + line_length.ID: line_length, + new_line_at_end_of_file.ID: new_line_at_end_of_file, + new_lines.ID: new_lines, + octal_values.ID: octal_values, + quoted_strings.ID: quoted_strings, + trailing_spaces.ID: trailing_spaces, + truthy.ID: truthy, +} + + +def get(id): + if id not in _RULES: + raise ValueError('no such rule: "%s"' % id) + + return _RULES[id] diff --git a/third_party/python/yamllint/yamllint/rules/braces.py b/third_party/python/yamllint/yamllint/rules/braces.py new file mode 100644 index 0000000000..654b36d330 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/braces.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to control the number of spaces inside braces (``{`` and ``}``). + +.. rubric:: Options + +* ``min-spaces-inside`` defines the minimal number of spaces required inside + braces. +* ``max-spaces-inside`` defines the maximal number of spaces allowed inside + braces. +* ``min-spaces-inside-empty`` defines the minimal number of spaces required + inside empty braces. +* ``max-spaces-inside-empty`` defines the maximal number of spaces allowed + inside empty braces. + +.. rubric:: Examples + +#. With ``braces: {min-spaces-inside: 0, max-spaces-inside: 0}`` + + the following code snippet would **PASS**: + :: + + object: {key1: 4, key2: 8} + + the following code snippet would **FAIL**: + :: + + object: { key1: 4, key2: 8 } + +#. With ``braces: {min-spaces-inside: 1, max-spaces-inside: 3}`` + + the following code snippet would **PASS**: + :: + + object: { key1: 4, key2: 8 } + + the following code snippet would **PASS**: + :: + + object: { key1: 4, key2: 8 } + + the following code snippet would **FAIL**: + :: + + object: { key1: 4, key2: 8 } + + the following code snippet would **FAIL**: + :: + + object: {key1: 4, key2: 8 } + +#. With ``braces: {min-spaces-inside-empty: 0, max-spaces-inside-empty: 0}`` + + the following code snippet would **PASS**: + :: + + object: {} + + the following code snippet would **FAIL**: + :: + + object: { } + +#. With ``braces: {min-spaces-inside-empty: 1, max-spaces-inside-empty: -1}`` + + the following code snippet would **PASS**: + :: + + object: { } + + the following code snippet would **FAIL**: + :: + + object: {} +""" + + +import yaml + +from yamllint.rules.common import spaces_after, spaces_before + + +ID = 'braces' +TYPE = 'token' +CONF = {'min-spaces-inside': int, + 'max-spaces-inside': int, + 'min-spaces-inside-empty': int, + 'max-spaces-inside-empty': int} +DEFAULT = {'min-spaces-inside': 0, + 'max-spaces-inside': 0, + 'min-spaces-inside-empty': -1, + 'max-spaces-inside-empty': -1} + + +def check(conf, token, prev, next, nextnext, context): + if (isinstance(token, yaml.FlowMappingStartToken) and + isinstance(next, yaml.FlowMappingEndToken)): + problem = spaces_after(token, prev, next, + min=(conf['min-spaces-inside-empty'] + if conf['min-spaces-inside-empty'] != -1 + else conf['min-spaces-inside']), + max=(conf['max-spaces-inside-empty'] + if conf['max-spaces-inside-empty'] != -1 + else conf['max-spaces-inside']), + min_desc='too few spaces inside empty braces', + max_desc='too many spaces inside empty braces') + if problem is not None: + yield problem + + elif isinstance(token, yaml.FlowMappingStartToken): + problem = spaces_after(token, prev, next, + min=conf['min-spaces-inside'], + max=conf['max-spaces-inside'], + min_desc='too few spaces inside braces', + max_desc='too many spaces inside braces') + if problem is not None: + yield problem + + elif (isinstance(token, yaml.FlowMappingEndToken) and + (prev is None or + not isinstance(prev, yaml.FlowMappingStartToken))): + problem = spaces_before(token, prev, next, + min=conf['min-spaces-inside'], + max=conf['max-spaces-inside'], + min_desc='too few spaces inside braces', + max_desc='too many spaces inside braces') + if problem is not None: + yield problem diff --git a/third_party/python/yamllint/yamllint/rules/brackets.py b/third_party/python/yamllint/yamllint/rules/brackets.py new file mode 100644 index 0000000000..b54c5154aa --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/brackets.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to control the number of spaces inside brackets (``[`` and +``]``). + +.. rubric:: Options + +* ``min-spaces-inside`` defines the minimal number of spaces required inside + brackets. +* ``max-spaces-inside`` defines the maximal number of spaces allowed inside + brackets. +* ``min-spaces-inside-empty`` defines the minimal number of spaces required + inside empty brackets. +* ``max-spaces-inside-empty`` defines the maximal number of spaces allowed + inside empty brackets. + +.. rubric:: Examples + +#. With ``brackets: {min-spaces-inside: 0, max-spaces-inside: 0}`` + + the following code snippet would **PASS**: + :: + + object: [1, 2, abc] + + the following code snippet would **FAIL**: + :: + + object: [ 1, 2, abc ] + +#. With ``brackets: {min-spaces-inside: 1, max-spaces-inside: 3}`` + + the following code snippet would **PASS**: + :: + + object: [ 1, 2, abc ] + + the following code snippet would **PASS**: + :: + + object: [ 1, 2, abc ] + + the following code snippet would **FAIL**: + :: + + object: [ 1, 2, abc ] + + the following code snippet would **FAIL**: + :: + + object: [1, 2, abc ] + +#. With ``brackets: {min-spaces-inside-empty: 0, max-spaces-inside-empty: 0}`` + + the following code snippet would **PASS**: + :: + + object: [] + + the following code snippet would **FAIL**: + :: + + object: [ ] + +#. With ``brackets: {min-spaces-inside-empty: 1, max-spaces-inside-empty: -1}`` + + the following code snippet would **PASS**: + :: + + object: [ ] + + the following code snippet would **FAIL**: + :: + + object: [] +""" + + +import yaml + +from yamllint.rules.common import spaces_after, spaces_before + + +ID = 'brackets' +TYPE = 'token' +CONF = {'min-spaces-inside': int, + 'max-spaces-inside': int, + 'min-spaces-inside-empty': int, + 'max-spaces-inside-empty': int} +DEFAULT = {'min-spaces-inside': 0, + 'max-spaces-inside': 0, + 'min-spaces-inside-empty': -1, + 'max-spaces-inside-empty': -1} + + +def check(conf, token, prev, next, nextnext, context): + if (isinstance(token, yaml.FlowSequenceStartToken) and + isinstance(next, yaml.FlowSequenceEndToken)): + problem = spaces_after(token, prev, next, + min=(conf['min-spaces-inside-empty'] + if conf['min-spaces-inside-empty'] != -1 + else conf['min-spaces-inside']), + max=(conf['max-spaces-inside-empty'] + if conf['max-spaces-inside-empty'] != -1 + else conf['max-spaces-inside']), + min_desc='too few spaces inside empty brackets', + max_desc=('too many spaces inside empty ' + 'brackets')) + if problem is not None: + yield problem + + elif isinstance(token, yaml.FlowSequenceStartToken): + problem = spaces_after(token, prev, next, + min=conf['min-spaces-inside'], + max=conf['max-spaces-inside'], + min_desc='too few spaces inside brackets', + max_desc='too many spaces inside brackets') + if problem is not None: + yield problem + + elif (isinstance(token, yaml.FlowSequenceEndToken) and + (prev is None or + not isinstance(prev, yaml.FlowSequenceStartToken))): + problem = spaces_before(token, prev, next, + min=conf['min-spaces-inside'], + max=conf['max-spaces-inside'], + min_desc='too few spaces inside brackets', + max_desc='too many spaces inside brackets') + if problem is not None: + yield problem diff --git a/third_party/python/yamllint/yamllint/rules/colons.py b/third_party/python/yamllint/yamllint/rules/colons.py new file mode 100644 index 0000000000..1a63cadab6 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/colons.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to control the number of spaces before and after colons (``:``). + +.. rubric:: Options + +* ``max-spaces-before`` defines the maximal number of spaces allowed before + colons (use ``-1`` to disable). +* ``max-spaces-after`` defines the maximal number of spaces allowed after + colons (use ``-1`` to disable). + +.. rubric:: Examples + +#. With ``colons: {max-spaces-before: 0, max-spaces-after: 1}`` + + the following code snippet would **PASS**: + :: + + object: + - a + - b + key: value + +#. With ``colons: {max-spaces-before: 1}`` + + the following code snippet would **PASS**: + :: + + object : + - a + - b + + the following code snippet would **FAIL**: + :: + + object : + - a + - b + +#. With ``colons: {max-spaces-after: 2}`` + + the following code snippet would **PASS**: + :: + + first: 1 + second: 2 + third: 3 + + the following code snippet would **FAIL**: + :: + + first: 1 + 2nd: 2 + third: 3 +""" + + +import yaml + +from yamllint.rules.common import is_explicit_key, spaces_after, spaces_before + + +ID = 'colons' +TYPE = 'token' +CONF = {'max-spaces-before': int, + 'max-spaces-after': int} +DEFAULT = {'max-spaces-before': 0, + 'max-spaces-after': 1} + + +def check(conf, token, prev, next, nextnext, context): + if isinstance(token, yaml.ValueToken): + problem = spaces_before(token, prev, next, + max=conf['max-spaces-before'], + max_desc='too many spaces before colon') + if problem is not None: + yield problem + + problem = spaces_after(token, prev, next, + max=conf['max-spaces-after'], + max_desc='too many spaces after colon') + if problem is not None: + yield problem + + if isinstance(token, yaml.KeyToken) and is_explicit_key(token): + problem = spaces_after(token, prev, next, + max=conf['max-spaces-after'], + max_desc='too many spaces after question mark') + if problem is not None: + yield problem diff --git a/third_party/python/yamllint/yamllint/rules/commas.py b/third_party/python/yamllint/yamllint/rules/commas.py new file mode 100644 index 0000000000..bb73044545 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/commas.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to control the number of spaces before and after commas (``,``). + +.. rubric:: Options + +* ``max-spaces-before`` defines the maximal number of spaces allowed before + commas (use ``-1`` to disable). +* ``min-spaces-after`` defines the minimal number of spaces required after + commas. +* ``max-spaces-after`` defines the maximal number of spaces allowed after + commas (use ``-1`` to disable). + +.. rubric:: Examples + +#. With ``commas: {max-spaces-before: 0}`` + + the following code snippet would **PASS**: + :: + + strange var: + [10, 20, 30, {x: 1, y: 2}] + + the following code snippet would **FAIL**: + :: + + strange var: + [10, 20 , 30, {x: 1, y: 2}] + +#. With ``commas: {max-spaces-before: 2}`` + + the following code snippet would **PASS**: + :: + + strange var: + [10 , 20 , 30, {x: 1 , y: 2}] + +#. With ``commas: {max-spaces-before: -1}`` + + the following code snippet would **PASS**: + :: + + strange var: + [10, + 20 , 30 + , {x: 1, y: 2}] + +#. With ``commas: {min-spaces-after: 1, max-spaces-after: 1}`` + + the following code snippet would **PASS**: + :: + + strange var: + [10, 20,30, {x: 1, y: 2}] + + the following code snippet would **FAIL**: + :: + + strange var: + [10, 20,30, {x: 1, y: 2}] + +#. With ``commas: {min-spaces-after: 1, max-spaces-after: 3}`` + + the following code snippet would **PASS**: + :: + + strange var: + [10, 20, 30, {x: 1, y: 2}] + +#. With ``commas: {min-spaces-after: 0, max-spaces-after: 1}`` + + the following code snippet would **PASS**: + :: + + strange var: + [10, 20,30, {x: 1, y: 2}] +""" + + +import yaml + +from yamllint.linter import LintProblem +from yamllint.rules.common import spaces_after, spaces_before + + +ID = 'commas' +TYPE = 'token' +CONF = {'max-spaces-before': int, + 'min-spaces-after': int, + 'max-spaces-after': int} +DEFAULT = {'max-spaces-before': 0, + 'min-spaces-after': 1, + 'max-spaces-after': 1} + + +def check(conf, token, prev, next, nextnext, context): + if isinstance(token, yaml.FlowEntryToken): + if (prev is not None and conf['max-spaces-before'] != -1 and + prev.end_mark.line < token.start_mark.line): + yield LintProblem(token.start_mark.line + 1, + max(1, token.start_mark.column), + 'too many spaces before comma') + else: + problem = spaces_before(token, prev, next, + max=conf['max-spaces-before'], + max_desc='too many spaces before comma') + if problem is not None: + yield problem + + problem = spaces_after(token, prev, next, + min=conf['min-spaces-after'], + max=conf['max-spaces-after'], + min_desc='too few spaces after comma', + max_desc='too many spaces after comma') + if problem is not None: + yield problem diff --git a/third_party/python/yamllint/yamllint/rules/comments.py b/third_party/python/yamllint/yamllint/rules/comments.py new file mode 100644 index 0000000000..0122838f61 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/comments.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to control the position and formatting of comments. + +.. rubric:: Options + +* Use ``require-starting-space`` to require a space character right after the + ``#``. Set to ``true`` to enable, ``false`` to disable. +* Use ``ignore-shebangs`` to ignore a + `shebang `_ at the beginning of + the file when ``require-starting-space`` is set. +* ``min-spaces-from-content`` is used to visually separate inline comments from + content. It defines the minimal required number of spaces between a comment + and its preceding content. + +.. rubric:: Examples + +#. With ``comments: {require-starting-space: true}`` + + the following code snippet would **PASS**: + :: + + # This sentence + # is a block comment + + the following code snippet would **PASS**: + :: + + ############################## + ## This is some documentation + + the following code snippet would **FAIL**: + :: + + #This sentence + #is a block comment + +#. With ``comments: {min-spaces-from-content: 2}`` + + the following code snippet would **PASS**: + :: + + x = 2 ^ 127 - 1 # Mersenne prime number + + the following code snippet would **FAIL**: + :: + + x = 2 ^ 127 - 1 # Mersenne prime number +""" + + +import re + +from yamllint.linter import LintProblem + + +ID = 'comments' +TYPE = 'comment' +CONF = {'require-starting-space': bool, + 'ignore-shebangs': bool, + 'min-spaces-from-content': int} +DEFAULT = {'require-starting-space': True, + 'ignore-shebangs': True, + 'min-spaces-from-content': 2} + + +def check(conf, comment): + if (conf['min-spaces-from-content'] != -1 and comment.is_inline() and + comment.pointer - comment.token_before.end_mark.pointer < + conf['min-spaces-from-content']): + yield LintProblem(comment.line_no, comment.column_no, + 'too few spaces before comment') + + if conf['require-starting-space']: + text_start = comment.pointer + 1 + while (comment.buffer[text_start] == '#' and + text_start < len(comment.buffer)): + text_start += 1 + if text_start < len(comment.buffer): + if (conf['ignore-shebangs'] and + comment.line_no == 1 and + comment.column_no == 1 and + re.match(r'^!\S', comment.buffer[text_start:])): + return + elif comment.buffer[text_start] not in (' ', '\n', '\0'): + column = comment.column_no + text_start - comment.pointer + yield LintProblem(comment.line_no, + column, + 'missing starting space in comment') diff --git a/third_party/python/yamllint/yamllint/rules/comments_indentation.py b/third_party/python/yamllint/yamllint/rules/comments_indentation.py new file mode 100644 index 0000000000..22ab55d6d3 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/comments_indentation.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to force comments to be indented like content. + +.. rubric:: Examples + +#. With ``comments-indentation: {}`` + + the following code snippet would **PASS**: + :: + + # Fibonacci + [0, 1, 1, 2, 3, 5] + + the following code snippet would **FAIL**: + :: + + # Fibonacci + [0, 1, 1, 2, 3, 5] + + the following code snippet would **PASS**: + :: + + list: + - 2 + - 3 + # - 4 + - 5 + + the following code snippet would **FAIL**: + :: + + list: + - 2 + - 3 + # - 4 + - 5 + + the following code snippet would **PASS**: + :: + + # This is the first object + obj1: + - item A + # - item B + # This is the second object + obj2: [] + + the following code snippet would **PASS**: + :: + + # This sentence + # is a block comment + + the following code snippet would **FAIL**: + :: + + # This sentence + # is a block comment +""" + + +import yaml + +from yamllint.linter import LintProblem +from yamllint.rules.common import get_line_indent + + +ID = 'comments-indentation' +TYPE = 'comment' + + +# Case A: +# +# prev: line: +# # commented line +# current: line +# +# Case B: +# +# prev: line +# # commented line 1 +# # commented line 2 +# current: line + +def check(conf, comment): + # Only check block comments + if (not isinstance(comment.token_before, yaml.StreamStartToken) and + comment.token_before.end_mark.line + 1 == comment.line_no): + return + + next_line_indent = comment.token_after.start_mark.column + if isinstance(comment.token_after, yaml.StreamEndToken): + next_line_indent = 0 + + if isinstance(comment.token_before, yaml.StreamStartToken): + prev_line_indent = 0 + else: + prev_line_indent = get_line_indent(comment.token_before) + + # In the following case only the next line indent is valid: + # list: + # # comment + # - 1 + # - 2 + if prev_line_indent <= next_line_indent: + prev_line_indent = next_line_indent + + # If two indents are valid but a previous comment went back to normal + # indent, for the next ones to do the same. In other words, avoid this: + # list: + # - 1 + # # comment on valid indent (0) + # # comment on valid indent (4) + # other-list: + # - 2 + if (comment.comment_before is not None and + not comment.comment_before.is_inline()): + prev_line_indent = comment.comment_before.column_no - 1 + + if (comment.column_no - 1 != prev_line_indent and + comment.column_no - 1 != next_line_indent): + yield LintProblem(comment.line_no, comment.column_no, + 'comment not indented like content') diff --git a/third_party/python/yamllint/yamllint/rules/common.py b/third_party/python/yamllint/yamllint/rules/common.py new file mode 100644 index 0000000000..989345965c --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/common.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import string + +import yaml + +from yamllint.linter import LintProblem + + +def spaces_after(token, prev, next, min=-1, max=-1, + min_desc=None, max_desc=None): + if next is not None and token.end_mark.line == next.start_mark.line: + spaces = next.start_mark.pointer - token.end_mark.pointer + if max != - 1 and spaces > max: + return LintProblem(token.start_mark.line + 1, + next.start_mark.column, max_desc) + elif min != - 1 and spaces < min: + return LintProblem(token.start_mark.line + 1, + next.start_mark.column + 1, min_desc) + + +def spaces_before(token, prev, next, min=-1, max=-1, + min_desc=None, max_desc=None): + if (prev is not None and prev.end_mark.line == token.start_mark.line and + # Discard tokens (only scalars?) that end at the start of next line + (prev.end_mark.pointer == 0 or + prev.end_mark.buffer[prev.end_mark.pointer - 1] != '\n')): + spaces = token.start_mark.pointer - prev.end_mark.pointer + if max != - 1 and spaces > max: + return LintProblem(token.start_mark.line + 1, + token.start_mark.column, max_desc) + elif min != - 1 and spaces < min: + return LintProblem(token.start_mark.line + 1, + token.start_mark.column + 1, min_desc) + + +def get_line_indent(token): + """Finds the indent of the line the token starts in.""" + start = token.start_mark.buffer.rfind('\n', 0, + token.start_mark.pointer) + 1 + content = start + while token.start_mark.buffer[content] == ' ': + content += 1 + return content - start + + +def get_real_end_line(token): + """Finds the line on which the token really ends. + + With pyyaml, scalar tokens often end on a next line. + """ + end_line = token.end_mark.line + 1 + + if not isinstance(token, yaml.ScalarToken): + return end_line + + pos = token.end_mark.pointer - 1 + while (pos >= token.start_mark.pointer - 1 and + token.end_mark.buffer[pos] in string.whitespace): + if token.end_mark.buffer[pos] == '\n': + end_line -= 1 + pos -= 1 + return end_line + + +def is_explicit_key(token): + # explicit key: + # ? key + # : v + # or + # ? + # key + # : v + return (token.start_mark.pointer < token.end_mark.pointer and + token.start_mark.buffer[token.start_mark.pointer] == '?') diff --git a/third_party/python/yamllint/yamllint/rules/document_end.py b/third_party/python/yamllint/yamllint/rules/document_end.py new file mode 100644 index 0000000000..e98aac1d12 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/document_end.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to require or forbid the use of document end marker (``...``). + +.. rubric:: Options + +* Set ``present`` to ``true`` when the document end marker is required, or to + ``false`` when it is forbidden. + +.. rubric:: Examples + +#. With ``document-end: {present: true}`` + + the following code snippet would **PASS**: + :: + + --- + this: + is: [a, document] + ... + --- + - this + - is: another one + ... + + the following code snippet would **FAIL**: + :: + + --- + this: + is: [a, document] + --- + - this + - is: another one + ... + +#. With ``document-end: {present: false}`` + + the following code snippet would **PASS**: + :: + + --- + this: + is: [a, document] + --- + - this + - is: another one + + the following code snippet would **FAIL**: + :: + + --- + this: + is: [a, document] + ... + --- + - this + - is: another one +""" + + +import yaml + +from yamllint.linter import LintProblem + + +ID = 'document-end' +TYPE = 'token' +CONF = {'present': bool} +DEFAULT = {'present': True} + + +def check(conf, token, prev, next, nextnext, context): + if conf['present']: + is_stream_end = isinstance(token, yaml.StreamEndToken) + is_start = isinstance(token, yaml.DocumentStartToken) + prev_is_end_or_stream_start = isinstance( + prev, (yaml.DocumentEndToken, yaml.StreamStartToken) + ) + + if is_stream_end and not prev_is_end_or_stream_start: + yield LintProblem(token.start_mark.line, 1, + 'missing document end "..."') + elif is_start and not prev_is_end_or_stream_start: + yield LintProblem(token.start_mark.line + 1, 1, + 'missing document end "..."') + + else: + if isinstance(token, yaml.DocumentEndToken): + yield LintProblem(token.start_mark.line + 1, + token.start_mark.column + 1, + 'found forbidden document end "..."') diff --git a/third_party/python/yamllint/yamllint/rules/document_start.py b/third_party/python/yamllint/yamllint/rules/document_start.py new file mode 100644 index 0000000000..36c3d8e8db --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/document_start.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to require or forbid the use of document start marker (``---``). + +.. rubric:: Options + +* Set ``present`` to ``true`` when the document start marker is required, or to + ``false`` when it is forbidden. + +.. rubric:: Examples + +#. With ``document-start: {present: true}`` + + the following code snippet would **PASS**: + :: + + --- + this: + is: [a, document] + --- + - this + - is: another one + + the following code snippet would **FAIL**: + :: + + this: + is: [a, document] + --- + - this + - is: another one + +#. With ``document-start: {present: false}`` + + the following code snippet would **PASS**: + :: + + this: + is: [a, document] + ... + + the following code snippet would **FAIL**: + :: + + --- + this: + is: [a, document] + ... +""" + + +import yaml + +from yamllint.linter import LintProblem + + +ID = 'document-start' +TYPE = 'token' +CONF = {'present': bool} +DEFAULT = {'present': True} + + +def check(conf, token, prev, next, nextnext, context): + if conf['present']: + if (isinstance(prev, (yaml.StreamStartToken, + yaml.DocumentEndToken, + yaml.DirectiveToken)) and + not isinstance(token, (yaml.DocumentStartToken, + yaml.DirectiveToken, + yaml.StreamEndToken))): + yield LintProblem(token.start_mark.line + 1, 1, + 'missing document start "---"') + + else: + if isinstance(token, yaml.DocumentStartToken): + yield LintProblem(token.start_mark.line + 1, + token.start_mark.column + 1, + 'found forbidden document start "---"') diff --git a/third_party/python/yamllint/yamllint/rules/empty_lines.py b/third_party/python/yamllint/yamllint/rules/empty_lines.py new file mode 100644 index 0000000000..d9a8c4d173 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/empty_lines.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to set a maximal number of allowed consecutive blank lines. + +.. rubric:: Options + +* ``max`` defines the maximal number of empty lines allowed in the document. +* ``max-start`` defines the maximal number of empty lines allowed at the + beginning of the file. This option takes precedence over ``max``. +* ``max-end`` defines the maximal number of empty lines allowed at the end of + the file. This option takes precedence over ``max``. + +.. rubric:: Examples + +#. With ``empty-lines: {max: 1}`` + + the following code snippet would **PASS**: + :: + + - foo: + - 1 + - 2 + + - bar: [3, 4] + + the following code snippet would **FAIL**: + :: + + - foo: + - 1 + - 2 + + + - bar: [3, 4] +""" + + +from yamllint.linter import LintProblem + + +ID = 'empty-lines' +TYPE = 'line' +CONF = {'max': int, + 'max-start': int, + 'max-end': int} +DEFAULT = {'max': 2, + 'max-start': 0, + 'max-end': 0} + + +def check(conf, line): + if line.start == line.end and line.end < len(line.buffer): + # Only alert on the last blank line of a series + if (line.end + 2 <= len(line.buffer) and + line.buffer[line.end:line.end + 2] == '\n\n'): + return + elif (line.end + 4 <= len(line.buffer) and + line.buffer[line.end:line.end + 4] == '\r\n\r\n'): + return + + blank_lines = 0 + + start = line.start + while start >= 2 and line.buffer[start - 2:start] == '\r\n': + blank_lines += 1 + start -= 2 + while start >= 1 and line.buffer[start - 1] == '\n': + blank_lines += 1 + start -= 1 + + max = conf['max'] + + # Special case: start of document + if start == 0: + blank_lines += 1 # first line doesn't have a preceding \n + max = conf['max-start'] + + # Special case: end of document + # NOTE: The last line of a file is always supposed to end with a new + # line. See POSIX definition of a line at: + if ((line.end == len(line.buffer) - 1 and + line.buffer[line.end] == '\n') or + (line.end == len(line.buffer) - 2 and + line.buffer[line.end:line.end + 2] == '\r\n')): + # Allow the exception of the one-byte file containing '\n' + if line.end == 0: + return + + max = conf['max-end'] + + if blank_lines > max: + yield LintProblem(line.line_no, 1, 'too many blank lines (%d > %d)' + % (blank_lines, max)) diff --git a/third_party/python/yamllint/yamllint/rules/empty_values.py b/third_party/python/yamllint/yamllint/rules/empty_values.py new file mode 100644 index 0000000000..bb4982bfdb --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/empty_values.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2017 Greg Dubicki +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to prevent nodes with empty content, that implicitly result in +``null`` values. + +.. rubric:: Options + +* Use ``forbid-in-block-mappings`` to prevent empty values in block mappings. +* Use ``forbid-in-flow-mappings`` to prevent empty values in flow mappings. + +.. rubric:: Examples + +#. With ``empty-values: {forbid-in-block-mappings: true}`` + + the following code snippets would **PASS**: + :: + + some-mapping: + sub-element: correctly indented + + :: + + explicitly-null: null + + the following code snippets would **FAIL**: + :: + + some-mapping: + sub-element: incorrectly indented + + :: + + implicitly-null: + +#. With ``empty-values: {forbid-in-flow-mappings: true}`` + + the following code snippet would **PASS**: + :: + + {prop: null} + {a: 1, b: 2, c: 3} + + the following code snippets would **FAIL**: + :: + + {prop: } + + :: + + {a: 1, b:, c: 3} + +""" + +import yaml + +from yamllint.linter import LintProblem + + +ID = 'empty-values' +TYPE = 'token' +CONF = {'forbid-in-block-mappings': bool, + 'forbid-in-flow-mappings': bool} +DEFAULT = {'forbid-in-block-mappings': True, + 'forbid-in-flow-mappings': True} + + +def check(conf, token, prev, next, nextnext, context): + + if conf['forbid-in-block-mappings']: + if isinstance(token, yaml.ValueToken) and isinstance(next, ( + yaml.KeyToken, yaml.BlockEndToken)): + yield LintProblem(token.start_mark.line + 1, + token.end_mark.column + 1, + 'empty value in block mapping') + + if conf['forbid-in-flow-mappings']: + if isinstance(token, yaml.ValueToken) and isinstance(next, ( + yaml.FlowEntryToken, yaml.FlowMappingEndToken)): + yield LintProblem(token.start_mark.line + 1, + token.end_mark.column + 1, + 'empty value in flow mapping') diff --git a/third_party/python/yamllint/yamllint/rules/hyphens.py b/third_party/python/yamllint/yamllint/rules/hyphens.py new file mode 100644 index 0000000000..df38b4c519 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/hyphens.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to control the number of spaces after hyphens (``-``). + +.. rubric:: Options + +* ``max-spaces-after`` defines the maximal number of spaces allowed after + hyphens. + +.. rubric:: Examples + +#. With ``hyphens: {max-spaces-after: 1}`` + + the following code snippet would **PASS**: + :: + + - first list: + - a + - b + - - 1 + - 2 + - 3 + + the following code snippet would **FAIL**: + :: + + - first list: + - a + - b + + the following code snippet would **FAIL**: + :: + + - - 1 + - 2 + - 3 + +#. With ``hyphens: {max-spaces-after: 3}`` + + the following code snippet would **PASS**: + :: + + - key + - key2 + - key42 + + the following code snippet would **FAIL**: + :: + + - key + - key2 + - key42 +""" + + +import yaml + +from yamllint.rules.common import spaces_after + + +ID = 'hyphens' +TYPE = 'token' +CONF = {'max-spaces-after': int} +DEFAULT = {'max-spaces-after': 1} + + +def check(conf, token, prev, next, nextnext, context): + if isinstance(token, yaml.BlockEntryToken): + problem = spaces_after(token, prev, next, + max=conf['max-spaces-after'], + max_desc='too many spaces after hyphen') + if problem is not None: + yield problem diff --git a/third_party/python/yamllint/yamllint/rules/indentation.py b/third_party/python/yamllint/yamllint/rules/indentation.py new file mode 100644 index 0000000000..d83eb6594b --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/indentation.py @@ -0,0 +1,575 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to control the indentation. + +.. rubric:: Options + +* ``spaces`` defines the indentation width, in spaces. Set either to an integer + (e.g. ``2`` or ``4``, representing the number of spaces in an indentation + level) or to ``consistent`` to allow any number, as long as it remains the + same within the file. +* ``indent-sequences`` defines whether block sequences should be indented or + not (when in a mapping, this indentation is not mandatory -- some people + perceive the ``-`` as part of the indentation). Possible values: ``true``, + ``false``, ``whatever`` and ``consistent``. ``consistent`` requires either + all block sequences to be indented, or none to be. ``whatever`` means either + indenting or not indenting individual block sequences is OK. +* ``check-multi-line-strings`` defines whether to lint indentation in + multi-line strings. Set to ``true`` to enable, ``false`` to disable. + +.. rubric:: Examples + +#. With ``indentation: {spaces: 1}`` + + the following code snippet would **PASS**: + :: + + history: + - name: Unix + date: 1969 + - name: Linux + date: 1991 + nest: + recurse: + - haystack: + needle + +#. With ``indentation: {spaces: 4}`` + + the following code snippet would **PASS**: + :: + + history: + - name: Unix + date: 1969 + - name: Linux + date: 1991 + nest: + recurse: + - haystack: + needle + + the following code snippet would **FAIL**: + :: + + history: + - name: Unix + date: 1969 + - name: Linux + date: 1991 + nest: + recurse: + - haystack: + needle + +#. With ``indentation: {spaces: consistent}`` + + the following code snippet would **PASS**: + :: + + history: + - name: Unix + date: 1969 + - name: Linux + date: 1991 + nest: + recurse: + - haystack: + needle + + the following code snippet would **FAIL**: + :: + + some: + Russian: + dolls + +#. With ``indentation: {spaces: 2, indent-sequences: false}`` + + the following code snippet would **PASS**: + :: + + list: + - flying + - spaghetti + - monster + + the following code snippet would **FAIL**: + :: + + list: + - flying + - spaghetti + - monster + +#. With ``indentation: {spaces: 2, indent-sequences: whatever}`` + + the following code snippet would **PASS**: + :: + + list: + - flying: + - spaghetti + - monster + - not flying: + - spaghetti + - sauce + +#. With ``indentation: {spaces: 2, indent-sequences: consistent}`` + + the following code snippet would **PASS**: + :: + + - flying: + - spaghetti + - monster + - not flying: + - spaghetti + - sauce + + the following code snippet would **FAIL**: + :: + + - flying: + - spaghetti + - monster + - not flying: + - spaghetti + - sauce + +#. With ``indentation: {spaces: 4, check-multi-line-strings: true}`` + + the following code snippet would **PASS**: + :: + + Blaise Pascal: + Je vous écris une longue lettre parce que + je n'ai pas le temps d'en écrire une courte. + + the following code snippet would **PASS**: + :: + + Blaise Pascal: Je vous écris une longue lettre parce que + je n'ai pas le temps d'en écrire une courte. + + the following code snippet would **FAIL**: + :: + + Blaise Pascal: Je vous écris une longue lettre parce que + je n'ai pas le temps d'en écrire une courte. + + the following code snippet would **FAIL**: + :: + + C code: + void main() { + printf("foo"); + } + + the following code snippet would **PASS**: + :: + + C code: + void main() { + printf("bar"); + } +""" + +import yaml + +from yamllint.linter import LintProblem +from yamllint.rules.common import get_real_end_line, is_explicit_key + + +ID = 'indentation' +TYPE = 'token' +CONF = {'spaces': (int, 'consistent'), + 'indent-sequences': (bool, 'whatever', 'consistent'), + 'check-multi-line-strings': bool} +DEFAULT = {'spaces': 'consistent', + 'indent-sequences': True, + 'check-multi-line-strings': False} + +ROOT, B_MAP, F_MAP, B_SEQ, F_SEQ, B_ENT, KEY, VAL = range(8) +labels = ('ROOT', 'B_MAP', 'F_MAP', 'B_SEQ', 'F_SEQ', 'B_ENT', 'KEY', 'VAL') + + +class Parent(object): + def __init__(self, type, indent, line_indent=None): + self.type = type + self.indent = indent + self.line_indent = line_indent + self.explicit_key = False + self.implicit_block_seq = False + + def __repr__(self): + return '%s:%d' % (labels[self.type], self.indent) + + +def check_scalar_indentation(conf, token, context): + if token.start_mark.line == token.end_mark.line: + return + + def compute_expected_indent(found_indent): + def detect_indent(base_indent): + if not isinstance(context['spaces'], int): + context['spaces'] = found_indent - base_indent + return base_indent + context['spaces'] + + if token.plain: + return token.start_mark.column + elif token.style in ('"', "'"): + return token.start_mark.column + 1 + elif token.style in ('>', '|'): + if context['stack'][-1].type == B_ENT: + # - > + # multi + # line + return detect_indent(token.start_mark.column) + elif context['stack'][-1].type == KEY: + assert context['stack'][-1].explicit_key + # - ? > + # multi-line + # key + # : > + # multi-line + # value + return detect_indent(token.start_mark.column) + elif context['stack'][-1].type == VAL: + if token.start_mark.line + 1 > context['cur_line']: + # - key: + # > + # multi + # line + return detect_indent(context['stack'][-1].indent) + elif context['stack'][-2].explicit_key: + # - ? key + # : > + # multi-line + # value + return detect_indent(token.start_mark.column) + else: + # - key: > + # multi + # line + return detect_indent(context['stack'][-2].indent) + else: + return detect_indent(context['stack'][-1].indent) + + expected_indent = None + + line_no = token.start_mark.line + 1 + + line_start = token.start_mark.pointer + while True: + line_start = token.start_mark.buffer.find( + '\n', line_start, token.end_mark.pointer - 1) + 1 + if line_start == 0: + break + line_no += 1 + + indent = 0 + while token.start_mark.buffer[line_start + indent] == ' ': + indent += 1 + if token.start_mark.buffer[line_start + indent] == '\n': + continue + + if expected_indent is None: + expected_indent = compute_expected_indent(indent) + + if indent != expected_indent: + yield LintProblem(line_no, indent + 1, + 'wrong indentation: expected %d but found %d' % + (expected_indent, indent)) + + +def _check(conf, token, prev, next, nextnext, context): + if 'stack' not in context: + context['stack'] = [Parent(ROOT, 0)] + context['cur_line'] = -1 + context['spaces'] = conf['spaces'] + context['indent-sequences'] = conf['indent-sequences'] + + # Step 1: Lint + + is_visible = ( + not isinstance(token, (yaml.StreamStartToken, yaml.StreamEndToken)) and + not isinstance(token, yaml.BlockEndToken) and + not (isinstance(token, yaml.ScalarToken) and token.value == '')) + first_in_line = (is_visible and + token.start_mark.line + 1 > context['cur_line']) + + def detect_indent(base_indent, next): + if not isinstance(context['spaces'], int): + context['spaces'] = next.start_mark.column - base_indent + return base_indent + context['spaces'] + + if first_in_line: + found_indentation = token.start_mark.column + expected = context['stack'][-1].indent + + if isinstance(token, (yaml.FlowMappingEndToken, + yaml.FlowSequenceEndToken)): + expected = context['stack'][-1].line_indent + elif (context['stack'][-1].type == KEY and + context['stack'][-1].explicit_key and + not isinstance(token, yaml.ValueToken)): + expected = detect_indent(expected, token) + + if found_indentation != expected: + yield LintProblem(token.start_mark.line + 1, found_indentation + 1, + 'wrong indentation: expected %d but found %d' % + (expected, found_indentation)) + + if (isinstance(token, yaml.ScalarToken) and + conf['check-multi-line-strings']): + for problem in check_scalar_indentation(conf, token, context): + yield problem + + # Step 2.a: + + if is_visible: + context['cur_line'] = get_real_end_line(token) + if first_in_line: + context['cur_line_indent'] = found_indentation + + # Step 2.b: Update state + + if isinstance(token, yaml.BlockMappingStartToken): + # - a: 1 + # or + # - ? a + # : 1 + # or + # - ? + # a + # : 1 + assert isinstance(next, yaml.KeyToken) + assert next.start_mark.line == token.start_mark.line + + indent = token.start_mark.column + + context['stack'].append(Parent(B_MAP, indent)) + + elif isinstance(token, yaml.FlowMappingStartToken): + if next.start_mark.line == token.start_mark.line: + # - {a: 1, b: 2} + indent = next.start_mark.column + else: + # - { + # a: 1, b: 2 + # } + indent = detect_indent(context['cur_line_indent'], next) + + context['stack'].append(Parent(F_MAP, indent, + line_indent=context['cur_line_indent'])) + + elif isinstance(token, yaml.BlockSequenceStartToken): + # - - a + # - b + assert isinstance(next, yaml.BlockEntryToken) + assert next.start_mark.line == token.start_mark.line + + indent = token.start_mark.column + + context['stack'].append(Parent(B_SEQ, indent)) + + elif (isinstance(token, yaml.BlockEntryToken) and + # in case of an empty entry + not isinstance(next, (yaml.BlockEntryToken, yaml.BlockEndToken))): + # It looks like pyyaml doesn't issue BlockSequenceStartTokens when the + # list is not indented. We need to compensate that. + if context['stack'][-1].type != B_SEQ: + context['stack'].append(Parent(B_SEQ, token.start_mark.column)) + context['stack'][-1].implicit_block_seq = True + + if next.start_mark.line == token.end_mark.line: + # - item 1 + # - item 2 + indent = next.start_mark.column + elif next.start_mark.column == token.start_mark.column: + # - + # key: value + indent = next.start_mark.column + else: + # - + # item 1 + # - + # key: + # value + indent = detect_indent(token.start_mark.column, next) + + context['stack'].append(Parent(B_ENT, indent)) + + elif isinstance(token, yaml.FlowSequenceStartToken): + if next.start_mark.line == token.start_mark.line: + # - [a, b] + indent = next.start_mark.column + else: + # - [ + # a, b + # ] + indent = detect_indent(context['cur_line_indent'], next) + + context['stack'].append(Parent(F_SEQ, indent, + line_indent=context['cur_line_indent'])) + + elif isinstance(token, yaml.KeyToken): + indent = context['stack'][-1].indent + + context['stack'].append(Parent(KEY, indent)) + + context['stack'][-1].explicit_key = is_explicit_key(token) + + elif isinstance(token, yaml.ValueToken): + assert context['stack'][-1].type == KEY + + # Special cases: + # key: &anchor + # value + # and: + # key: !!tag + # value + if isinstance(next, (yaml.AnchorToken, yaml.TagToken)): + if (next.start_mark.line == prev.start_mark.line and + next.start_mark.line < nextnext.start_mark.line): + next = nextnext + + # Only if value is not empty + if not isinstance(next, (yaml.BlockEndToken, + yaml.FlowMappingEndToken, + yaml.FlowSequenceEndToken, + yaml.KeyToken)): + if context['stack'][-1].explicit_key: + # ? k + # : value + # or + # ? k + # : + # value + indent = detect_indent(context['stack'][-1].indent, next) + elif next.start_mark.line == prev.start_mark.line: + # k: value + indent = next.start_mark.column + elif isinstance(next, (yaml.BlockSequenceStartToken, + yaml.BlockEntryToken)): + # NOTE: We add BlockEntryToken in the test above because + # sometimes BlockSequenceStartToken are not issued. Try + # yaml.scan()ning this: + # '- lib:\n' + # ' - var\n' + if context['indent-sequences'] is False: + indent = context['stack'][-1].indent + elif context['indent-sequences'] is True: + if (context['spaces'] == 'consistent' and + next.start_mark.column - + context['stack'][-1].indent == 0): + # In this case, the block sequence item is not indented + # (while it should be), but we don't know yet the + # indentation it should have (because `spaces` is + # `consistent` and its value has not been computed yet + # -- this is probably the beginning of the document). + # So we choose an arbitrary value (2). + indent = 2 + else: + indent = detect_indent(context['stack'][-1].indent, + next) + else: # 'whatever' or 'consistent' + if next.start_mark.column == context['stack'][-1].indent: + # key: + # - e1 + # - e2 + if context['indent-sequences'] == 'consistent': + context['indent-sequences'] = False + indent = context['stack'][-1].indent + else: + if context['indent-sequences'] == 'consistent': + context['indent-sequences'] = True + # key: + # - e1 + # - e2 + indent = detect_indent(context['stack'][-1].indent, + next) + else: + # k: + # value + indent = detect_indent(context['stack'][-1].indent, next) + + context['stack'].append(Parent(VAL, indent)) + + consumed_current_token = False + while True: + if (context['stack'][-1].type == F_SEQ and + isinstance(token, yaml.FlowSequenceEndToken) and + not consumed_current_token): + context['stack'].pop() + consumed_current_token = True + + elif (context['stack'][-1].type == F_MAP and + isinstance(token, yaml.FlowMappingEndToken) and + not consumed_current_token): + context['stack'].pop() + consumed_current_token = True + + elif (context['stack'][-1].type in (B_MAP, B_SEQ) and + isinstance(token, yaml.BlockEndToken) and + not context['stack'][-1].implicit_block_seq and + not consumed_current_token): + context['stack'].pop() + consumed_current_token = True + + elif (context['stack'][-1].type == B_ENT and + not isinstance(token, yaml.BlockEntryToken) and + context['stack'][-2].implicit_block_seq and + not isinstance(token, (yaml.AnchorToken, yaml.TagToken)) and + not isinstance(next, yaml.BlockEntryToken)): + context['stack'].pop() + context['stack'].pop() + + elif (context['stack'][-1].type == B_ENT and + isinstance(next, (yaml.BlockEntryToken, yaml.BlockEndToken))): + context['stack'].pop() + + elif (context['stack'][-1].type == VAL and + not isinstance(token, yaml.ValueToken) and + not isinstance(token, (yaml.AnchorToken, yaml.TagToken))): + assert context['stack'][-2].type == KEY + context['stack'].pop() + context['stack'].pop() + + elif (context['stack'][-1].type == KEY and + isinstance(next, (yaml.BlockEndToken, + yaml.FlowMappingEndToken, + yaml.FlowSequenceEndToken, + yaml.KeyToken))): + # A key without a value: it's part of a set. Let's drop this key + # and leave room for the next one. + context['stack'].pop() + + else: + break + + +def check(conf, token, prev, next, nextnext, context): + try: + for problem in _check(conf, token, prev, next, nextnext, context): + yield problem + except AssertionError: + yield LintProblem(token.start_mark.line + 1, + token.start_mark.column + 1, + 'cannot infer indentation: unexpected token') diff --git a/third_party/python/yamllint/yamllint/rules/key_duplicates.py b/third_party/python/yamllint/yamllint/rules/key_duplicates.py new file mode 100644 index 0000000000..bd38b14345 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/key_duplicates.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to prevent multiple entries with the same key in mappings. + +.. rubric:: Examples + +#. With ``key-duplicates: {}`` + + the following code snippet would **PASS**: + :: + + - key 1: v + key 2: val + key 3: value + - {a: 1, b: 2, c: 3} + + the following code snippet would **FAIL**: + :: + + - key 1: v + key 2: val + key 1: value + + the following code snippet would **FAIL**: + :: + + - {a: 1, b: 2, b: 3} + + the following code snippet would **FAIL**: + :: + + duplicated key: 1 + "duplicated key": 2 + + other duplication: 1 + ? >- + other + duplication + : 2 +""" + +import yaml + +from yamllint.linter import LintProblem + + +ID = 'key-duplicates' +TYPE = 'token' + +MAP, SEQ = range(2) + + +class Parent(object): + def __init__(self, type): + self.type = type + self.keys = [] + + +def check(conf, token, prev, next, nextnext, context): + if 'stack' not in context: + context['stack'] = [] + + if isinstance(token, (yaml.BlockMappingStartToken, + yaml.FlowMappingStartToken)): + context['stack'].append(Parent(MAP)) + elif isinstance(token, (yaml.BlockSequenceStartToken, + yaml.FlowSequenceStartToken)): + context['stack'].append(Parent(SEQ)) + elif isinstance(token, (yaml.BlockEndToken, + yaml.FlowMappingEndToken, + yaml.FlowSequenceEndToken)): + context['stack'].pop() + elif (isinstance(token, yaml.KeyToken) and + isinstance(next, yaml.ScalarToken)): + # This check is done because KeyTokens can be found inside flow + # sequences... strange, but allowed. + if len(context['stack']) > 0 and context['stack'][-1].type == MAP: + if (next.value in context['stack'][-1].keys and + # `<<` is "merge key", see http://yaml.org/type/merge.html + next.value != '<<'): + yield LintProblem( + next.start_mark.line + 1, next.start_mark.column + 1, + 'duplication of key "%s" in mapping' % next.value) + else: + context['stack'][-1].keys.append(next.value) diff --git a/third_party/python/yamllint/yamllint/rules/key_ordering.py b/third_party/python/yamllint/yamllint/rules/key_ordering.py new file mode 100644 index 0000000000..1ca992b66e --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/key_ordering.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2017 Johannes F. Knauf +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to enforce alphabetical ordering of keys in mappings. The sorting +order uses the Unicode code point number. As a result, the ordering is +case-sensitive and not accent-friendly (see examples below). + +.. rubric:: Examples + +#. With ``key-ordering: {}`` + + the following code snippet would **PASS**: + :: + + - key 1: v + key 2: val + key 3: value + - {a: 1, b: 2, c: 3} + - T-shirt: 1 + T-shirts: 2 + t-shirt: 3 + t-shirts: 4 + - hair: true + hais: true + haïr: true + haïssable: true + + the following code snippet would **FAIL**: + :: + + - key 2: v + key 1: val + + the following code snippet would **FAIL**: + :: + + - {b: 1, a: 2} + + the following code snippet would **FAIL**: + :: + + - T-shirt: 1 + t-shirt: 2 + T-shirts: 3 + t-shirts: 4 + + the following code snippet would **FAIL**: + :: + + - haïr: true + hais: true +""" + +import yaml + +from yamllint.linter import LintProblem + + +ID = 'key-ordering' +TYPE = 'token' + +MAP, SEQ = range(2) + + +class Parent(object): + def __init__(self, type): + self.type = type + self.keys = [] + + +def check(conf, token, prev, next, nextnext, context): + if 'stack' not in context: + context['stack'] = [] + + if isinstance(token, (yaml.BlockMappingStartToken, + yaml.FlowMappingStartToken)): + context['stack'].append(Parent(MAP)) + elif isinstance(token, (yaml.BlockSequenceStartToken, + yaml.FlowSequenceStartToken)): + context['stack'].append(Parent(SEQ)) + elif isinstance(token, (yaml.BlockEndToken, + yaml.FlowMappingEndToken, + yaml.FlowSequenceEndToken)): + context['stack'].pop() + elif (isinstance(token, yaml.KeyToken) and + isinstance(next, yaml.ScalarToken)): + # This check is done because KeyTokens can be found inside flow + # sequences... strange, but allowed. + if len(context['stack']) > 0 and context['stack'][-1].type == MAP: + if any(next.value < key for key in context['stack'][-1].keys): + yield LintProblem( + next.start_mark.line + 1, next.start_mark.column + 1, + 'wrong ordering of key "%s" in mapping' % next.value) + else: + context['stack'][-1].keys.append(next.value) diff --git a/third_party/python/yamllint/yamllint/rules/line_length.py b/third_party/python/yamllint/yamllint/rules/line_length.py new file mode 100644 index 0000000000..9b5a1ab687 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/line_length.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to set a limit to lines length. + +Note: with Python 2, the ``line-length`` rule may not work properly with +unicode characters because of the way strings are represented in bytes. We +recommend running yamllint with Python 3. + +.. rubric:: Options + +* ``max`` defines the maximal (inclusive) length of lines. +* ``allow-non-breakable-words`` is used to allow non breakable words (without + spaces inside) to overflow the limit. This is useful for long URLs, for + instance. Use ``true`` to allow, ``false`` to forbid. +* ``allow-non-breakable-inline-mappings`` implies ``allow-non-breakable-words`` + and extends it to also allow non-breakable words in inline mappings. + +.. rubric:: Examples + +#. With ``line-length: {max: 70}`` + + the following code snippet would **PASS**: + :: + + long sentence: + Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do + eiusmod tempor incididunt ut labore et dolore magna aliqua. + + the following code snippet would **FAIL**: + :: + + long sentence: + Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod + tempor incididunt ut labore et dolore magna aliqua. + +#. With ``line-length: {max: 60, allow-non-breakable-words: true}`` + + the following code snippet would **PASS**: + :: + + this: + is: + - a: + http://localhost/very/very/very/very/very/very/very/very/long/url + + # this comment is too long, + # but hard to split: + # http://localhost/another/very/very/very/very/very/very/very/very/long/url + + the following code snippet would **FAIL**: + :: + + - this line is waaaaaaaaaaaaaay too long but could be easily split... + + and the following code snippet would also **FAIL**: + :: + + - foobar: http://localhost/very/very/very/very/very/very/very/very/long/url + +#. With ``line-length: {max: 60, allow-non-breakable-words: true, + allow-non-breakable-inline-mappings: true}`` + + the following code snippet would **PASS**: + :: + + - foobar: http://localhost/very/very/very/very/very/very/very/very/long/url + +#. With ``line-length: {max: 60, allow-non-breakable-words: false}`` + + the following code snippet would **FAIL**: + :: + + this: + is: + - a: + http://localhost/very/very/very/very/very/very/very/very/long/url +""" + + +import yaml + +from yamllint.linter import LintProblem + + +ID = 'line-length' +TYPE = 'line' +CONF = {'max': int, + 'allow-non-breakable-words': bool, + 'allow-non-breakable-inline-mappings': bool} +DEFAULT = {'max': 80, + 'allow-non-breakable-words': True, + 'allow-non-breakable-inline-mappings': False} + + +def check_inline_mapping(line): + loader = yaml.SafeLoader(line.content) + try: + while loader.peek_token(): + if isinstance(loader.get_token(), yaml.BlockMappingStartToken): + while loader.peek_token(): + if isinstance(loader.get_token(), yaml.ValueToken): + t = loader.get_token() + if isinstance(t, yaml.ScalarToken): + return ( + ' ' not in line.content[t.start_mark.column:]) + except yaml.scanner.ScannerError: + pass + + return False + + +def check(conf, line): + if line.end - line.start > conf['max']: + conf['allow-non-breakable-words'] |= \ + conf['allow-non-breakable-inline-mappings'] + if conf['allow-non-breakable-words']: + start = line.start + while start < line.end and line.buffer[start] == ' ': + start += 1 + + if start != line.end: + if line.buffer[start] in ('#', '-'): + start += 2 + + if line.buffer.find(' ', start, line.end) == -1: + return + + if (conf['allow-non-breakable-inline-mappings'] and + check_inline_mapping(line)): + return + + yield LintProblem(line.line_no, conf['max'] + 1, + 'line too long (%d > %d characters)' % + (line.end - line.start, conf['max'])) diff --git a/third_party/python/yamllint/yamllint/rules/new_line_at_end_of_file.py b/third_party/python/yamllint/yamllint/rules/new_line_at_end_of_file.py new file mode 100644 index 0000000000..90b1cc2ae7 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/new_line_at_end_of_file.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to require a new line character (``\\n``) at the end of files. + +The POSIX standard `requires the last line to end with a new line character +`_. +All UNIX tools expect a new line at the end of files. Most text editors use +this convention too. +""" + + +from yamllint.linter import LintProblem + + +ID = 'new-line-at-end-of-file' +TYPE = 'line' + + +def check(conf, line): + if line.end == len(line.buffer) and line.end > line.start: + yield LintProblem(line.line_no, line.end - line.start + 1, + 'no new line character at the end of file') diff --git a/third_party/python/yamllint/yamllint/rules/new_lines.py b/third_party/python/yamllint/yamllint/rules/new_lines.py new file mode 100644 index 0000000000..686bac244b --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/new_lines.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to force the type of new line characters. + +.. rubric:: Options + +* Set ``type`` to ``unix`` to use UNIX-typed new line characters (``\\n``), or + ``dos`` to use DOS-typed new line characters (``\\r\\n``). +""" + + +from yamllint.linter import LintProblem + + +ID = 'new-lines' +TYPE = 'line' +CONF = {'type': ('unix', 'dos')} +DEFAULT = {'type': 'unix'} + + +def check(conf, line): + if line.start == 0 and len(line.buffer) > line.end: + if conf['type'] == 'dos': + if (line.end + 2 > len(line.buffer) or + line.buffer[line.end:line.end + 2] != '\r\n'): + yield LintProblem(1, line.end - line.start + 1, + 'wrong new line character: expected \\r\\n') + else: + if line.buffer[line.end] == '\r': + yield LintProblem(1, line.end - line.start + 1, + 'wrong new line character: expected \\n') diff --git a/third_party/python/yamllint/yamllint/rules/octal_values.py b/third_party/python/yamllint/yamllint/rules/octal_values.py new file mode 100644 index 0000000000..f6e80cef56 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/octal_values.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2017 ScienJus +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to prevent values with octal numbers. In YAML, numbers that +start with ``0`` are interpreted as octal, but this is not always wanted. +For instance ``010`` is the city code of Beijing, and should not be +converted to ``8``. + +.. rubric:: Examples + +#. With ``octal-values: {forbid-implicit-octal: true}`` + + the following code snippets would **PASS**: + :: + + user: + city-code: '010' + + the following code snippets would **PASS**: + :: + + user: + city-code: 010,021 + + the following code snippets would **FAIL**: + :: + + user: + city-code: 010 + +#. With ``octal-values: {forbid-explicit-octal: true}`` + + the following code snippets would **PASS**: + :: + + user: + city-code: '0o10' + + the following code snippets would **FAIL**: + :: + + user: + city-code: 0o10 +""" + +import yaml + +from yamllint.linter import LintProblem + + +ID = 'octal-values' +TYPE = 'token' +CONF = {'forbid-implicit-octal': bool, + 'forbid-explicit-octal': bool} +DEFAULT = {'forbid-implicit-octal': True, + 'forbid-explicit-octal': True} + + +def check(conf, token, prev, next, nextnext, context): + if prev and isinstance(prev, yaml.tokens.TagToken): + return + + if conf['forbid-implicit-octal']: + if isinstance(token, yaml.tokens.ScalarToken): + if not token.style: + val = token.value + if val.isdigit() and len(val) > 1 and val[0] == '0': + yield LintProblem( + token.start_mark.line + 1, token.end_mark.column + 1, + 'forbidden implicit octal value "%s"' % + token.value) + + if conf['forbid-explicit-octal']: + if isinstance(token, yaml.tokens.ScalarToken): + if not token.style: + val = token.value + if len(val) > 2 and val[:2] == '0o' and val[2:].isdigit(): + yield LintProblem( + token.start_mark.line + 1, token.end_mark.column + 1, + 'forbidden explicit octal value "%s"' % + token.value) diff --git a/third_party/python/yamllint/yamllint/rules/quoted_strings.py b/third_party/python/yamllint/yamllint/rules/quoted_strings.py new file mode 100644 index 0000000000..1d997294da --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/quoted_strings.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2018 ClearScore +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to forbid any string values that are not quoted, or to prevent +quoted strings without needing it. You can also enforce the type of the quote +used. + +.. rubric:: Options + +* ``quote-type`` defines allowed quotes: ``single``, ``double`` or ``any`` + (default). +* ``required`` defines whether using quotes in string values is required + (``true``, default) or not (``false``), or only allowed when really needed + (``only-when-needed``). +* ``extra-required`` is a list of PCRE regexes to force string values to be + quoted, if they match any regex. This option can only be used with + ``required: false`` and ``required: only-when-needed``. +* ``extra-allowed`` is a list of PCRE regexes to allow quoted string values, + even if ``required: only-when-needed`` is set. + +**Note**: Multi-line strings (with ``|`` or ``>``) will not be checked. + +.. rubric:: Examples + +#. With ``quoted-strings: {quote-type: any, required: true}`` + + the following code snippet would **PASS**: + :: + + foo: "bar" + bar: 'foo' + number: 123 + boolean: true + + the following code snippet would **FAIL**: + :: + + foo: bar + +#. With ``quoted-strings: {quote-type: single, required: only-when-needed}`` + + the following code snippet would **PASS**: + :: + + foo: bar + bar: foo + not_number: '123' + not_boolean: 'true' + not_comment: '# comment' + not_list: '[1, 2, 3]' + not_map: '{a: 1, b: 2}' + + the following code snippet would **FAIL**: + :: + + foo: 'bar' + +#. With ``quoted-strings: {required: false, extra-required: [^http://, + ^ftp://]}`` + + the following code snippet would **PASS**: + :: + + - localhost + - "localhost" + - "http://localhost" + - "ftp://localhost" + + the following code snippet would **FAIL**: + :: + + - http://localhost + - ftp://localhost + +#. With ``quoted-strings: {required: only-when-needed, extra-allowed: + [^http://, ^ftp://], extra-required: [QUOTED]}`` + + the following code snippet would **PASS**: + :: + + - localhost + - "http://localhost" + - "ftp://localhost" + - "this is a string that needs to be QUOTED" + + the following code snippet would **FAIL**: + :: + + - "localhost" + - this is a string that needs to be QUOTED +""" + +import re + +import yaml + +from yamllint.linter import LintProblem + +ID = 'quoted-strings' +TYPE = 'token' +CONF = {'quote-type': ('any', 'single', 'double'), + 'required': (True, False, 'only-when-needed'), + 'extra-required': [str], + 'extra-allowed': [str]} +DEFAULT = {'quote-type': 'any', + 'required': True, + 'extra-required': [], + 'extra-allowed': []} + + +def VALIDATE(conf): + if conf['required'] is True and len(conf['extra-allowed']) > 0: + return 'cannot use both "required: true" and "extra-allowed"' + if conf['required'] is True and len(conf['extra-required']) > 0: + return 'cannot use both "required: true" and "extra-required"' + if conf['required'] is False and len(conf['extra-allowed']) > 0: + return 'cannot use both "required: false" and "extra-allowed"' + + +DEFAULT_SCALAR_TAG = u'tag:yaml.org,2002:str' + + +def _quote_match(quote_type, token_style): + return ((quote_type == 'any') or + (quote_type == 'single' and token_style == "'") or + (quote_type == 'double' and token_style == '"')) + + +def _quotes_are_needed(string): + loader = yaml.BaseLoader('key: ' + string) + # Remove the 5 first tokens corresponding to 'key: ' (StreamStartToken, + # BlockMappingStartToken, KeyToken, ScalarToken(value=key), ValueToken) + for _ in range(5): + loader.get_token() + try: + a, b = loader.get_token(), loader.get_token() + if (isinstance(a, yaml.ScalarToken) and a.style is None and + isinstance(b, yaml.BlockEndToken)): + return False + return True + except yaml.scanner.ScannerError: + return True + + +def check(conf, token, prev, next, nextnext, context): + if not (isinstance(token, yaml.tokens.ScalarToken) and + isinstance(prev, (yaml.BlockEntryToken, yaml.FlowEntryToken, + yaml.FlowSequenceStartToken, yaml.TagToken, + yaml.ValueToken))): + + return + + # Ignore explicit types, e.g. !!str testtest or !!int 42 + if (prev and isinstance(prev, yaml.tokens.TagToken) and + prev.value[0] == '!!'): + return + + # Ignore numbers, booleans, etc. + resolver = yaml.resolver.Resolver() + tag = resolver.resolve(yaml.nodes.ScalarNode, token.value, (True, False)) + if token.plain and tag != DEFAULT_SCALAR_TAG: + return + + # Ignore multi-line strings + if (not token.plain) and (token.style == "|" or token.style == ">"): + return + + quote_type = conf['quote-type'] + + msg = None + if conf['required'] is True: + + # Quotes are mandatory and need to match config + if token.style is None or not _quote_match(quote_type, token.style): + msg = "string value is not quoted with %s quotes" % quote_type + + elif conf['required'] is False: + + # Quotes are not mandatory but when used need to match config + if token.style and not _quote_match(quote_type, token.style): + msg = "string value is not quoted with %s quotes" % quote_type + + elif not token.style: + is_extra_required = any(re.search(r, token.value) + for r in conf['extra-required']) + if is_extra_required: + msg = "string value is not quoted" + + elif conf['required'] == 'only-when-needed': + + # Quotes are not strictly needed here + if (token.style and tag == DEFAULT_SCALAR_TAG and token.value and + not _quotes_are_needed(token.value)): + is_extra_required = any(re.search(r, token.value) + for r in conf['extra-required']) + is_extra_allowed = any(re.search(r, token.value) + for r in conf['extra-allowed']) + if not (is_extra_required or is_extra_allowed): + msg = "string value is redundantly quoted with %s quotes" % ( + quote_type) + + # But when used need to match config + elif token.style and not _quote_match(quote_type, token.style): + msg = "string value is not quoted with %s quotes" % quote_type + + elif not token.style: + is_extra_required = len(conf['extra-required']) and any( + re.search(r, token.value) for r in conf['extra-required']) + if is_extra_required: + msg = "string value is not quoted" + + if msg is not None: + yield LintProblem( + token.start_mark.line + 1, + token.start_mark.column + 1, + msg) diff --git a/third_party/python/yamllint/yamllint/rules/trailing_spaces.py b/third_party/python/yamllint/yamllint/rules/trailing_spaces.py new file mode 100644 index 0000000000..2fc4bbba03 --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/trailing_spaces.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Adrien Vergé +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to forbid trailing spaces at the end of lines. + +.. rubric:: Examples + +#. With ``trailing-spaces: {}`` + + the following code snippet would **PASS**: + :: + + this document doesn't contain + any trailing + spaces + + the following code snippet would **FAIL**: + :: + + this document contains """ """ + trailing spaces + on lines 1 and 3 """ """ +""" + + +import string + +from yamllint.linter import LintProblem + + +ID = 'trailing-spaces' +TYPE = 'line' + + +def check(conf, line): + if line.end == 0: + return + + # YAML recognizes two white space characters: space and tab. + # http://yaml.org/spec/1.2/spec.html#id2775170 + + pos = line.end + while line.buffer[pos - 1] in string.whitespace and pos > line.start: + pos -= 1 + + if pos != line.end and line.buffer[pos] in ' \t': + yield LintProblem(line.line_no, pos - line.start + 1, + 'trailing spaces') diff --git a/third_party/python/yamllint/yamllint/rules/truthy.py b/third_party/python/yamllint/yamllint/rules/truthy.py new file mode 100644 index 0000000000..64ccaaa45c --- /dev/null +++ b/third_party/python/yamllint/yamllint/rules/truthy.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2016 Peter Ericson +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Use this rule to forbid non-explictly typed truthy values other than allowed +ones (by default: ``true`` and ``false``), for example ``YES`` or ``off``. + +This can be useful to prevent surprises from YAML parsers transforming +``[yes, FALSE, Off]`` into ``[true, false, false]`` or +``{y: 1, yes: 2, on: 3, true: 4, True: 5}`` into ``{y: 1, true: 5}``. + +.. rubric:: Options + +* ``allowed-values`` defines the list of truthy values which will be ignored + during linting. The default is ``['true', 'false']``, but can be changed to + any list containing: ``'TRUE'``, ``'True'``, ``'true'``, ``'FALSE'``, + ``'False'``, ``'false'``, ``'YES'``, ``'Yes'``, ``'yes'``, ``'NO'``, + ``'No'``, ``'no'``, ``'ON'``, ``'On'``, ``'on'``, ``'OFF'``, ``'Off'``, + ``'off'``. +* ``check-keys`` disables verification for keys in mappings. By default, + ``truthy`` rule applies to both keys and values. Set this option to ``false`` + to prevent this. + +.. rubric:: Examples + +#. With ``truthy: {}`` + + the following code snippet would **PASS**: + :: + + boolean: true + + object: {"True": 1, 1: "True"} + + "yes": 1 + "on": 2 + "True": 3 + + explicit: + string1: !!str True + string2: !!str yes + string3: !!str off + encoded: !!binary | + True + OFF + pad== # this decodes as 'N\xbb\x9e8Qii' + boolean1: !!bool true + boolean2: !!bool "false" + boolean3: !!bool FALSE + boolean4: !!bool True + boolean5: !!bool off + boolean6: !!bool NO + + the following code snippet would **FAIL**: + :: + + object: {True: 1, 1: True} + + the following code snippet would **FAIL**: + :: + + yes: 1 + on: 2 + True: 3 + +#. With ``truthy: {allowed-values: ["yes", "no"]}`` + + the following code snippet would **PASS**: + :: + + - yes + - no + - "true" + - 'false' + - foo + - bar + + the following code snippet would **FAIL**: + :: + + - true + - false + - on + - off + +#. With ``truthy: {check-keys: false}`` + + the following code snippet would **PASS**: + :: + + yes: 1 + on: 2 + true: 3 + + the following code snippet would **FAIL**: + :: + + yes: Yes + on: On + true: True +""" + +import yaml + +from yamllint.linter import LintProblem + + +TRUTHY = ['YES', 'Yes', 'yes', + 'NO', 'No', 'no', + 'TRUE', 'True', 'true', + 'FALSE', 'False', 'false', + 'ON', 'On', 'on', + 'OFF', 'Off', 'off'] + + +ID = 'truthy' +TYPE = 'token' +CONF = {'allowed-values': list(TRUTHY), 'check-keys': bool} +DEFAULT = {'allowed-values': ['true', 'false'], 'check-keys': True} + + +def check(conf, token, prev, next, nextnext, context): + if prev and isinstance(prev, yaml.tokens.TagToken): + return + + if (not conf['check-keys'] and isinstance(prev, yaml.tokens.KeyToken) and + isinstance(token, yaml.tokens.ScalarToken)): + return + + if isinstance(token, yaml.tokens.ScalarToken): + if (token.value in (set(TRUTHY) - set(conf['allowed-values'])) and + token.style is None): + yield LintProblem(token.start_mark.line + 1, + token.start_mark.column + 1, + "truthy value should be one of [" + + ", ".join(sorted(conf['allowed-values'])) + "]") -- cgit v1.2.3