diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 18373e8..0000000 --- a/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -*.pyc -*.sw? -*~ -.coverage -.eggs/ -__pycache__ -*.egg-info/ -version.txt -build/ -dist/ diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 7a5c79d..0000000 --- a/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -Copyright (C) 2015-2016 The Software Heritage developers - -See http://www.softwareheritage.org/ for more information. diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 94a9ed0..0000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - 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/PKG-INFO b/PKG-INFO index 1c34d1b..2c3b753 100644 --- a/PKG-INFO +++ b/PKG-INFO @@ -1,130 +1,130 @@ Metadata-Version: 2.1 Name: swh.loader.mercurial -Version: 0.0.14 +Version: 0.0.16 Summary: Software Heritage Mercurial Loader Home-page: https://forge.softwareheritage.org/diffusion/DLDHG/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN -Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest Project-URL: Funding, https://www.softwareheritage.org/donate Project-URL: Source, https://forge.softwareheritage.org/source/swh-loader-mercurial +Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest Description: swh-loader-mercurial ========================= # Configuration file In usual location for a loader, *{/etc/softwareheritage/ | ~/.swh/ | ~/.config/swh/}loader/hg.yml*: ``` YAML storage: cls: remote args: url: http://localhost:5002/ ``` # Basic use The main entry point to import a Mercurial repository is the `main` function defined in the `swh.loader.mercurial.cli` module: ``` bash python3 -m swh.loader.mercurial.cli ``` If the Python package has been installed via `pip`, you should be able to type: ``` bash user@host:~$ swh-loader-hg --help Usage: swh-loader-hg [OPTIONS] ORIGIN_URL Options: -d, --hg-directory TEXT Path to the hg (local) directory to load from. If unset, the hg repo will ben cloned from the given (origin) url -a, --hg-archive TEXT Path to the hg (local) archive file to load from. -D, --visit-date TEXT Visit date (defaults to now) -l, --log-level [NOTSET|DEBUG|INFO|WARNING|ERROR|CRITICAL] Log level --help Show this message and exit. ``` For example: ``` bash user@host:~$ swh-loader-hg https://www.mercurial-scm.org/repo/hello [...] ``` # From Python From python3's toplevel: ## Remote ``` Python project = 'hello' # remote repository origin_url = 'https://www.mercurial-scm.org/repo/%s' % project # local clone directory = '/home/storage/hg/repo/%s' % project import logging logging.basicConfig(level=logging.DEBUG) from swh.loader.mercurial.tasks import LoadMercurial t = LoadMercurial() t.run(origin_url=origin_url, directory=directory, visit_date='2016-05-03T15:16:32+00:00') ``` ## local directory Only origin, contents, and directories are filled so far. Remaining objects are empty (revision, release, occurrence). ``` Python project = '756015-ipv6' directory = '/home/storage/hg/repo/%s' % project origin_url = 'https://%s.googlecode.com' % project import logging logging.basicConfig(level=logging.DEBUG) from swh.loader.mercurial.tasks import LoadMercurial t = LoadMercurial() t.run(origin_url=origin_url, directory=directory, visit_date='2016-05-03T15:16:32+00:00') ``` ## local archive ``` Python project = '756015-ipv6-source-archive.zip' archive_path = '/home/storage/hg/repo/%s' % project origin_url = 'https://%s-archive.googlecode.com' % project import logging logging.basicConfig(level=logging.DEBUG) from swh.loader.mercurial.tasks import LoadArchiveMercurial t = LoadArchiveMercurial() t.run(origin_url=origin_url, archive_path=archive_path, visit_date='2016-05-03T15:16:32+00:00') ``` Platform: UNKNOWN Classifier: Programming Language :: Python :: 3 Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: OS Independent Classifier: Development Status :: 4 - Beta Description-Content-Type: text/markdown Provides-Extra: testing diff --git a/docs/.gitignore b/docs/.gitignore deleted file mode 100644 index 58a761e..0000000 --- a/docs/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -_build/ -apidoc/ -*-stamp diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index c30c50a..0000000 --- a/docs/Makefile +++ /dev/null @@ -1 +0,0 @@ -include ../../swh-docs/Makefile.sphinx diff --git a/docs/_static/.placeholder b/docs/_static/.placeholder deleted file mode 100644 index e69de29..0000000 diff --git a/docs/_templates/.placeholder b/docs/_templates/.placeholder deleted file mode 100644 index e69de29..0000000 diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index 190deb7..0000000 --- a/docs/conf.py +++ /dev/null @@ -1 +0,0 @@ -from swh.docs.sphinx.conf import * # NoQA diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index 6901dfc..0000000 --- a/docs/index.rst +++ /dev/null @@ -1,19 +0,0 @@ -.. _swh-loader-mercurial: - -Software Heritage - Mercurial loader -==================================== - -Loader for `Mercurial `_ repositories. - - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/requirements-swh.txt b/requirements-swh.txt index 0c28121..2f24ad2 100644 --- a/requirements-swh.txt +++ b/requirements-swh.txt @@ -1,5 +1,5 @@ swh.core >= 0.0.36 swh.model >= 0.0.27 -swh.storage >= 0.0.95 -swh.scheduler >= 0.0.19 -swh.loader.core >= 0.0.34 +swh.storage >= 0.0.114 +swh.scheduler >= 0.0.39 +swh.loader.core >= 0.0.37 diff --git a/requirements-test.txt b/requirements-test.txt deleted file mode 100644 index f3c7e8e..0000000 --- a/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -nose diff --git a/swh.loader.mercurial.egg-info/PKG-INFO b/swh.loader.mercurial.egg-info/PKG-INFO index 1c34d1b..2c3b753 100644 --- a/swh.loader.mercurial.egg-info/PKG-INFO +++ b/swh.loader.mercurial.egg-info/PKG-INFO @@ -1,130 +1,130 @@ Metadata-Version: 2.1 Name: swh.loader.mercurial -Version: 0.0.14 +Version: 0.0.16 Summary: Software Heritage Mercurial Loader Home-page: https://forge.softwareheritage.org/diffusion/DLDHG/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN -Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest Project-URL: Funding, https://www.softwareheritage.org/donate Project-URL: Source, https://forge.softwareheritage.org/source/swh-loader-mercurial +Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest Description: swh-loader-mercurial ========================= # Configuration file In usual location for a loader, *{/etc/softwareheritage/ | ~/.swh/ | ~/.config/swh/}loader/hg.yml*: ``` YAML storage: cls: remote args: url: http://localhost:5002/ ``` # Basic use The main entry point to import a Mercurial repository is the `main` function defined in the `swh.loader.mercurial.cli` module: ``` bash python3 -m swh.loader.mercurial.cli ``` If the Python package has been installed via `pip`, you should be able to type: ``` bash user@host:~$ swh-loader-hg --help Usage: swh-loader-hg [OPTIONS] ORIGIN_URL Options: -d, --hg-directory TEXT Path to the hg (local) directory to load from. If unset, the hg repo will ben cloned from the given (origin) url -a, --hg-archive TEXT Path to the hg (local) archive file to load from. -D, --visit-date TEXT Visit date (defaults to now) -l, --log-level [NOTSET|DEBUG|INFO|WARNING|ERROR|CRITICAL] Log level --help Show this message and exit. ``` For example: ``` bash user@host:~$ swh-loader-hg https://www.mercurial-scm.org/repo/hello [...] ``` # From Python From python3's toplevel: ## Remote ``` Python project = 'hello' # remote repository origin_url = 'https://www.mercurial-scm.org/repo/%s' % project # local clone directory = '/home/storage/hg/repo/%s' % project import logging logging.basicConfig(level=logging.DEBUG) from swh.loader.mercurial.tasks import LoadMercurial t = LoadMercurial() t.run(origin_url=origin_url, directory=directory, visit_date='2016-05-03T15:16:32+00:00') ``` ## local directory Only origin, contents, and directories are filled so far. Remaining objects are empty (revision, release, occurrence). ``` Python project = '756015-ipv6' directory = '/home/storage/hg/repo/%s' % project origin_url = 'https://%s.googlecode.com' % project import logging logging.basicConfig(level=logging.DEBUG) from swh.loader.mercurial.tasks import LoadMercurial t = LoadMercurial() t.run(origin_url=origin_url, directory=directory, visit_date='2016-05-03T15:16:32+00:00') ``` ## local archive ``` Python project = '756015-ipv6-source-archive.zip' archive_path = '/home/storage/hg/repo/%s' % project origin_url = 'https://%s-archive.googlecode.com' % project import logging logging.basicConfig(level=logging.DEBUG) from swh.loader.mercurial.tasks import LoadArchiveMercurial t = LoadArchiveMercurial() t.run(origin_url=origin_url, archive_path=archive_path, visit_date='2016-05-03T15:16:32+00:00') ``` Platform: UNKNOWN Classifier: Programming Language :: Python :: 3 Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: OS Independent Classifier: Development Status :: 4 - Beta Description-Content-Type: text/markdown Provides-Extra: testing diff --git a/swh.loader.mercurial.egg-info/SOURCES.txt b/swh.loader.mercurial.egg-info/SOURCES.txt index bcd26bd..76f8730 100644 --- a/swh.loader.mercurial.egg-info/SOURCES.txt +++ b/swh.loader.mercurial.egg-info/SOURCES.txt @@ -1,46 +1,32 @@ -.gitignore -AUTHORS -LICENSE MANIFEST.in Makefile README.md requirements-swh.txt -requirements-test.txt requirements.txt setup.py version.txt -debian/changelog -debian/compat -debian/control -debian/copyright -debian/rules -debian/source/format -docs/.gitignore -docs/Makefile -docs/conf.py -docs/index.rst -docs/_static/.placeholder -docs/_templates/.placeholder swh/__init__.py swh.loader.mercurial.egg-info/PKG-INFO swh.loader.mercurial.egg-info/SOURCES.txt swh.loader.mercurial.egg-info/dependency_links.txt swh.loader.mercurial.egg-info/entry_points.txt swh.loader.mercurial.egg-info/requires.txt swh.loader.mercurial.egg-info/top_level.txt swh/loader/__init__.py swh/loader/mercurial/__init__.py swh/loader/mercurial/archive_extract.py swh/loader/mercurial/bundle20_reader.py swh/loader/mercurial/chunked_reader.py swh/loader/mercurial/cli.py swh/loader/mercurial/converters.py swh/loader/mercurial/loader.py -swh/loader/mercurial/loader_verifier.py swh/loader/mercurial/objects.py swh/loader/mercurial/tasks.py swh/loader/mercurial/tests/__init__.py -swh/loader/mercurial/tests/test_loader.org +swh/loader/mercurial/tests/common.py +swh/loader/mercurial/tests/conftest.py +swh/loader/mercurial/tests/test_converters.py swh/loader/mercurial/tests/test_loader.py +swh/loader/mercurial/tests/test_tasks.py swh/loader/mercurial/tests/resources/hello.tgz swh/loader/mercurial/tests/resources/the-sandbox.tgz \ No newline at end of file diff --git a/swh.loader.mercurial.egg-info/requires.txt b/swh.loader.mercurial.egg-info/requires.txt index 4ec0aae..48d7ccc 100644 --- a/swh.loader.mercurial.egg-info/requires.txt +++ b/swh.loader.mercurial.egg-info/requires.txt @@ -1,15 +1,16 @@ click patool python-dateutil python-hglib retrying sqlitedict +vcversioner swh.core>=0.0.36 -swh.loader.core>=0.0.34 swh.model>=0.0.27 -swh.scheduler>=0.0.19 -swh.storage>=0.0.95 -vcversioner +swh.storage>=0.0.114 +swh.scheduler>=0.0.39 +swh.loader.core>=0.0.37 [testing] -nose +pytest<4 +swh.scheduler[testing] diff --git a/swh/loader/mercurial/archive_extract.py b/swh/loader/mercurial/archive_extract.py index 001c984..1cbe9b0 100644 --- a/swh/loader/mercurial/archive_extract.py +++ b/swh/loader/mercurial/archive_extract.py @@ -1,51 +1,54 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import os import tempfile import patoolib import shutil def tmp_extract(archive, dir=None, prefix=None, suffix=None, log=None, source=None): """Extract an archive to a temporary location with optional logs. Args: archive (string): Absolute path of the archive to be extracted prefix (string): Optional modifier to the temporary storage directory name. (I guess in case something goes wrong and you want to go look?) log (python logging instance): Optional for recording extractions. source (string): Optional source URL of the archive for adding to log messages. Returns: A context manager for a temporary directory that automatically removes itself. See: help(tempfile.TemporaryDirectory) """ logstr = 'From %s - ' % source if log and source else '' + if dir and not os.path.exists(dir): + os.makedirs(dir, exist_ok=True) + archive_base = os.path.basename(archive) if archive_base[0] == '.': package = '.' + archive_base.split('.')[1] else: package = archive_base.split('.')[0] tmpdir = tempfile.mkdtemp(dir=dir, prefix=prefix, suffix=suffix) repo_path = os.path.join(tmpdir, package) try: patoolib.extract_archive(archive, interactive=False, outdir=tmpdir) except Exception as e: if os.path.exists(tmpdir): shutil.rmtree(tmpdir) msg = '%sFailed to uncompress archive %s at %s - %s' % ( logstr, archive_base, repo_path, e) raise ValueError(msg) if log: log.info('%sUncompressing archive %s at %s' % ( logstr, archive_base, repo_path)) return tmpdir diff --git a/swh/loader/mercurial/bundle20_reader.py b/swh/loader/mercurial/bundle20_reader.py index ec24383..c6952ec 100644 --- a/swh/loader/mercurial/bundle20_reader.py +++ b/swh/loader/mercurial/bundle20_reader.py @@ -1,619 +1,624 @@ # Copyright (C) 2017 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information """This document contains code for extracting all of the data from Mercurial version 2 bundle file. It is referenced by bundle20_loader.py """ # ============================================================================= # ============================================================================= # BACKGROUND # ============================================================================= # ============================================================================= # # https://www.mercurial-scm.org/wiki/BundleFormat says: # "The new bundle format design is described on the BundleFormat2 page." # # https://www.mercurial-scm.org/wiki/BundleFormat2#Format_of_the_Bundle2_Container says: # noqa # "The latest description of the binary format can be found as comment in the # Mercurial source code." # # https://www.mercurial-scm.org/repo/hg/file/default/mercurial/help/internals/bundles.txt says: # noqa # "The 'HG20' format is not yet documented here. See the inline comments in # 'mercurial/exchange.py' for now." # # ----------------------------------------------------------------------------- # Avi says: # ----------------------------------------------------------------------------- # # All of the above official(?) statements seem to be quite wrong. # # The mercurial-scm wiki is a cluster#@*& of missing pages, bad links, wrong # information, obsolete information, undecipherable names, and half-started # leavings that only sort of look like content. I don't understand who or what # it's there for. I think that means it's not there for me? # # https://www.mercurial-scm.org/wiki/BundleFormat2#New_header is wrong and # bizarre, and there isn't any other information on the page. # # # https://www.mercurial-scm.org/repo/hg/file/de86a6872d06/mercurial/help/internals/changegroups.txt # noqa # (`hg help internals.changegroups`) is very close to what we need. # It is accurate, current, and thorough. # It describes much of the internal structure, which is super helpful if you # know in advance which info can be trusted, but it doesn't describe any of the # file-level details, including the file headers and that the entire bundle # is broken into overlaid 4KB chunks starting from just after the bundle # header, nor does it describe what any of the component elements are used for, # nor does it explain the meta-message segment in the blob deltas, nor does it # explain the file flags occasionally appended to manifest file hashes. Also it # says: "The [delta data] format is described more fully in 'hg help # internals.bdiff'", which is also wrong. As far as I can tell, that # file has never existed. # # It does however have one potentially extremely useful note buried in the # middle that, in hindsight, could have significant implications for complexity # and performance in future Mercurial loading work. # # It says: "In version 1, the delta is always applied against the previous node # from the changegroup or the first parent if this is the first entry in the # changegroup." # # If the next version of HG support for SWH can reliably get version 1 data, # then it could be implemented entirely without worrying about ballooning # memory utilization, which would shrink the code significantly and probably be # faster too. So maybe HG10 bundles instead of HG20 bundles are superior for # this task? But then I read that servers can optionally disable serving # version 1 content, and I like to think that this loader could eventually # be applied directly to a network stream without an intermediate phase for # cloning and local bundling, so...It seemed like a good idea at the time? # # ----------------------------------------------------------------------------- # Other notes and thoughts: # ----------------------------------------------------------------------------- # 1) # This is a relatively minor detail, but # Mercurial nodes are not content-addressable like Git's are. # # https://www.mercurial-scm.org/wiki/Nodeid explains: "If you modify a file, # commit the change, and then modify it to restore the original contents, the # contents are the same but the history is different, so the file will get a # new nodeid. This history-sensitivity is obtained by calculating the nodeid # from the concatenation of the parent nodeids with the file's contents..." # # The result is that we always have to collect and hash everything at least # once in order to know if we've seen something like it before, because nothing # tells us that the node we're looking at is unique. We can use node ids for # linking disparate elements together (e.g. commit to manifest) but not for # determining whether two elements in the same group are identical in all but # descendency. So there's no way to save time on duplicate hashing. Well... # there is the copied_file blob metadata, but, lol. # # 2) # Most of the code complexity is due to dealing with 'version 2' changegroups, # for which we need to keep track of the entire history of all updates made # to a given file or working directory tree structure, because a revision # delta could be applied over any of the prior revisions all the way back to # rev 0, according to whenever files were branched/merged/uncommitted/etc. For # very large repositories with a lot of churn, this can quickly expand to # require multiple gigabytes of space, possibly exceeding RAM availability if # one desires to keep as much data resident in memory as possible to boost # performance. mozilla-unified, for instance, produces some 2 million+ blobs # (1.6 million+ unique). Nested umpteen subdirectory levels deep, those blobs # balloon into a quantity of directory subtrees that rapidly exceeds an 8GB RAM # laptop's ability to keep them all active without a good amount of care and # pruning. The code here tries to strike a balance between memory utilization # and performance. # # This problem is also referenced in the last paragraph of the previous # section, where potentially this problem wouldn't exist for 'version 1' data # if we can reliably get it. Can we? Either that or not use bundles at all, # which has other costs. # # 3) # If the list of changed files stored by the changesets had indicated which # of those changed files were added or modified and which ones were removed, # this code could be much faster. Right now we have to perform a huge number of # substring replacements (see the apply_revdata method) to produce a complete # file manifest for each commit (as a string!!!) in order to know how to get # the set of removed files from the next delta. We can intuit from every # manifest delta which files were modified or added, but I believe there's no # way to intuit which files were removed without actually having the complete # prior state and without the list of removals being explicitly given. If you # have an explicit list of all the files that were removed for any given commit # changegroup, and you combine that with the delta updates in the manifest # changegroups which detail the set of files that have been added or modified, # then you wouldn't even have to apply any of the string deltas to get a # complete understanding of the set of differences between one manifest and the # next. Not having this effective speed boost is rather unfortunate; it would # require only one extra stored byte per commit to differentiate removals and # would make extracting bundles lightning fast. # ============================================================================ ## import itertools import struct from binascii import unhexlify from collections import OrderedDict from datetime import datetime from .chunked_reader import ChunkedFileReader from .objects import SelectiveCache def unpack(fmt_str, source): """Utility function for fetching the right number of bytes from a stream to satisfy a struct.unpack pattern. args: fmt_str: a struct.unpack string pattern (e.g. '>I' for 4 bytes big-endian) source: any IO object that has a read() method which returns an appropriate sequence of bytes """ ret = struct.unpack(fmt_str, source.read(struct.calcsize(fmt_str))) if len(ret) == 1: return ret[0] return ret class Bundle20Reader(object): """Parser for extracting data from Mercurial Bundle20 files. NOTE: Currently only works on uncompressed HG20 bundles, but checking for COMPRESSION=<2chars> and loading the appropriate stream decompressor at that point would be trivial to add if necessary. args: bundlefile (str): name of the binary repository bundle file cache_filename (str): path to the disk cache used (transited to the SelectiveCache instance) cache_size (int): tuning parameter for the upper RAM limit used by historical data caches. The default is defined in the SelectiveCache class. """ NAUGHT_NODE = b'\x00' * 20 def __init__(self, bundlefile, cache_filename, cache_size=None): self.bundlefile = bundlefile self.cache_filename = cache_filename bfile = open(bundlefile, 'rb', buffering=200*1024*1024) btype = bfile.read(4) # 'HG20' if btype != b'HG20': raise Exception(bundlefile, b'Not an HG20 bundle. First 4 bytes:' + btype) bfile.read(4) # '\x00\x00\x00\x00' self.params = self.read_bundle_header(bfile) # print('PARAMETERS', self.params) self.num_commits = self.params[b'nbchanges'] self.filereader = ChunkedFileReader(bfile) self.cache_size = cache_size self.blobs_offset = None self.changes_offset = self.filereader.tell() self.changes_next_offset = None self.manifests_offset = None self.manifests_next_offset = None self.id_to_info = {} def read_bundle_header(self, bfile): """Parse the file header which describes the format and parameters. See the structure diagram at the top of the file for more insight. args: bfile: bundle file handle with the cursor at the start offset of the content header (the 9th byte in the file) returns: dict of decoded bundle parameters """ unpack('>I', bfile) # header length chg_len = unpack('>B', bfile) # len('CHANGEGROUP') == 11 bfile.read(chg_len) # should say 'CHANGEGROUP' unpack('>I', bfile) # probably \x00\x00\x00\x00 n_mandatory, n_advisory = unpack('>BB', bfile) # parameter counts mandatory_params = [ (key_len, val_len) for key_len, val_len in [unpack('>BB', bfile) for i in range(n_mandatory)] ] advisory_params = [ (key_len, val_len) for key_len, val_len in [unpack('>BB', bfile) for i in range(n_advisory)] ] params = {} for key_len, val_len in mandatory_params+advisory_params: key = unpack('>%ds' % key_len, bfile) val = int(unpack('>%ds' % val_len, bfile)) params[key] = val return params def revdata_iterator(self, bytes_to_read): """A chunk's revdata section is a series of start/end/length/data_delta content updates called RevDiffs that indicate components of a text diff applied to the node's basenode. The sum length of all diffs is the length indicated at the beginning of the chunk at the start of the header. See the structure diagram at the top of the file for more insight. args: bytes_to_read: int total number of bytes in the chunk's revdata yields: (int, int, read iterator) representing a single text diff component """ while bytes_to_read > 0: start_offset = unpack('>I', self.filereader) end_offset = unpack('>I', self.filereader) blocklen = unpack('>I', self.filereader) delta_it = self.filereader.read_iterator(blocklen) bytes_to_read -= (12 + blocklen) yield (start_offset, end_offset, delta_it) # RevDiff def read_chunk_header(self): """The header of a RevChunk describes the id ('node') for the current change, the commit id ('linknode') associated with this change, the parental heritage ('p1' and 'p2'), and the node to which the revdata updates will apply ('basenode'). 'linknode' is the same as 'node' when reading the commit log because any commit is already itself. 'basenode' for a changeset will be NAUGHT_NODE, because changeset chunks include complete information and not diffs. See the structure diagram at the top of the file for more insight. returns: dict of the next delta header """ header = self.filereader.read(100) header = { 'node': header[0:20], 'p1': header[20:40], 'p2': header[40:60], 'basenode': header[60:80], 'linknode': header[80:100] } return header def read_revchunk(self): """Fetch a complete RevChunk. A RevChunk contains the collection of line changes made in a particular update. header['node'] identifies which update. Commits, manifests, and files all have these. Each chunk contains an indicator of the whole chunk size, an update header, and then the body of the update as a series of text diff components. See the structure diagram at the top of the file for more insight. returns: tuple(dict, iterator) of (header, chunk data) if there is another chunk in the group, else None """ size = unpack('>I', self.filereader) - 104 if size >= 0: header = self.read_chunk_header() return (header, self.revdata_iterator(size)) else: return None # NullChunk def extract_commit_metadata(self, data): """Converts the binary commit metadata format into a dict. args: data: bytestring of encoded commit information returns: dict of decoded commit information """ parts, message = data.split(b'\n\n', 1) parts = parts.split(b'\n') commit = {} commit['message'] = message commit['manifest'] = unhexlify(parts[0]) commit['user'] = parts[1] tstamp, tz, *extra = parts[2].split(b' ') commit['time'] = datetime.fromtimestamp(float(tstamp)) commit['time_offset_seconds'] = int(tz) if extra: commit['extra'] = extra[0] commit['changed_files'] = parts[3:] return commit def skip_sections(self, num_sections=1): """Skip past sections quickly. args: num_sections: int number of sections to skip """ for i in range(num_sections): size = unpack('>I', self.filereader) while size >= 104: self.filereader.seek(size - 4, from_current=True) size = unpack('>I', self.filereader) def apply_revdata(self, revdata_it, prev_state): """Compose the complete text body for a change from component deltas. args: revdata_it: output from the revdata_iterator method prev_state: bytestring the base complete text on which the new deltas will be applied returns: (bytestring, list, list) the new complete string and lists of added and removed components (used in manifest processing) """ state = [] added = [] removed = [] next_start = 0 for delta_start, delta_end, rev_diff_it in revdata_it: removed.append(prev_state[delta_start:delta_end]) added.append(b''.join(rev_diff_it)) state.append(prev_state[next_start:delta_start]) state.append(added[-1]) next_start = delta_end state.append(prev_state[next_start:]) state = b''.join(state) return (state, added, removed) def skim_headers(self): """Get all header data from a change group but bypass processing of the contained delta components. yields: output of read_chunk_header method for all chunks in the group """ size = unpack('>I', self.filereader) - 104 while size >= 0: header = self.read_chunk_header() self.filereader.seek(size, from_current=True) yield header size = unpack('>I', self.filereader) - 104 def group_iterator(self): """Bundle sections are called groups. These are composed of one or more revision chunks of delta components. Iterate over all the chunks in a group and hand each one back. yields: see output of read_revchunk method """ revchunk = self.read_revchunk() while revchunk: # A group is terminated by a NullChunk yield revchunk # (header, revdata_iterator) revchunk = self.read_revchunk() def yield_group_objects(self, cache_hints=None, group_offset=None): """Bundles are sectioned into groups: the log of all commits, the log of all manifest changes, and a series of logs of blob changes (one for each file). All groups are structured the same way, as a series of revisions each with a series of delta components. Iterate over the current group and return the completed object data for the current update by applying all of the internal delta components to each prior revision. args: cache_hints: see build_cache_hints (this will be built automatically if not pre-built and passed in) group_offset: int file position of the start of the desired group yields: (dict, bytestring, list, list) the output from read_chunk_header followed by the output from apply_revdata """ if group_offset is not None: self.filereader.seek(group_offset) if cache_hints is None: cache_hints = self.build_cache_hints() data_cache = SelectiveCache(max_size=self.cache_size, cache_hints=cache_hints, filename=self.cache_filename) # Loop over all revisions in the group data = b'' for header, revdata_it in self.group_iterator(): node = header['node'] basenode = header['basenode'] data = data_cache.fetch(basenode) or b'' data, added, removed = self.apply_revdata(revdata_it, data) data_cache.store(node, data) yield (header, data, added, removed) # each RevChunk def extract_meta_from_blob(self, data): """File revision data sometimes begins with a metadata section of dubious value. Strip it off and maybe decode it. It seems to be mostly useless. Why indicate that a file node is a copy of another node? You can already get that information from the delta header. args: data: bytestring of one revision of a file, possibly with metadata embedded at the start returns: (bytestring, dict) of (the blob data, the meta information) """ meta = {} if data.startswith(b'\x01\n'): empty, metainfo, data = data.split(b'\x01\n', 2) metainfo = b'\x01\n' + metainfo + b'\x01\n' if metainfo.startswith(b'copy:'): # direct file copy (?) copyinfo = metainfo.split(b'\n') meta['copied_file'] = copyinfo[0][6:] meta['copied_rev'] = copyinfo[1][9:] elif metainfo.startswith(b'censored:'): # censored revision deltas must be full-replacements (?) meta['censored'] = metainfo else: # no idea meta['text'] = metainfo return data, meta def seek_changelog(self): """Seek to the beginning of the change logs section. """ self.filereader.seek(self.changes_offset) def seek_manifests(self): """Seek to the beginning of the manifests section. """ if self.manifests_offset is None: self.seek_changelog() self.skip_sections(1) # skip past commits self.manifests_offset = self.filereader.tell() else: self.filereader.seek(self.manifests_offset) def seek_filelist(self): """Seek to the beginning of the file changes section. """ if self.blobs_offset is None: self.seek_manifests() self.skip_sections(1) # skip past manifests self.blobs_offset = self.filereader.tell() else: self.filereader.seek(self.blobs_offset) def yield_all_blobs(self): """Gets blob data from the bundle. yields: (bytestring, (bytestring, int, dict)) of (blob data, (file name, start offset of the file within the bundle, node header)) """ self.seek_filelist() # Loop through all files that have commits size = unpack('>I', self.filereader) while size > 0: file_name = self.filereader.read(size-4) file_start_offset = self.filereader.tell() # get all of the blobs for each file for header, data, *_ in self.yield_group_objects(): blob, meta = self.extract_meta_from_blob(data) yield blob, (file_name, file_start_offset, header) size = unpack('>I', self.filereader) def yield_all_changesets(self): """Gets commit data from the bundle. yields: (dict, dict) of (read_chunk_header output, extract_commit_metadata output) """ self.seek_changelog() for header, data, *_ in self.yield_group_objects(): changeset = self.extract_commit_metadata(data) yield (header, changeset) def yield_all_manifest_deltas(self, cache_hints=None): """Gets manifest data from the bundle. In order to process the manifests in a reasonable amount of time, we want to use only the deltas and not the entire manifest at each change, because if we're processing them in sequential order (we are) then we already have the previous state so we only need the changes. args: cache_hints: see build_cache_hints method yields: (dict, dict, dict) of (read_chunk_header output, extract_manifest_elements output on added/modified files, extract_manifest_elements on removed files) """ self.seek_manifests() for header, data, added, removed in self.yield_group_objects( cache_hints=cache_hints ): added = self.extract_manifest_elements(added) removed = self.extract_manifest_elements(removed) yield (header, added, removed) def build_manifest_hints(self): """Just a minor abstraction shortcut for the build_cache_hints method. returns: see build_cache_hints method """ self.seek_manifests() return self.build_cache_hints() def build_cache_hints(self): """The SelectiveCache class that we use in building nodes can accept a set of key counters that makes its memory usage much more efficient. returns: dict of key=a node id, value=the number of times we will need data from that node when building subsequent nodes """ cur_pos = self.filereader.tell() hints = OrderedDict() prev_node = None for header in self.skim_headers(): basenode = header['basenode'] if (basenode != self.NAUGHT_NODE) and (basenode != prev_node): # If the base isn't immediately prior, then cache it once more. hints[basenode] = hints.get(basenode, 0) + 1 prev_node = header['node'] self.filereader.seek(cur_pos) return hints def extract_manifest_elements(self, data): """Parses data that looks like a manifest. In practice we only pass in the bits extracted from the application of a manifest delta describing which files were added/modified or which ones were removed. args: data: either a string or a list of strings that, when joined, - embodies the composition of a manifest. This takes the form - of repetitions of (without the brackets): - b'\x00[flag]\n' ...repeat... - where [flag] may or may not be there depending on whether the - file is specially flagged as executable or something + embodies the composition of a manifest. + + This takes the form + of repetitions of (without the brackets):: + + b'\x00[flag]\\n' ...repeat... + + where ``[flag]`` may or may not be there depending on + whether the file is specially flagged as executable or + something returns: - dict of key=file_path, value=(file_node, permissions) where + dict: ``{file_path: (file_node, permissions), ...}`` where permissions is given according to the flag that optionally exists in the data """ elements = {} if isinstance(data, str): data = data.split(b'\n') else: data = itertools.chain.from_iterable( [chunk.split(b'\n') for chunk in data] ) for line in data: if line != b'': f = line.split(b'\x00') node = f[1] flag_bytes = node[40:] elements[f[0]] = ( unhexlify(node[:40]), b'l' in flag_bytes, b'755' if (b'x' in flag_bytes) else b'644' ) return elements diff --git a/swh/loader/mercurial/loader.py b/swh/loader/mercurial/loader.py index a9a1c8f..ee796b2 100644 --- a/swh/loader/mercurial/loader.py +++ b/swh/loader/mercurial/loader.py @@ -1,531 +1,531 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information """This document contains a SWH loader for ingesting repository data from Mercurial version 2 bundle files. """ # NOTE: The code here does expensive work twice in places because of the # intermediate need to check for what is missing before sending to the database # and the desire to not juggle very large amounts of data. # TODO: Decide whether to also serialize to disk and read back more quickly # from there. Maybe only for very large repos and fast drives. # - Avi import datetime import hglib import os import random import re from dateutil import parser from shutil import rmtree from tempfile import mkdtemp from swh.model import identifiers from swh.model.hashutil import ( MultiHash, hash_to_hex, hash_to_bytes, DEFAULT_ALGORITHMS ) -from swh.loader.core.loader import SWHStatelessLoader +from swh.loader.core.loader import UnbufferedLoader from swh.loader.core.converters import content_for_storage from swh.loader.core.utils import clean_dangling_folders from . import converters from .archive_extract import tmp_extract from .bundle20_reader import Bundle20Reader from .converters import PRIMARY_ALGO as ALGO from .objects import SelectiveCache, SimpleTree TAG_PATTERN = re.compile('[0-9A-Fa-f]{40}') TEMPORARY_DIR_PREFIX_PATTERN = 'swh.loader.mercurial.' HEAD_POINTER_NAME = b'tip' -class HgBundle20Loader(SWHStatelessLoader): +class HgBundle20Loader(UnbufferedLoader): """Mercurial loader able to deal with remote or local repository. """ - CONFIG_BASE_FILENAME = 'loader/hg' + CONFIG_BASE_FILENAME = 'loader/mercurial' ADDITIONAL_CONFIG = { 'bundle_filename': ('str', 'HG20_none_bundle'), - 'reduce_effort': ('bool', True), # default: Try to be smart about time + 'reduce_effort': ('bool', False), 'temp_directory': ('str', '/tmp'), 'cache1_size': ('int', 800*1024*1024), 'cache2_size': ('int', 800*1024*1024), } def __init__(self, logging_class='swh.loader.mercurial.Bundle20Loader'): super().__init__(logging_class=logging_class) self.content_max_size_limit = self.config['content_size_limit'] self.bundle_filename = self.config['bundle_filename'] self.reduce_effort_flag = self.config['reduce_effort'] self.empty_repository = None self.temp_directory = self.config['temp_directory'] self.cache1_size = self.config['cache1_size'] self.cache2_size = self.config['cache2_size'] self.working_directory = None self.bundle_path = None def pre_cleanup(self): """Cleanup potential dangling files from prior runs (e.g. OOM killed tasks) """ clean_dangling_folders(self.temp_directory, pattern_check=TEMPORARY_DIR_PREFIX_PATTERN, log=self.log) def cleanup(self): """Clean temporary working directory """ if self.bundle_path and os.path.exists(self.bundle_path): self.log.debug('Cleanup up working bundle %s' % self.bundle_path) os.unlink(self.bundle_path) if self.working_directory and os.path.exists(self.working_directory): self.log.debug('Cleanup up working directory %s' % ( self.working_directory, )) rmtree(self.working_directory) def get_heads(self, repo): """Read the closed branches heads (branch, bookmarks) and returns a dict with key the branch_name (bytes) and values the tuple (pointer nature (bytes), mercurial's node id (bytes)). Those needs conversion to swh-ids. This is taken care of in get_revisions. """ b = {} for _, node_hash_id, pointer_nature, branch_name, *_ in repo.heads(): b[branch_name] = ( pointer_nature, hash_to_bytes(node_hash_id.decode())) bookmarks = repo.bookmarks() if bookmarks and bookmarks[0]: for bookmark_name, _, target_short in bookmarks[0]: target = repo[target_short].node() b[bookmark_name] = (None, hash_to_bytes(target.decode())) return b def prepare_origin_visit(self, *, origin_url, visit_date, **kwargs): self.origin_url = origin_url self.origin = {'url': self.origin_url, 'type': 'hg'} if isinstance(visit_date, str): # visit_date can be string or datetime visit_date = parser.parse(visit_date) self.visit_date = visit_date def prepare(self, *, origin_url, visit_date, directory=None): """Prepare the necessary steps to load an actual remote or local repository. To load a local repository, pass the optional directory parameter as filled with a path to a real local folder. To load a remote repository, pass the optional directory parameter as None. Args: origin_url (str): Origin url to load visit_date (str/datetime): Date of the visit directory (str/None): The local directory to load """ self.branches = {} self.tags = [] self.releases = {} self.node_2_rev = {} if not directory: # remote repository self.working_directory = mkdtemp( prefix=TEMPORARY_DIR_PREFIX_PATTERN, suffix='-%s' % os.getpid(), dir=self.temp_directory) os.makedirs(self.working_directory, exist_ok=True) self.hgdir = self.working_directory self.log.debug('Cloning %s to %s' % ( self.origin['url'], self.hgdir)) hglib.clone(source=self.origin['url'], dest=self.hgdir) else: # local repository self.working_directory = None self.hgdir = directory self.bundle_path = os.path.join(self.hgdir, self.bundle_filename) self.log.debug('Bundling at %s' % self.bundle_path) with hglib.open(self.hgdir) as repo: self.heads = self.get_heads(repo) repo.bundle(bytes(self.bundle_path, 'utf-8'), all=True, type=b'none-v2') self.cache_filename1 = os.path.join( self.hgdir, 'swh-cache-1-%s' % ( hex(random.randint(0, 0xffffff))[2:], )) self.cache_filename2 = os.path.join( self.hgdir, 'swh-cache-2-%s' % ( hex(random.randint(0, 0xffffff))[2:], )) try: self.br = Bundle20Reader(bundlefile=self.bundle_path, cache_filename=self.cache_filename1, cache_size=self.cache1_size) - except FileNotFoundError as e: + except FileNotFoundError: # Empty repository! Still a successful visit targeting an # empty snapshot self.log.warn('%s is an empty repository!' % self.hgdir) self.empty_repository = True else: self.reduce_effort = set() if self.reduce_effort_flag: now = datetime.datetime.now(tz=datetime.timezone.utc) if (now - self.visit_date).days > 1: # Assuming that self.visit_date would be today for # a new visit, treat older visit dates as # indication of wanting to skip some processing # effort. for header, commit in self.br.yield_all_changesets(): ts = commit['time'].timestamp() if ts < self.visit_date.timestamp(): self.reduce_effort.add(header['node']) def has_contents(self): return not self.empty_repository def has_directories(self): return not self.empty_repository def has_revisions(self): return not self.empty_repository def has_releases(self): return not self.empty_repository def fetch_data(self): """Fetch the data from the data source.""" pass def get_contents(self): """Get the contents that need to be loaded.""" # NOTE: This method generates blobs twice to reduce memory usage # without generating disk writes. self.file_node_to_hash = {} hash_to_info = {} self.num_contents = 0 contents = {} missing_contents = set() for blob, node_info in self.br.yield_all_blobs(): self.num_contents += 1 file_name = node_info[0] header = node_info[2] length = len(blob) if header['linknode'] in self.reduce_effort: algorithms = [ALGO] else: algorithms = DEFAULT_ALGORITHMS h = MultiHash.from_data(blob, hash_names=algorithms) content = h.digest() content['length'] = length blob_hash = content[ALGO] self.file_node_to_hash[header['node']] = blob_hash if header['linknode'] in self.reduce_effort: continue hash_to_info[blob_hash] = node_info contents[blob_hash] = content missing_contents.add(blob_hash) if file_name == b'.hgtags': # https://www.mercurial-scm.org/wiki/GitConcepts#Tag_model # overwrite until the last one self.tags = (t for t in blob.split(b'\n') if t != b'') if contents: missing_contents = set( self.storage.content_missing( list(contents.values()), key_hash=ALGO ) ) # Clusters needed blobs by file offset and then only fetches the # groups at the needed offsets. focs = {} # "file/offset/contents" for blob_hash in missing_contents: _, file_offset, header = hash_to_info[blob_hash] focs.setdefault(file_offset, {}) focs[file_offset][header['node']] = blob_hash hash_to_info = None for offset, node_hashes in sorted(focs.items()): for header, data, *_ in self.br.yield_group_objects( group_offset=offset ): node = header['node'] if node in node_hashes: blob, meta = self.br.extract_meta_from_blob(data) content = contents.pop(node_hashes[node], None) if content: content['data'] = blob yield content_for_storage( content, log=self.log, max_content_size=self.content_max_size_limit, origin_id=self.origin_id ) def load_directories(self): """This is where the work is done to convert manifest deltas from the repository bundle into SWH directories. """ self.mnode_to_tree_id = {} cache_hints = self.br.build_manifest_hints() def tree_size(t): return t.size() self.trees = SelectiveCache(cache_hints=cache_hints, size_function=tree_size, filename=self.cache_filename2, max_size=self.cache2_size) tree = SimpleTree() for header, added, removed in self.br.yield_all_manifest_deltas( cache_hints ): node = header['node'] basenode = header['basenode'] tree = self.trees.fetch(basenode) or tree # working tree for path in removed.keys(): tree = tree.remove_tree_node_for_path(path) for path, info in added.items(): file_node, is_symlink, perms_code = info tree = tree.add_blob( path, self.file_node_to_hash[file_node], is_symlink, perms_code ) if header['linknode'] in self.reduce_effort: self.trees.store(node, tree) else: new_dirs = [] self.mnode_to_tree_id[node] = tree.hash_changed(new_dirs) self.trees.store(node, tree) yield header, tree, new_dirs def get_directories(self): """Compute directories to load """ dirs = {} self.num_directories = 0 for _, _, new_dirs in self.load_directories(): for d in new_dirs: self.num_directories += 1 dirs[d['id']] = d missing_dirs = list(dirs.keys()) if missing_dirs: missing_dirs = self.storage.directory_missing(missing_dirs) for _id in missing_dirs: yield dirs[_id] dirs = {} def get_revisions(self): """Compute revisions to load """ revisions = {} self.num_revisions = 0 for header, commit in self.br.yield_all_changesets(): if header['node'] in self.reduce_effort: continue self.num_revisions += 1 date_dict = identifiers.normalize_timestamp( int(commit['time'].timestamp()) ) author_dict = converters.parse_author(commit['user']) if commit['manifest'] == Bundle20Reader.NAUGHT_NODE: directory_id = SimpleTree().hash_changed() else: directory_id = self.mnode_to_tree_id[commit['manifest']] extra_meta = [] extra = commit.get('extra') if extra: for e in extra.split(b'\x00'): k, v = e.split(b':', 1) k = k.decode('utf-8') extra_meta.append([k, v]) revision = { 'author': author_dict, 'date': date_dict, 'committer': author_dict, 'committer_date': date_dict, 'type': 'hg', 'directory': directory_id, 'message': commit['message'], 'metadata': { 'node': hash_to_hex(header['node']), 'extra_headers': [ ['time_offset_seconds', str(commit['time_offset_seconds']).encode('utf-8')], ] + extra_meta }, 'synthetic': False, 'parents': [] } p1 = self.node_2_rev.get(header['p1']) p2 = self.node_2_rev.get(header['p2']) if p1: revision['parents'].append(p1) if p2: revision['parents'].append(p2) revision['id'] = hash_to_bytes( identifiers.revision_identifier(revision) ) self.node_2_rev[header['node']] = revision['id'] revisions[revision['id']] = revision # Converts heads to use swh ids self.heads = { branch_name: (pointer_nature, self.node_2_rev[node_id]) for branch_name, (pointer_nature, node_id) in self.heads.items() } missing_revs = revisions.keys() if missing_revs: missing_revs = set( self.storage.revision_missing(list(missing_revs)) ) for r in missing_revs: yield revisions[r] self.mnode_to_tree_id = None def _read_tag(self, tag, split_byte=b' '): node, *name = tag.split(split_byte) name = split_byte.join(name) return node, name def get_releases(self): """Get the releases that need to be loaded.""" self.num_releases = 0 releases = {} missing_releases = [] for t in self.tags: self.num_releases += 1 node, name = self._read_tag(t) node = node.decode() node_bytes = hash_to_bytes(node) if not TAG_PATTERN.match(node): self.log.warn('Wrong pattern (%s) found in tags. Skipping' % ( node, )) continue if node_bytes not in self.node_2_rev: self.log.warn('No matching revision for tag %s ' '(hg changeset: %s). Skipping' % (name.decode(), node)) continue tgt_rev = self.node_2_rev[node_bytes] release = { 'name': name, 'target': tgt_rev, 'target_type': 'revision', 'message': None, 'metadata': None, 'synthetic': False, 'author': {'name': None, 'email': None, 'fullname': b''}, 'date': None } id_hash = hash_to_bytes( identifiers.release_identifier(release)) release['id'] = id_hash missing_releases.append(id_hash) releases[id_hash] = release self.releases[name] = id_hash if missing_releases: missing_releases = set( self.storage.release_missing(missing_releases)) for _id in missing_releases: yield releases[_id] def get_snapshot(self): """Get the snapshot that need to be loaded.""" branches = {} for name, (pointer_nature, target) in self.heads.items(): branches[name] = {'target': target, 'target_type': 'revision'} if pointer_nature == HEAD_POINTER_NAME: branches[b'HEAD'] = {'target': name, 'target_type': 'alias'} for name, target in self.releases.items(): branches[name] = {'target': target, 'target_type': 'release'} snap = { 'id': None, 'branches': branches, } snap['id'] = identifiers.identifier_to_bytes( identifiers.snapshot_identifier(snap)) return snap def get_fetch_history_result(self): """Return the data to store in fetch_history.""" return { 'contents': self.num_contents, 'directories': self.num_directories, 'revisions': self.num_revisions, 'releases': self.num_releases, } class HgArchiveBundle20Loader(HgBundle20Loader): """Mercurial loader for repository wrapped within archives. """ def __init__(self): super().__init__( logging_class='swh.loader.mercurial.HgArchiveBundle20Loader') self.temp_dir = None def prepare(self, *, origin_url, archive_path, visit_date): self.temp_dir = tmp_extract(archive=archive_path, dir=self.temp_directory, prefix=TEMPORARY_DIR_PREFIX_PATTERN, suffix='.dump-%s' % os.getpid(), log=self.log, source=origin_url) repo_name = os.listdir(self.temp_dir)[0] directory = os.path.join(self.temp_dir, repo_name) super().prepare(origin_url=origin_url, visit_date=visit_date, directory=directory) def cleanup(self): if self.temp_dir and os.path.exists(self.temp_dir): rmtree(self.temp_dir) super().cleanup() diff --git a/swh/loader/mercurial/loader_verifier.py b/swh/loader/mercurial/loader_verifier.py deleted file mode 100644 index e29f52f..0000000 --- a/swh/loader/mercurial/loader_verifier.py +++ /dev/null @@ -1,248 +0,0 @@ -# Copyright (C) 2017-2018 The Software Heritage developers -# See the AUTHORS file at the top-level directory of this distribution -# License: GNU General Public License version 3, or any later version -# See top-level LICENSE file for more information - -import click -import code -import datetime -import hglib -import logging -import os -import random -import sys -import time - -from binascii import hexlify, unhexlify - -from swh.model.hashutil import MultiHash - -from .loader import HgBundle20Loader -from .converters import PRIMARY_ALGO as ALGO -from .objects import SimpleTree - - -class HgLoaderValidater(HgBundle20Loader): - def generate_all_blobs(self, validate=True, frequency=1): - logging.debug('GENERATING BLOBS') - i = 0 - start = time.time() - u = set() - for blob, node_info in self.br.yield_all_blobs(): - filename = node_info[0] - header = node_info[2] - i += 1 - - hashes = MultiHash.from_data(blob, hash_names=set([ALGO])).digest() - bhash = hashes[ALGO] - self.file_node_to_hash[header['node']] = bhash - - u.update([bhash]) - - if validate: - if random.random() < frequency: - self.validate_blob(filename, header, blob) - - if i % 10000 == 0: - logging.debug(i) - - logging.debug('\nFOUND %s BLOBS' % i) - logging.debug('FOUND: %s UNIQUE BLOBS' % len(u)) - logging.debug('ELAPSED: %s' % (time.time()-start)) - - def validate_blob(self, filename, header, blob): - if not self.hg: - self.hg = hglib.open(self.hgdir) - - data = bytes(blob) - - filepath = os.path.join(self.hg.root(), bytes(filename)) - linknode = hexlify(header['linknode']) - cat_contents = self.hg.cat([filepath], rev=linknode) - - if cat_contents != data: - logging.debug('INTERNAL ERROR ERROR ERROR ERROR') - logging.debug(filename) - logging.debug(header) - logging.debug('-----') - logging.debug(cat_contents) - logging.debug('---- vs ----') - logging.debug(data) - code.interact(local=dict(globals(), **locals())) - quit() - else: - logging.debug('v', end='') - - def generate_all_trees(self, validate=True, frequency=1): - logging.debug('GENERATING MANIFEST TREES') - - c = 0 - n = 0 - u = set() - - start = time.time() - validated = 0 - - for header, tree, new_dirs in self.load_directories(): - if validate and (c >= validated) and (random.random() < frequency): - self.validate_tree(tree, header, c) - - for d in new_dirs: - u.add(d['id']) - - c += 1 - n += len(new_dirs) - - logging.debug('.', end='') - if c % 20 == 0: - sys.stdout.flush() - if c % 10000 == 0: - logging.debug(c) - - logging.debug('\nFOUND: %s COMMIT MANIFESTS' % c) - logging.debug('FOUND: %s NEW DIRS' % n) - logging.debug('FOUND: %s UNIQUE DIRS' % len(u)) - logging.debug('ELAPSED: %s' % (time.time()-start)) - - def validate_tree(self, tree, header, i): - if not self.hg: - self.hg = hglib.open(self.hgdir) - - commit_id = header['linknode'] - if len(commit_id) == 20: - commit_id = hexlify(commit_id) - - base_tree = SimpleTree() - base_files = list(self.hg.manifest(rev=commit_id)) - bfiles = sorted([f[4] for f in base_files]) - - for p in base_files: - base_tree.add_blob( - p[4], self.file_node_to_hash[unhexlify(p[0])], p[3], p[1] - ) - base_tree.hash_changed() - - files = sorted(list(tree.flatten().keys())) - - if tree != base_tree: - logging.debug('validating rev: %s commit: %s' % (i, commit_id)) - logging.debug('validating files: %s %s INVALID TREE' % ( - len(files), len(base_files))) - - def so1(a): - keys = [k['name'] for k in a['entries']] - return b''.join(sorted(keys)) - - tree_dirs = [d for d in tree.yield_swh_directories()] - base_dirs = [d for d in base_tree.yield_swh_directories()] - tree_dirs.sort(key=so1) - base_dirs.sort(key=so1) - - # for i in range(len(tree_dirs)): - # if tree_dirs[i] != base_dirs[i]: - # logging.debug(i) - # code.interact(local=dict(globals(), **locals())) - - logging.debug('Program will quit after your next Ctrl-D') - code.interact(local=dict(globals(), **locals())) - quit() - else: - logging.debug('v') - - def generate_all_commits(self, validate=True, frequency=1): - i = 0 - start = time.time() - for rev in self.get_revisions(): - logging.debug('.', end='') - i += 1 - if i % 20 == 0: - sys.stdout.flush() - - logging.debug('') - logging.debug('\nFOUND: %s COMMITS' % i) - logging.debug('ELAPSED: %s' % (time.time()-start)) - - def runtest(self, hgdir, validate_blobs=False, validate_trees=False, - frequency=1.0, test_iterative=False): - """HgLoaderValidater().runtest('/home/avi/SWH/mozilla-unified') - - """ - self.origin_id = 'test' - - dt = datetime.datetime.now(tz=datetime.timezone.utc) - if test_iterative: - dt = dt - datetime.timedelta(10) - - hgrepo = None - if (hgdir.lower().startswith('http:') - or hgdir.lower().startswith('https:')): - hgrepo, hgdir = hgdir, hgrepo - - self.hgdir = hgdir - - try: - logging.debug('preparing') - self.prepare(origin_url=hgrepo, visit_date=dt, directory=hgdir) - - self.file_node_to_hash = {} - - # self.generate_all_blobs(validate=validate_blobs, - # frequency=frequency) - - # self.generate_all_trees(validate=validate_trees, frequency=frequency) - # self.generate_all_commits() - logging.debug('getting contents') - cs = 0 - for c in self.get_contents(): - cs += 1 - pass - - logging.debug('getting directories') - ds = 0 - for d in self.get_directories(): - ds += 1 - pass - - revs = 0 - logging.debug('getting revisions') - for rev in self.get_revisions(): - revs += 1 - pass - - logging.debug('getting releases') - rels = 0 - for rel in self.get_releases(): - rels += 1 - logging.debug(rel) - - self.visit = 'foo' - logging.debug('getting snapshot') - o = self.get_snapshot() - logging.debug('Snapshot: %s' % o) - - finally: - self.cleanup() - - logging.info('final count: cs %s ds %s revs %s rels %s' % ( - cs, ds, revs, rels)) - - -@click.command() -@click.option('--verbose', is_flag=True, default=False) -@click.option('--validate-frequency', default=0.001, type=click.FLOAT) -@click.option('--test-iterative', default=False, type=click.BOOL) -@click.argument('repository-url', required=1) -def main(verbose, validate_frequency, test_iterative, repository_url): - logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) - while repository_url[-1] == '/': - repository_url = repository_url[:-1] - - HgLoaderValidater().runtest( - repository_url, - validate_blobs=True, validate_trees=True, - frequency=validate_frequency, - test_iterative=test_iterative) - - -if __name__ == '__main__': - main() diff --git a/swh/loader/mercurial/tasks.py b/swh/loader/mercurial/tasks.py index 6e2703d..ed70ac8 100644 --- a/swh/loader/mercurial/tasks.py +++ b/swh/loader/mercurial/tasks.py @@ -1,43 +1,35 @@ # Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information -from swh.scheduler.task import Task +from celery import current_app as app from .loader import HgBundle20Loader, HgArchiveBundle20Loader -class LoadMercurial(Task): +@app.task(name=__name__ + '.LoadMercurial') +def load_mercurial(origin_url, directory=None, visit_date=None): """Mercurial repository loading - """ - task_queue = 'swh_loader_mercurial' - - def run_task(self, *, origin_url, visit_date=None, directory=None): - """Import a mercurial tarball into swh. - - Args: see :func:`DepositLoader.load`. + Import a mercurial tarball into swh. - """ - loader = HgBundle20Loader() - loader.log = self.log - return loader.load(origin_url=origin_url, - directory=directory, - visit_date=visit_date) + Args: see :func:`DepositLoader.load`. + """ + loader = HgBundle20Loader() + return loader.load(origin_url=origin_url, + directory=directory, + visit_date=visit_date) -class LoadArchiveMercurial(Task): - task_queue = 'swh_loader_mercurial_archive' - - def run_task(self, *, origin_url, archive_path, visit_date): - """Import a mercurial tarball into swh. - Args: see :func:`DepositLoader.load`. +@app.task(name=__name__ + '.LoadArchiveMercurial') +def load_archive_mercurial(origin_url, archive_path, visit_date=None): + """Import a mercurial tarball into swh. - """ - loader = HgArchiveBundle20Loader() - loader.log = self.log - return loader.load(origin_url=origin_url, - archive_path=archive_path, - visit_date=visit_date) + Args: see :func:`DepositLoader.load`. + """ + loader = HgArchiveBundle20Loader() + return loader.load(origin_url=origin_url, + archive_path=archive_path, + visit_date=visit_date) diff --git a/swh/loader/mercurial/tests/common.py b/swh/loader/mercurial/tests/common.py new file mode 100644 index 0000000..f24cac7 --- /dev/null +++ b/swh/loader/mercurial/tests/common.py @@ -0,0 +1,63 @@ +# Copyright (C) 2018 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +from swh.loader.mercurial.loader import ( + HgBundle20Loader, HgArchiveBundle20Loader +) + + +_LOADER_TEST_CONFIG = { + 'bundle_filename': 'HG20_none_bundle', + 'cache1_size': 838860800, + 'cache2_size': 838860800, + 'content_packet_size': 100000, + 'content_packet_size_bytes': 1073741824, + 'content_size_limit': 104857600, + 'directory_packet_size': 25000, + 'log_db': 'dbname=softwareheritage-log', + 'occurrence_packet_size': 100000, + 'reduce_effort': False, + 'release_packet_size': 100000, + 'revision_packet_size': 100000, + 'save_data': False, + 'save_data_path': '', + 'send_contents': True, + 'send_directories': True, + 'send_occurrences': True, + 'send_releases': True, + 'send_revisions': True, + 'send_snapshot': True, + 'storage': {'args': {}, 'cls': 'memory'}, + 'temp_directory': '/tmp/swh.loader.mercurial' +} + + +class BaseHgLoaderMemoryStorage: + """The base mercurial loader to test. + + Mixin behavior changed to: + - use an in-memory storage + - not use the default configuration loading mechanism + + At the end of the tests, you can make sure you have the rights + objects. + + """ + def __init__(self): + super().__init__() + self.origin_id = 1 + self.visit = 1 + + def parse_config_file(self, *args, **kwargs): + return _LOADER_TEST_CONFIG + + +class HgLoaderMemoryStorage(BaseHgLoaderMemoryStorage, HgBundle20Loader): + pass + + +class HgArchiveLoaderMemoryStorage(BaseHgLoaderMemoryStorage, + HgArchiveBundle20Loader): + pass diff --git a/swh/loader/mercurial/tests/conftest.py b/swh/loader/mercurial/tests/conftest.py new file mode 100644 index 0000000..d1dcb10 --- /dev/null +++ b/swh/loader/mercurial/tests/conftest.py @@ -0,0 +1,10 @@ +import pytest + +from swh.scheduler.tests.conftest import * # noqa + + +@pytest.fixture(scope='session') +def celery_includes(): + return [ + 'swh.loader.mercurial.tasks', + ] diff --git a/swh/loader/mercurial/tests/test_converters.py b/swh/loader/mercurial/tests/test_converters.py new file mode 100644 index 0000000..b3d50e7 --- /dev/null +++ b/swh/loader/mercurial/tests/test_converters.py @@ -0,0 +1,76 @@ +# Copyright (C) 2018 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +import unittest + +from swh.loader.mercurial import converters + + +class TestParseAuthorConverters(unittest.TestCase): + def test_parse_author_no_email(self): + self.assertIsNone(converters.parse_author(None)) + + def test_parse_author_no_bracket(self): + actual_author = converters.parse_author(b'someone') + + self.assertEqual(actual_author, { + 'name': None, + 'email': None, + 'fullname': b'someone' + }) + + def test_parse_author_2(self): + actual_author = converters.parse_author(b'something wicked') + + self.assertEqual(actual_author, { + 'name': None, + 'email': None, + 'fullname': b'something >wicked' + }) + + def test_parse_author_4(self): + actual_author = converters.parse_author(b'something <') + + self.assertEqual(actual_author, { + 'name': b'something', + 'email': None, + 'fullname': b'something <' + }) + + def test_parse_author_5(self): + actual_author = converters.parse_author(b'') + + self.assertEqual(actual_author, { + 'name': None, + 'email': b'only', + 'fullname': b'' + }) + + def test_parse_author_6(self): + actual_author = converters.parse_author(b' ') + + self.assertEqual(actual_author, { + 'name': b' ', + 'email': b'something', + 'fullname': b' ' + }) + + def test_parse_author_normal(self): + actual_author = converters.parse_author(b'someone ') + + self.assertEqual(actual_author, { + 'name': b'someone', + 'email': b'awesome', + 'fullname': b'someone ' + }) diff --git a/swh/loader/mercurial/tests/test_loader.org b/swh/loader/mercurial/tests/test_loader.org deleted file mode 100644 index cfd7c8f..0000000 --- a/swh/loader/mercurial/tests/test_loader.org +++ /dev/null @@ -1,121 +0,0 @@ -#+title: Where the loader test data comes from - -Mercurial repositories are archived within the folder -swh/loader/mercurial/tests/resources. They contain mercurial -repository. - -The following demonstrates the commands executed from within the -repository to retrieve information. - -* the-sandbox - -Archive: the-sandbox.tgz - -** branches - -Listing of branches and their tip: -#+BEGIN_SRC sh -$ hg branches -develop 57:76cc0882284d -default 2:2f13849f14f5 (inactive) -#+END_SRC - -** Changesets - -#+BEGIN_SRC sh -$ for i in {0..57}; do hg checkout $i > /dev/null; echo $i $(swh-hashtree --ignore '.hg' --path .); done -0 e2e117569b086ceabeeedee4acd95f35298d4553 -1 9cd8160c67ac4b0bc97e2e2cd918a580425167d3 -2 180bd57623a7c2c47a8c43514a5f4d903503d0aa -3 180bd57623a7c2c47a8c43514a5f4d903503d0aa -4 180bd57623a7c2c47a8c43514a5f4d903503d0aa -5 180bd57623a7c2c47a8c43514a5f4d903503d0aa -6 180bd57623a7c2c47a8c43514a5f4d903503d0aa -7 180bd57623a7c2c47a8c43514a5f4d903503d0aa -8 180bd57623a7c2c47a8c43514a5f4d903503d0aa -9 180bd57623a7c2c47a8c43514a5f4d903503d0aa -10 180bd57623a7c2c47a8c43514a5f4d903503d0aa -11 180bd57623a7c2c47a8c43514a5f4d903503d0aa -12 180bd57623a7c2c47a8c43514a5f4d903503d0aa -13 180bd57623a7c2c47a8c43514a5f4d903503d0aa -14 180bd57623a7c2c47a8c43514a5f4d903503d0aa -15 180bd57623a7c2c47a8c43514a5f4d903503d0aa -16 180bd57623a7c2c47a8c43514a5f4d903503d0aa -17 180bd57623a7c2c47a8c43514a5f4d903503d0aa -18 180bd57623a7c2c47a8c43514a5f4d903503d0aa -19 180bd57623a7c2c47a8c43514a5f4d903503d0aa -20 180bd57623a7c2c47a8c43514a5f4d903503d0aa -21 180bd57623a7c2c47a8c43514a5f4d903503d0aa -22 180bd57623a7c2c47a8c43514a5f4d903503d0aa -23 180bd57623a7c2c47a8c43514a5f4d903503d0aa -24 180bd57623a7c2c47a8c43514a5f4d903503d0aa -25 180bd57623a7c2c47a8c43514a5f4d903503d0aa -26 180bd57623a7c2c47a8c43514a5f4d903503d0aa -27 180bd57623a7c2c47a8c43514a5f4d903503d0aa -28 180bd57623a7c2c47a8c43514a5f4d903503d0aa -29 180bd57623a7c2c47a8c43514a5f4d903503d0aa -30 180bd57623a7c2c47a8c43514a5f4d903503d0aa -31 180bd57623a7c2c47a8c43514a5f4d903503d0aa -32 180bd57623a7c2c47a8c43514a5f4d903503d0aa -33 180bd57623a7c2c47a8c43514a5f4d903503d0aa -34 180bd57623a7c2c47a8c43514a5f4d903503d0aa -35 180bd57623a7c2c47a8c43514a5f4d903503d0aa -36 180bd57623a7c2c47a8c43514a5f4d903503d0aa -37 180bd57623a7c2c47a8c43514a5f4d903503d0aa -38 180bd57623a7c2c47a8c43514a5f4d903503d0aa -39 180bd57623a7c2c47a8c43514a5f4d903503d0aa -40 180bd57623a7c2c47a8c43514a5f4d903503d0aa -41 180bd57623a7c2c47a8c43514a5f4d903503d0aa -42 180bd57623a7c2c47a8c43514a5f4d903503d0aa -43 180bd57623a7c2c47a8c43514a5f4d903503d0aa -44 180bd57623a7c2c47a8c43514a5f4d903503d0aa -45 180bd57623a7c2c47a8c43514a5f4d903503d0aa -46 180bd57623a7c2c47a8c43514a5f4d903503d0aa -47 180bd57623a7c2c47a8c43514a5f4d903503d0aa -48 180bd57623a7c2c47a8c43514a5f4d903503d0aa -49 180bd57623a7c2c47a8c43514a5f4d903503d0aa -50 180bd57623a7c2c47a8c43514a5f4d903503d0aa -51 180bd57623a7c2c47a8c43514a5f4d903503d0aa -52 180bd57623a7c2c47a8c43514a5f4d903503d0aa -53 180bd57623a7c2c47a8c43514a5f4d903503d0aa -54 180bd57623a7c2c47a8c43514a5f4d903503d0aa -55 180bd57623a7c2c47a8c43514a5f4d903503d0aa -56 180bd57623a7c2c47a8c43514a5f4d903503d0aa -57 180bd57623a7c2c47a8c43514a5f4d903503d0aa -#+END_SRC - -Note: swh-hashtree is a cli tool defined in swh-model/bin/swh-hashtree - -* hello - -Archive: hello.tgz - -** branches - -#+BEGIN_SRC sh -$ hg branches -default 1:82e55d328c8c -#+END_SRC - -** tags - -I added a tag to have some more data to load (1st repository has no tags): -#+BEGIN_SRC sh -$ hg tags -tip 2:b985ae4a07e1 -0.1 1:82e55d328c8c -#+END_SRC - -#+BEGIN_SRC sh -$ cat .hgtags -82e55d328c8ca4ee16520036c0aaace03a5beb65 0.1 -#+END_SRC - -** Changesets - -#+BEGIN_SRC sh -$ for i in {0..1}; do hg checkout $i > /dev/null; echo $i $(swh-hashtree --ignore '.hg' --path .); done -0 43d727f2f3f2f7cb3b098ddad1d7038464a4cee2 -1 b3f85f210ff86d334575f64cb01c5bf49895b63e -2 8f2be433c945384c85920a8e60f2a68d2c0f20fb -#+END_SRC diff --git a/swh/loader/mercurial/tests/test_loader.py b/swh/loader/mercurial/tests/test_loader.py index 38c2d02..0210ad1 100644 --- a/swh/loader/mercurial/tests/test_loader.py +++ b/swh/loader/mercurial/tests/test_loader.py @@ -1,259 +1,249 @@ # Copyright (C) 2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import os -from nose.tools import istest +from unittest.mock import patch -from swh.loader.core.tests import BaseLoaderTest, LoaderNoStorage -from swh.loader.mercurial.loader import HgBundle20Loader - - -class MockStorage: - """A mixin inhibited storage overriding *_missing methods. Those are - called from within the mercurial loader. - - Rationale: Need to take control of the current behavior prior - to refactor it. The end game is to remove this when we will - have tests ok. - - """ - def content_missing(self, contents, key_hash='sha1'): - return [c[key_hash] for c in contents] - - def directory_missing(self, directories): - return directories - - def release_missing(self, releases): - return releases - - def revision_missing(self, revisions): - return revisions +from swh.loader.core.tests import BaseLoaderTest +from .common import HgLoaderMemoryStorage, HgArchiveLoaderMemoryStorage class BaseHgLoaderTest(BaseLoaderTest): """Mixin base loader test to prepare the mercurial repository to uncompress, load and test the results. This sets up """ - def setUp(self, archive_name='the-sandbox.tgz', filename='the-sandbox'): + def setUp(self, loader=HgLoaderMemoryStorage, + archive_name='the-sandbox.tgz', filename='the-sandbox', + uncompress_archive=True): super().setUp(archive_name=archive_name, filename=filename, prefix_tmp_folder_name='swh.loader.mercurial.', - start_path=os.path.dirname(__file__)) - + start_path=os.path.dirname(__file__), + uncompress_archive=uncompress_archive) + self.loader = loader() + self.storage = self.loader.storage -class HgLoaderNoStorage(LoaderNoStorage, HgBundle20Loader): - """The mercurial loader to test. - Its behavior has been changed to: - - not use any persistence (no storage, or for now a passthrough - storage with no filtering) - - not use the default configuration loading - - At the end of the tests, you can make sure you have the rights - objects. - - """ - ADDITIONAL_CONFIG = { - 'reduce_effort': ('bool', False), # FIXME: This needs to be - # checked (in production - # for now, this is not - # deployed.) - 'temp_directory': ('str', '/tmp/swh.loader.mercurial'), - 'cache1_size': ('int', 800*1024*1024), - 'cache2_size': ('int', 800*1024*1024), - 'bundle_filename': ('str', 'HG20_none_bundle'), - } - - def __init__(self): - super().__init__() - self.origin_id = 1 - self.visit = 1 - self.storage = MockStorage() - - -class LoaderITest1(BaseHgLoaderTest): +class LoaderTestT1(BaseHgLoaderTest): """Load a mercurial repository without release """ - def setUp(self): - super().setUp() - self.loader = HgLoaderNoStorage() - - @istest - def load(self): + def test_load(self): """Load a repository with multiple branches results in 1 snapshot """ # when self.loader.load( origin_url=self.repo_url, visit_date='2016-05-03 15:16:32+00', directory=self.destination_path) # then self.assertCountContents(2) self.assertCountDirectories(3) self.assertCountReleases(0) self.assertCountRevisions(58) tip_revision_develop = 'a9c4534552df370f43f0ef97146f393ef2f2a08c' tip_revision_default = '70e750bb046101fdced06f428e73fee471509c56' # same from rev 3 onward directory_hash = '180bd57623a7c2c47a8c43514a5f4d903503d0aa' # cf. test_loader.org for explaining from where those hashes # come from expected_revisions = { # revision hash | directory hash # noqa 'aafb69fd7496ca617f741d38c40808ff2382aabe': 'e2e117569b086ceabeeedee4acd95f35298d4553', # noqa 'b6932cb7f59e746899e4804f3d496126d1343615': '9cd8160c67ac4b0bc97e2e2cd918a580425167d3', # noqa tip_revision_default: directory_hash, '18012a93d5aadc331c468dac84b524430f4abc19': directory_hash, 'bec4c0a31b0b2502f44f34aeb9827cd090cca621': directory_hash, '5f4eba626c3f826820c4475d2d81410759ec911b': directory_hash, 'dcba06661c607fe55ec67b1712d153b69f65e38c': directory_hash, 'c77e776d22548d47a8d96463a3556172776cd59b': directory_hash, '61d762d65afb3150e2653d6735068241779c1fcf': directory_hash, '40def747398c76ceec1bd248e3a6cb2a52e22dc5': directory_hash, '6910964416438ca8d1698f6295871d727c4d4851': directory_hash, 'be44d5e6cc66580f59c108f8bff5911ee91a22e4': directory_hash, 'c4a95d5097519dedac437fddf0ef775136081241': directory_hash, '32eb0354a660128e205bf7c3a84b46040ef70d92': directory_hash, 'dafa445964230e808148db043c126063ea1dc9b6': directory_hash, 'a41e2a548ba51ee47f22baad8e88994853d3e2f5': directory_hash, 'dc3e3ab7fe257d04769528e5e17ad9f1acb44659': directory_hash, 'd2164061453ecb03d4347a05a77db83f706b8e15': directory_hash, '34192ceef239b8b72141efcc58b1d7f1676a18c9': directory_hash, '2652147529269778757d96e09aaf081695548218': directory_hash, '4d640e8064fe69b4c851dfd43915c431e80c7497': directory_hash, 'c313df50bfcaa773dcbe038d00f8bd770ba997f8': directory_hash, '769db00b34b9e085dc699c8f1550c95793d0e904': directory_hash, '2973e5dc9568ac491b198f6b7f10c44ddc04e0a3': directory_hash, 'be34b8c7857a6c04e41cc06b26338d8e59cb2601': directory_hash, '24f45e41637240b7f9e16d2791b5eacb4a406d0f': directory_hash, '62ff4741eac1821190f6c2cdab7c8a9d7db64ad0': directory_hash, 'c346f6ff7f42f2a8ff867f92ab83a6721057d86c': directory_hash, 'f2afbb94b319ef5d60823859875284afb95dcc18': directory_hash, '4e2dc6d6073f0b6d348f84ded52f9143b10344b9': directory_hash, '31cd7c5f669868651c57e3a2ba25ac45f76fa5cf': directory_hash, '25f5b27dfa5ed15d336188ef46bef743d88327d4': directory_hash, '88b80615ed8561be74a700b92883ec0374ddacb0': directory_hash, '5ee9ea92ed8cc1737b7670e39dab6081c64f2598': directory_hash, 'dcddcc32740d2de0e1403e21a5c4ed837b352992': directory_hash, '74335db9f45a5d1c8133ff7a7db5ed7a8d4a197b': directory_hash, 'cb36b894129ca7910bb81c457c72d69d5ff111bc': directory_hash, 'caef0cb155eb6c55215aa59aabe04a9c702bbe6a': directory_hash, '5017ce0b285351da09a2029ea2cf544f79b593c7': directory_hash, '17a62618eb6e91a1d5d8e1246ccedae020d3b222': directory_hash, 'a1f000fb8216838aa2a120738cc6c7fef2d1b4d8': directory_hash, '9f82d95bd3edfb7f18b1a21d6171170395ea44ce': directory_hash, 'a701d39a17a9f48c61a06eee08bd9ac0b8e3838b': directory_hash, '4ef794980f820d44be94b2f0d53eb34d4241638c': directory_hash, 'ddecbc16f4c916c39eacfcb2302e15a9e70a231e': directory_hash, '3565e7d385af0745ec208d719e469c2f58be8e94': directory_hash, 'c875bad563a73a25c5f3379828b161b1441a7c5d': directory_hash, '94be9abcf9558213ff301af0ecd8223451ce991d': directory_hash, '1ee770fd10ea2d8c4f6e68a1dbe79378a86611e0': directory_hash, '553b09724bd30d9691b290e157b27a73e2d3e537': directory_hash, '9e912851eb64e3a1e08fbb587de7a4c897ce5a0a': directory_hash, '9c9e0ff08f215a5a5845ce3dbfc5b48c8050bdaf': directory_hash, 'db9e625ba90056304897a94c92e5d27bc60f112d': directory_hash, '2d4a801c9a9645fcd3a9f4c06418d8393206b1f3': directory_hash, 'e874cd5967efb1f45282e9f5ce87cc68a898a6d0': directory_hash, 'e326a7bbb5bc00f1d8cacd6108869dedef15569c': directory_hash, '3ed4b85d30401fe32ae3b1d650f215a588293a9e': directory_hash, tip_revision_develop: directory_hash, } - self.assertRevisionsOk(expected_revisions) + self.assertRevisionsContain(expected_revisions) self.assertCountSnapshots(1) expected_snapshot = { 'id': '3b8fe58e467deb7597b12a5fd3b2c096b8c02028', 'branches': { 'develop': { 'target': tip_revision_develop, 'target_type': 'revision' }, 'default': { 'target': tip_revision_default, 'target_type': 'revision' }, 'HEAD': { 'target': 'develop', 'target_type': 'alias', } } } - self.assertSnapshotOk(expected_snapshot) + self.assertSnapshotEqual(expected_snapshot) self.assertEqual(self.loader.load_status(), {'status': 'eventful'}) self.assertEqual(self.loader.visit_status(), 'full') -class LoaderITest2(BaseHgLoaderTest): - """Load a mercurial repository with release - - """ - def setUp(self): - super().setUp(archive_name='hello.tgz', filename='hello') - self.loader = HgLoaderNoStorage() - - @istest - def load(self): - """Load a repository with tags results in 1 snapshot - - """ - # when - self.loader.load( - origin_url=self.repo_url, - visit_date='2016-05-03 15:16:32+00', - directory=self.destination_path) - +class CommonHgLoaderData: + def assert_data_ok(self): # then self.assertCountContents(3) self.assertCountDirectories(3) self.assertCountReleases(1) self.assertCountRevisions(3) tip_release = '515c4d72e089404356d0f4b39d60f948b8999140' - self.assertReleasesOk([tip_release]) + self.assertReleasesContain([tip_release]) tip_revision_default = 'c3dbe4fbeaaa98dd961834e4007edb3efb0e2a27' # cf. test_loader.org for explaining from where those hashes # come from expected_revisions = { # revision hash | directory hash # noqa '93b48d515580522a05f389bec93227fc8e43d940': '43d727f2f3f2f7cb3b098ddad1d7038464a4cee2', # noqa '8dd3db5d5519e4947f035d141581d304565372d2': 'b3f85f210ff86d334575f64cb01c5bf49895b63e', # noqa tip_revision_default: '8f2be433c945384c85920a8e60f2a68d2c0f20fb', } - self.assertRevisionsOk(expected_revisions) + self.assertRevisionsContain(expected_revisions) self.assertCountSnapshots(1) expected_snapshot = { 'id': 'd35668e02e2ba4321dc951cd308cf883786f918a', 'branches': { 'default': { 'target': tip_revision_default, 'target_type': 'revision' }, '0.1': { 'target': tip_release, 'target_type': 'release' }, 'HEAD': { 'target': 'default', 'target_type': 'alias', } } } - self.assertSnapshotOk(expected_snapshot) + self.assertSnapshotEqual(expected_snapshot) self.assertEqual(self.loader.load_status(), {'status': 'eventful'}) self.assertEqual(self.loader.visit_status(), 'full') + + +class LoaderTest2(BaseHgLoaderTest, CommonHgLoaderData): + """Load a mercurial repository with release + + """ + def setUp(self): + super().setUp(archive_name='hello.tgz', filename='hello') + + def test_load(self): + """Load a repository with tags results in 1 snapshot + + """ + # when + self.loader.load( + origin_url=self.repo_url, + visit_date='2016-05-03 15:16:32+00', + directory=self.destination_path) + + self.assert_data_ok() + + +class ArchiveLoaderTest(BaseHgLoaderTest, CommonHgLoaderData): + """Load a mercurial repository archive with release + + """ + def setUp(self): + super().setUp(loader=HgArchiveLoaderMemoryStorage, + archive_name='hello.tgz', filename='hello', + uncompress_archive=False) + + def test_load(self): + """Load a mercurial repository archive with tags results in 1 snapshot + + """ + # when + self.loader.load( + origin_url=self.repo_url, + visit_date='2016-05-03 15:16:32+00', + archive_path=self.destination_path) + + self.assert_data_ok() + + @patch('swh.loader.mercurial.archive_extract.patoolib') + def test_load_with_failure(self, mock_patoo): + mock_patoo.side_effect = ValueError + + # when + r = self.loader.load( + origin_url=self.repo_url, + visit_date='2016-05-03 15:16:32+00', + archive_path=self.destination_path) + + self.assertEqual(r, {'status': 'failed'}) + self.assertCountContents(0) + self.assertCountDirectories(0) + self.assertCountRevisions(0) + self.assertCountReleases(0) + self.assertCountSnapshots(0) diff --git a/swh/loader/mercurial/tests/test_tasks.py b/swh/loader/mercurial/tests/test_tasks.py new file mode 100644 index 0000000..09c5517 --- /dev/null +++ b/swh/loader/mercurial/tests/test_tasks.py @@ -0,0 +1,41 @@ +# Copyright (C) 2018 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +from unittest.mock import patch + + +@patch('swh.loader.mercurial.loader.HgBundle20Loader.load') +def test_loader(mock_loader, swh_app, celery_session_worker): + mock_loader.return_value = {'status': 'eventful'} + + res = swh_app.send_task( + 'swh.loader.mercurial.tasks.LoadMercurial', + kwargs=dict(origin_url='origin_url', directory='/some/repo', + visit_date='now')) + assert res + res.wait() + assert res.successful() + + assert res.result == {'status': 'eventful'} + mock_loader.assert_called_once_with( + origin_url='origin_url', visit_date='now', directory='/some/repo') + + +@patch('swh.loader.mercurial.loader.HgArchiveBundle20Loader.load') +def test_archive_loader(mock_loader, swh_app, celery_session_worker): + mock_loader.return_value = {'status': 'uneventful'} + + res = swh_app.send_task( + 'swh.loader.mercurial.tasks.LoadArchiveMercurial', + ('another_url', '/some/tar.tgz', 'now')) + assert res + res.wait() + assert res.successful() + + assert res.result == {'status': 'uneventful'} + mock_loader.assert_called_once_with( + origin_url='another_url', + archive_path='/some/tar.tgz', + visit_date='now') diff --git a/version.txt b/version.txt index df2f276..937ba29 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -v0.0.14-0-gef75fd6 \ No newline at end of file +v0.0.16-0-gb184299 \ No newline at end of file